Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Swap/SwapAPI.swift3// Description: Price discovery and same-network swaps (services/api/src/swap.ts, swap-exec.ts, swap-exec-sol.ts): assets,4// providers, statistics, quotes (one answer or a live stream), what is executable where, and the preparation of a5// firm swap — KyberSwap on the EVM networks the server lists, Jupiter on Solana — verified before any passkey.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011/** POST /swap/proposals body. */12public struct SwapRequest: Codable, Sendable, Hashable {13 public let network: String14 /** Asset ids of the registry (`native` or the contract / mint), both on `network`. */15 public let fromAsset: String16 public let toAsset: String17 /** Decimal text in whole units of the source asset. */18 public let amount: String19 /** 1…300. */20 public let slippageBps: Int21 /** The reference of the route displayed (`SwapRoute.quoteReference`). Without it the server compares nothing. */22 public let quote: QuoteRef?23 public init(network: String, fromAsset: String, toAsset: String, amount: String, slippageBps: Int = 50, quote: QuoteRef? = nil) {24 self.network = network; self.fromAsset = fromAsset; self.toAsset = toAsset; self.amount = amount; self.slippageBps = slippageBps; self.quote = quote25 }26}2728public struct SwapAPI: SwapOperationAPI {29 public let client: APIClient30 public init(_ client: APIClient) { self.client = client }3132 // MARK: reads3334 /** Every asset of the swap graph (the wallet registry). */35 public func assets() async throws -> [SwapAsset] {36 struct R: Decodable, Sendable { let assets: [SwapAsset] }37 return try await client.get("/swap/assets", as: R.self).assets38 }39 /** The providers, their health, which need a key that is not configured, and WHICH ONES EXECUTE — as the server states it. */40 public func providers() async throws -> SwapProviders { try await client.get("/swap/providers") }41 public func stats() async throws -> SwapStats { try await client.get("/swap/stats") }42 /** Where same-network swaps are executable today. */43 public func execution() async throws -> SwapExecutionInfo { try await client.get("/swap/execution") }4445 // MARK: quotes (price discovery: signs nothing, prepares nothing)4647 /** Every route, once all providers answered or timed out. */48 public func quote(_ r: SwapQuoteRequest) async throws -> SwapSearch { try await client.post("/swap/quote", body: r) }4950 /**51 Routes as each provider answers, then `done` with the final ranking. The stream ends after `done` or `failed`; cancel the52 consuming task to close it (the server allows a few concurrent streams and answers `429 too_many_streams` beyond).53 */54 public func quoteStream(_ r: SwapQuoteRequest, transport: EventStreamTransport = URLSessionEventStreamTransport()) -> AsyncThrowingStream<SwapQuoteEvent, Error> {55 let raw = client.serverSentEvents("/swap/quote/stream", query: ["from": r.from, "to": r.to, "amount": r.amount, "slippageBps": String(r.slippageBps)], transport: transport)56 return AsyncThrowingStream { continuation in57 let task = Task {58 do {59 for try await e in raw {60 let event = try Self.event(e)61 continuation.yield(event)62 switch event { case .done, .failed: continuation.finish(); return; default: break }63 }64 continuation.finish()65 } catch { continuation.finish(throwing: error) }66 }67 continuation.onTermination = { _ in task.cancel() }68 }69 }7071 /** Decode one event of the stream. An event whose data cannot be read is an error, never a silently dropped route. */72 public static func event(_ e: SwapSSEvent) throws -> SwapQuoteEvent {73 func decode<T: Decodable>(_ type: T.Type) throws -> T {74 do { return try APICoding.decoder().decode(T.self, from: Data(e.data.utf8)) }75 catch { throw APIError(status: 200, code: "decoding", message: "unexpected `\(e.name)` event in the quote stream") }76 }77 switch e.name {78 case "start": return .start(try decode(SwapSearchStart.self))79 case "route": return .route(try decode(SwapRoute.self))80 case "provider": return .provider(try decode(SwapProviderAnswer.self))81 case "done": return .done(try decode(SwapSearch.self))82 case "error":83 struct Failure: Decodable { let code: String?; let message: String? }84 let f = try decode(Failure.self)85 return .failed(code: f.code ?? "internal", message: f.message ?? "the quote search failed")86 default: return .unknown(name: e.name, data: try? APICoding.decoder().decode(JSONValue.self, from: Data(e.data.utf8)))87 }88 }8990 // MARK: execution9192 /**93 Prepare a firm swap and VERIFY it: the intent must be a swap of exactly the requested amount of the requested asset on the94 requested network, from the wallet to the wallet, to the requested asset, through the provider of the quote displayed, with a95 guaranteed minimum that satisfies `minimumOutput`; its hash must be the challenge. Throws `QuoteMoved` when the price moved96 below the minimum displayed (nothing was prepared), `ApprovalError.unsupported` when the server does not return the intent.9798 - Parameters:99 - accounts: the wallet's own addresses (`WalletAPI.accounts()`), read before preparing.100 - idempotencyKey: chosen by the caller and REUSED when the answer was lost: the same key answers the same proposal.101 */102 public func prepare(_ r: SwapRequest, accounts: Accounts, minimumOutput: MinimumOutputRule = .asPrepared, idempotencyKey: String, now: Date = Date()) async throws -> PreparedOperation {103 let a: SwapVerification.Answer = try await SwapVerification.post(client, "/swap/proposals", body: r, idempotencyKey: idempotencyKey)104 var e = OperationExpectation(kind: .swap, network: r.network, asset: r.fromAsset,105 amount: .exactly(try SwapVerification.requestedUnits(r.amount, decimals: a.proposal.decimals, kind: .swap)))106 e.toAsset = r.toAsset; e.provider = r.quote?.provider; e.minimumOutput = SwapVerification.floor(minimumOutput, quote: r.quote)107 return try await SwapVerification.verifyOrWithdraw(client, a, expecting: e, accounts: accounts, now: now)108 }109}110