SPB Git

spb/os-vault Public

Self-custody, multi-chain crypto wallet for macOS. One recovery phrase, six chain families, zero API keys — nothing leaves your Mac.

Swift 96% Shell 3.4% Makefile 0.6%
2.0 KB · 69 lines swift
Raw Blame History
1import Foundation23public protocol APIClientRequest: Encodable {4    /// Expected entity with this request. Used to decode response to5    /// Can use AnyDecodable6    associatedtype Entity: Decodable7    init(method: String, params: [Encodable])8}910public struct JSONRPCAPIClientRequest<Entity: Decodable>: APIClientRequest {11    public init(method: String, params: [Encodable]) {12        self.method = method13        self.params = params14    }1516    public let id = UUID().uuidString17    public let method: String18    public let jsonrpc = "2.0"19    public let params: [Encodable]2021    enum CodingKeys: String, CodingKey {22        case id23        case method24        case jsonrpc25        case params26    }2728    public func encode(to encoder: Encoder) throws {29        var container = encoder.container(keyedBy: CodingKeys.self)30        try container.encode(id, forKey: .id)31        try container.encode(method, forKey: .method)32        try container.encode(jsonrpc, forKey: .jsonrpc)33        let wrappedDict = params.map(EncodableWrapper.init(wrapped:))34        try container.encode(wrappedDict, forKey: .params)35    }36}3738/// Encoder used to encode request in able to use with the transport39public protocol APIClientRequestEncoder {40    associatedtype RequestType: APIClientRequest41    init(request: RequestType)42    init(requests: [RequestType])4344    func encoded() throws -> Data45}4647public enum JSONRPCRequestEncoderError: Error {48    case cantEncodeValue49}5051/// JSONRPCRequestEncoder encodes requests of type RequestAPI according to JSONRPC rules52public class JSONRPCRequestEncoder: APIClientRequestEncoder {53    public typealias RequestType = JSONRPCAPIClientRequest<AnyDecodable>5455    private var requests: AnyEncodable // either array or single RequestType5657    public required init(request: RequestType) {58        requests = AnyEncodable(request)59    }6061    public required init(requests: [RequestType]) {62        self.requests = AnyEncodable(requests)63    }6465    public func encoded() throws -> Data {66        try JSONEncoder().encode(requests)67    }68}69