Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Swap/SwapModels.swift3// Description: Models of price discovery and same-network swaps (services/api/src/swap.ts, swap-exec.ts, swap-exec-sol.ts,4// prepare-common.ts, exec-status.ts): assets, providers and what they can do AS THE API SERVES IT, routes and their5// normalized card, the quote stream's events, the swap section of a proposal, the unified execution status, the6// quote record and the `quote_moved` refusal. Amounts are base-unit strings + the server's display text.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112/** A string code of the server kept verbatim: a value this version does not know is shown as it is, never mapped to a known one. */13public protocol ServerCode: RawRepresentable, Codable, Sendable, Hashable where RawValue == String {14 init(rawValue: String)15}16public extension ServerCode {17 init(_ raw: String) { self.init(rawValue: raw) }18}1920/** An asset of the swap graph (`viewAsset` / `assetView`). `name` and `native` are served by /swap/assets only. */21public struct SwapAsset: Codable, Sendable, Hashable, Identifiable {22 /** `<network>:<asset>`, the asset in lower case on EVM networks: the form /swap/quote and /plans expect. */23 public let key: String24 public let network: String25 public let networkName: String?26 public let asset: String27 public let symbol: String28 public let name: String?29 public let decimals: Int30 public let native: Bool?31 /** THORChain capability rows only: true when the asset may be the INPUT of a native swap. */32 public let source: Bool?33 public var id: String { key }34 public var ref: AssetRef { AssetRef(network: network, asset: asset) }35}3637public struct SwapProviderInfo: Codable, Sendable, Hashable, Identifiable {38 public struct Capabilities: Codable, Sendable, Hashable {39 public let networks: [String]40 public let crossChain: Bool41 /** True when the provider needs an API key; `configured` says whether the server has it. Not configured = never asked. */42 public let needsKey: Bool43 public let configured: Bool44 public let kinds: [String]45 public let docs: String?46 }47 public let id: String48 public let name: String?49 public let enabled: Bool50 /** Circuit breaker: `closed`, `open`, `half_open`. */51 public let state: String?52 public let calls: Int?53 public let failures: Int?54 public let timeouts: Int?55 public let lastError: String?56 /** Unix milliseconds. */57 public let lastOkAt: Double?58 public let p50: Double?59 public let p95: Double?60 public let p99: Double?61 public let capabilities: Capabilities?62}6364/** GET /swap/providers. Who EXECUTES is the server's statement (`executors`); every other provider is a comparison source. */65public struct SwapProviders: Codable, Sendable, Hashable {66 public let executionEnabled: Bool67 public let providers: [SwapProviderInfo]68 /** Providers that exist in the server's code but are not asked because their API key is not configured. */69 public let needsKey: [String]70 public let executors: [String]71 public func isExecutor(_ provider: String) -> Bool { executors.contains(provider) }72}7374/** GET /swap/stats: seven days of provider answers. */75public struct SwapStats: Codable, Sendable, Hashable {76 public struct Row: Codable, Sendable, Hashable { public let provider: String; public let calls: Int?; public let ok: Int?; public let quotes: Int?; public let p50: Double?; public let p95: Double?; public let p99: Double? }77 public let window: String78 public let providers: [Row]79}8081/** GET /swap/execution: where same-network swaps are EXECUTED today, as served (KyberSwap networks; Jupiter on Solana). */82public struct SwapExecutionInfo: Codable, Sendable, Hashable {83 public struct Solana: Codable, Sendable, Hashable {84 public let provider: String85 /** The label Jupiter's licence requires next to any use of this route ("Jupiter (Metis)"). */86 public let label: String87 public let networks: [String]88 public let program: String?89 public let programData: String?90 public let lastDeploySlot: Int?91 }92 public let enabled: Bool93 public let provider: String94 /** Networks on which the pinned KyberSwap router is reviewed and enabled. */95 public let networks: [String]96 public let router: String?97 public let solana: Solana?9899 /** The provider that executes a same-network swap on `network`, or nil: route comparison only there. */100 public func executor(on network: String) -> String? {101 guard enabled else { return nil }102 if let s = solana, s.networks.contains(network) { return s.provider }103 return networks.contains(network) ? provider : nil104 }105}106107public struct RiskLevel: ServerCode { public let rawValue: String; public init(rawValue: String) { self.rawValue = rawValue }108 public static let low = RiskLevel("low"), medium = RiskLevel("medium"), high = RiskLevel("high") }109110/** One fee line, in the asset it is charged in. `usd` is a valuation aid (nil without a price), never an amount. */111public struct SwapFee: Codable, Sendable, Hashable {112 /** `network`, `protocol`, `provider`, `bridge`, `affiliate`. */113 public let kind: String114 public let network: String?115 public let symbol: String?116 public let amount: String?117 public let display: String?118 public let estimated: Bool?119 /** True when the output is already net of this fee. */120 public let includedInOutput: Bool?121 public let usd: Double?122}123124/** The normalized route card (v11): the same object for every route. A figure the provider did not give is nil. */125public struct RouteCard: Codable, Sendable, Hashable {126 public struct FeeGroup: Codable, Sendable, Hashable { public let items: [SwapFee]; public let usd: Double?; public let bps: Double?; public let estimated: Bool?; public let includedInOutput: Bool? }127 public struct Step: Codable, Sendable, Hashable { public let kind: String; public let network: String; public let toNetwork: String; public let provider: String; public let descriptionCode: String? }128 public let routeId: String129 public let providers: [String]130 public let fingerprint: String131 public let amountIn: String132 public let estimatedOut: String133 public let minimumOut: String134 public let networkFee: FeeGroup?135 public let protocolFee: FeeGroup?136 /** The tolerance the quote was asked with, basis points. */137 public let toleranceBps: Int138 public let effectiveSlippageBps: Double?139 public let etaSeconds: Double?140 public let riskLevel: RiskLevel?141 public let riskFlags: [String]?142 public let steps: [Step]?143 /** Unix milliseconds: when the oldest leg of the quote was received, and when it must no longer be used. */144 public let quotedAt: Int145 public let expiresAt: Int146 public let executable: Bool147 public let executor: String?148 /** Why the wallet cannot execute the route (a code the UI translates); nil when it can. */149 public let reasonCode: String?150 public let quoteId: String?151 public let fromSymbol: String?152 public let toSymbol: String?153 public let amountInDisplay: String?154 public let estimatedOutDisplay: String?155 public let minimumOutDisplay: String?156}157158/** One route of a quote response (`viewRoute` of swap.ts). */159public struct SwapRoute: Codable, Sendable, Hashable, Identifiable {160 public struct Execution: Codable, Sendable, Hashable { public let via: String; /** CCTP only: `standard` or `fast`. */ public let speed: String? }161 public struct Executability: Codable, Sendable, Hashable {162 /** `verified` (the signer rebuilds or verifies every value-moving field), `opaque`, `quote_only`. */163 public let `class`: String164 public let code: String?165 public let reason: String?166 }167 public struct Valuation: Codable, Sendable, Hashable { public let inUsd: Double?; public let outUsd: Double?; public let minOutUsd: Double?; public let extraFeesUsd: Double?; public let unpricedFees: Double?; public let netUsd: Double? }168 public struct RiskFlag: Codable, Sendable, Hashable { public let code: String; public let level: RiskLevel; public let detail: String?; public let params: [String: JSONValue]? }169 public struct Risk: Codable, Sendable, Hashable { public let level: RiskLevel; public let score: Double?; public let flags: [RiskFlag] }170 public struct Contract: Codable, Sendable, Hashable { public let network: String; public let address: String; public let role: String }171 public struct Step: Codable, Sendable, Hashable { public let kind: String; public let provider: String; public let from: SwapAsset; public let to: SwapAsset; public let via: [String]?; public let contracts: [Contract]? }172173 public let id: String174 public let providers: [String]175 public let path: [SwapAsset]176 public let card: RouteCard?177 /** Who executes this route, as the SERVER states it (never inferred by the client); nil = comparison only. */178 public let executor: String?179 public let fingerprint: String?180 public let quotedAt: Int?181 public let amountIn: String?182 public let tags: [String]?183 public let pareto: Bool?184 /** The wallet can execute this route itself today (signer-verified on a reviewed router / program / vault). */185 public let executable: Bool186 public let exec: Execution?187 public let amountOut: String188 public let minAmountOut: String189 public let amountOutDisplay: String190 public let minAmountOutDisplay: String191 public let estimatedSeconds: Double?192 public let expiresAt: Int?193 public let executability: Executability?194 public let valuation: Valuation?195 public let risk: Risk?196 public let atomic: Bool?197 /** nil = the provider does not say. */198 public let refundable: Bool?199 public let priceImpactBps: Double?200 public let steps: [Step]?201 public let fees: [SwapFee]?202203 /** The executor stated by the server for an executable route (`executor`; `exec.via` is the same fact in the older field). */204 public var statedExecutor: String? { executable ? executor ?? exec?.via : nil }205206 /** The facts the route's fingerprint commits to, rebuilt from the route itself. nil when a needed field is absent. */207 public var quoteFacts: QuoteFacts? {208 guard let first = path.first, let last = path.last, path.count >= 2, let amountIn = amountIn ?? card?.amountIn, let tolerance = card?.toleranceBps else { return nil }209 return QuoteFacts(provider: providers.joined(separator: "+"), fromKey: first.key, toKey: last.key, amountIn: amountIn, slippageBps: tolerance, amountOut: amountOut, minAmountOut: minAmountOut)210 }211 /** True when the served fingerprint is the fingerprint of the figures served with it. */212 public var fingerprintIsConsistent: Bool { fingerprint != nil && quoteFacts?.fingerprint == fingerprint }213214 /**215 The reference to send back when THIS route is prepared: built only from served values, and only when the served fingerprint216 matches the displayed figures. nil for a route the wallet does not execute, and for a CCTP route of the stream (it is quoted217 with the swap tolerance; a CCTP transfer is prepared with the reference of its /bridge/quote option instead).218 */219 public var quoteReference: QuoteRef? {220 guard let via = statedExecutor, via != "cctp", fingerprintIsConsistent, let fingerprint, let provider = providers.first, let quotedAt = quotedAt ?? card?.quotedAt else { return nil }221 let ref = QuoteRef(id: id, provider: provider, fingerprint: fingerprint, amountOut: amountOut, minAmountOut: minAmountOut, quotedAt: quotedAt)222 return ref.isWellFormed ? ref : nil223 }224}225226public struct SwapProviderAnswer: Codable, Sendable, Hashable {227 public let provider: String228 /** `no_route`, `skipped`, `error`. */229 public let status: String230 /** `disabled`, `not_configured`, `timeout`, `rate_limited`, `invalid_quote`, … */231 public let code: String?232 public let ms: Double?233}234235/** POST /swap/quote and the `done` event of the stream. */236public struct SwapSearch: Codable, Sendable, Hashable {237 /** Routing mode (`best_price`, `fastest`, `balanced`) → route id. */238 public let best: [String: String]239 /** False when no enabled provider even advertises this pair (as opposed to "no liquidity right now"). */240 public let reachable: Bool241 public let ms: Double?242 /** The executors the wallet has for this PAIR, from the server's pinned tables. Empty = nothing here can be executed. */243 public let executors: [String]244 public let routes: [SwapRoute]245 public let providers: [SwapProviderAnswer]246}247248public struct SwapSearchStart: Codable, Sendable, Hashable {249 public let from: SwapAsset250 public let to: SwapAsset251 public let amountIn: String252 public let slippageBps: Int253 public let reachable: Bool254 public let executors: [String]255}256257/** One event of GET /swap/quote/stream. The stream ends after `done` or `failed`. */258public enum SwapQuoteEvent: Sendable, Hashable {259 case start(SwapSearchStart)260 case route(SwapRoute)261 case provider(SwapProviderAnswer)262 case done(SwapSearch)263 /** The server's `error` event: the search failed; nothing was prepared. */264 case failed(code: String, message: String)265 /** An event name this version does not know, with its data untouched. */266 case unknown(name: String, data: JSONValue?)267}268269public struct SwapQuoteRequest: Codable, Sendable, Hashable {270 /** Asset keys (`SwapAsset.key`). */271 public let from: String272 public let to: String273 /** Decimal text in whole units of the source asset. */274 public let amount: String275 /** 1…500. */276 public let slippageBps: Int277 public init(from: String, to: String, amount: String, slippageBps: Int = 50) { self.from = from; self.to = to; self.amount = amount; self.slippageBps = slippageBps }278}279280// MARK: - what a proposal carries281282/** The `swap` section of a proposal (`view()` of transfers.ts). Present on same-network swaps and on THORChain swaps. */283public struct SwapSection: Codable, Sendable, Hashable {284 public let provider: String285 public let toAsset: String286 public let toSymbol: String287 public let slippageBps: Int?288 /** An exact-amount token approval precedes the swap (a second transaction, covered by the same passkey approval). */289 public let needsApproval: Bool?290 public let simulated: Bool?291 public let expectedOut: String292 public let expectedOutDisplay: String293 public let minOut: String294 public let minOutDisplay: String295 /** What was actually received, read from the chain once the swap is final. nil until then — never the expected amount. */296 public let received: String?297 public let receivedDisplay: String?298 public let approvalTxid: String?299 /** `pending`, `sent`, `confirmed`; nil when no approval transaction exists. */300 public let approvalState: String?301 /** Provider-specific facts of the review sheet (Solana: licence label, venues, priority fee, token-account rent). */302 public let detail: JSONValue?303}304305public struct ExecState: ServerCode { public let rawValue: String; public init(rawValue: String) { self.rawValue = rawValue }306 public static let pending = ExecState("pending"), awaitingApproval = ExecState("awaiting_approval"), signing = ExecState("signing"), broadcast = ExecState("broadcast")307 public static let confirming = ExecState("confirming"), confirmed = ExecState("confirmed"), failed = ExecState("failed"), refunded = ExecState("refunded"), unknown = ExecState("unknown") }308309/** One step of the unified execution status (exec-status.ts). Timestamps the wallet does not record are nil. */310public struct ExecutionStep: Codable, Sendable, Hashable, Identifiable {311 public let id: String312 /** `approval`, `send`, `swap`, `burn`, `attestation`, `mint`, `deposit`, `observation`, `outbound`, `order`. */313 public let kind: String314 /** The network the step happens on; `circle` / `thorchain` for the two off-chain waits. */315 public let network: String316 public let provider: String?317 public let state: ExecState318 public let txid: String?319 public let explorer: String?320 public let startedAt: Date?321 public let endedAt: Date?322 /** Why the step is waiting or ended (a hold code, an error code). */323 public let code: String?324}325326/** The unified execution status of a proposal or of a plan leg. */327public struct ExecutionStatus: Codable, Sendable, Hashable {328 public let kind: String329 /** A failure or a refund wins, then the first step that is not finished; `confirmed` only when EVERY step is. */330 public let state: ExecState331 public let steps: [ExecutionStep]332 public let updatedAt: Date?333 /** True only when every step is confirmed — for a bridge that includes the mint on the destination, for a THORChain swap the outbound seen by the wallet. */334 public var isComplete: Bool { state == .confirmed && !steps.isEmpty && steps.allSatisfy { $0.state == .confirmed } }335 /** The step the execution is at: the first one that is not confirmed. */336 public var currentStep: ExecutionStep? { steps.first { $0.state != .confirmed } }337}338339/** The quote the owner was shown next to the firm figures of the preparation (`QuoteRecord` + display fields). */340public struct QuoteRecord: Codable, Sendable, Hashable {341 public let id: String342 public let provider: String343 public let fingerprint: String344 public let quotedOut: String345 public let quotedMinOut: String346 public let quotedAt: Int?347 public let firmOut: String348 public let firmMinOut: String349 /** Signed deviation of the firm expected output against the quoted one (negative = worse than shown; a loss is rounded away from zero). */350 public let deviationBps: Int351 public let quotedOutDisplay: String?352 public let firmOutDisplay: String?353}354355/**356 `409 quote_moved`: the firm route is below the minimum the owner was shown. NOTHING WAS PREPARED. Carries the quoted and the fresh357 figures so that the screen can say so and offer the fresh quote.358 */359public struct QuoteMoved: Error, Sendable, Equatable, LocalizedError {360 public struct Quoted: Codable, Sendable, Equatable {361 public let id: String?362 public let provider: String?363 public let amountOut: String364 public let amountOutDisplay: String365 public let minAmountOut: String366 public let minAmountOutDisplay: String367 public let quotedAt: Int?368 }369 public struct Fresh: Codable, Sendable, Equatable {370 public let provider: String?371 public let amountOut: String372 public let amountOutDisplay: String373 public let minAmountOut: String374 public let minAmountOutDisplay: String375 public let symbol: String?376 public let quotedAt: Int?377 public let fingerprint: String?378 }379 public let quoted: Quoted380 public let fresh: Fresh381 public let deviationBps: Int?382 public let slippageBps: Int?383 /** The server's English sentence. */384 public let message: String385 public var errorDescription: String? { message }386387 /** nil unless the error is a `409 quote_moved` whose `data` carries both sets of figures. */388 public init?(_ e: APIError) {389 struct Payload: Decodable { let quoted: Quoted; let fresh: Fresh; let deviationBps: Int?; let slippageBps: Int? }390 guard e.status == 409, e.code == "quote_moved", let p: Payload = try? e.data?.decode() else { return nil }391 quoted = p.quoted; fresh = p.fresh; deviationBps = p.deviationBps; slippageBps = p.slippageBps; message = e.message392 }393}394395public extension Proposal {396 /** The swap section, typed. Throws when the server's object cannot be read (it is never replaced by a guess). */397 func swapSection() throws -> SwapSection? { try swap.flatMap { $0.isNull ? nil : try $0.decode(SwapSection.self) } }398 func executionStatus() throws -> ExecutionStatus? { try execution.flatMap { $0.isNull ? nil : try $0.decode(ExecutionStatus.self) } }399 func quoteRecord() throws -> QuoteRecord? { try quote.flatMap { $0.isNull ? nil : try $0.decode(QuoteRecord.self) } }400}401public extension ProposalStatus {402 func executionStatus() throws -> ExecutionStatus? { try execution.flatMap { $0.isNull ? nil : try $0.decode(ExecutionStatus.self) } }403}404