Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Swap/CrossChainModels.swift3// Description: Models of the two cross-chain operations: USDC through Circle CCTP (services/api/src/bridge.ts, bridge-sol.ts,4// `bridgeView` / `solBridgeView` of transfers.ts) and native swaps through THORChain (xswap.ts, `xswapView` of5// xswap-state.ts). A cross-chain operation is NOT done when its source transaction is broadcast or even final:6// `isComplete` is true only for the state in which the wallet itself saw the funds on the destination.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112// MARK: - CCTP1314/** GET /bridge/execution: the networks between which the wallet moves USDC itself, as served. */15public struct BridgeExecutionInfo: Codable, Sendable, Hashable {16 public let enabled: Bool17 public let provider: String18 public let asset: String19 public let networks: [String]20 public let messenger: String?21 public let transmitter: String?22 public func canBridge(from: String, to: String) -> Bool { enabled && from != to && networks.contains(from) && networks.contains(to) }23}2425public struct BridgeSpeed: ServerCode { public let rawValue: String; public init(rawValue: String) { self.rawValue = rawValue }26 public static let standard = BridgeSpeed("standard"), fast = BridgeSpeed("fast") }2728/** GET /bridge/quote: what a transfer would cost and need, for both speeds. Signs nothing, prepares nothing. */29public struct BridgeQuote: Codable, Sendable, Hashable {30 public struct Option: Codable, Sendable, Hashable {31 public let speed: BridgeSpeed32 /** False when this speed cannot be used right now (fee not covered, Circle's Fast allowance too small…). */33 public let available: Bool34 /** Circle's fee CEILING, USDC base units. */35 public let fee: String36 public let feeDisplay: String37 public let minReceive: String38 public let minReceiveDisplay: String39 public let seconds: Double?40 /** What to send back as `quote` when preparing this option; nil when the amount does not cover the fee. */41 public let quote: QuoteRef?42 }43 public struct DestinationGas: Codable, Sendable, Hashable {44 public let symbol: String45 public let need: String46 public let needDisplay: String47 public let balance: String48 public let balanceDisplay: String49 /** False = the mint could not be paid on the destination: the server refuses to burn anything. */50 public let enough: Bool51 }52 /** Solana-specific lines: the refundable deposit of a burn on Solana (`source`), or the token account a mint on Solana needs (`destination`). */53 public struct Solana: Codable, Sendable, Hashable {54 public let role: String55 public let symbol: String?56 public let deposit: String?57 public let depositDisplay: String?58 public let reclaimAfterSeconds: Int?59 public let networkFeeDisplay: String?60 public let recipient: String?61 public let tokenAccount: String?62 /** False = the wallet's USDC token account must be created (a small passkey-approved transaction) BEFORE the burn. */63 public let tokenAccountExists: Bool?64 public let tokenAccountRentDisplay: String?65 public let nonceRentDisplay: String?66 }67 public let from: String68 public let to: String69 public let fromName: String?70 public let toName: String?71 public let amount: String72 public let symbol: String73 public let options: [Option]74 public let destinationGas: DestinationGas75 public let solana: Solana?76 public func option(_ speed: BridgeSpeed) -> Option? { options.first { $0.speed == speed } }77}7879/** One word for the whole transfer (`stage` of `bridgeView`). */80public struct BridgeStage: ServerCode { public let rawValue: String; public init(rawValue: String) { self.rawValue = rawValue }81 public static let review = BridgeStage("review"), burning = BridgeStage("burning"), attesting = BridgeStage("attesting"), ready = BridgeStage("ready")82 public static let minting = BridgeStage("minting"), mintFailed = BridgeStage("mint_failed"), done = BridgeStage("done"), failed = BridgeStage("failed") }8384/** The stored phase of the second leg (`BridgePhase` of bridge.ts). */85public struct BridgePhase: ServerCode { public let rawValue: String; public init(rawValue: String) { self.rawValue = rawValue }86 public static let burn = BridgePhase("burn"), attesting = BridgePhase("attesting"), ready = BridgePhase("ready")87 public static let mintSent = BridgePhase("mint_sent"), mintFailed = BridgePhase("mint_failed"), done = BridgePhase("done") }8889/** State of the reclaim of a Solana event-account deposit (`reclaimState` of `solBridgeView`). */90public struct ReclaimState: ServerCode { public let rawValue: String; public init(rawValue: String) { self.rawValue = rawValue }91 /** The burn is not mined yet. */ public static let pending = ReclaimState("pending")92 /** The program releases the deposit five days after the burn, once Circle attested it. */ public static let locked = ReclaimState("locked")93 public static let available = ReclaimState("available"), sent = ReclaimState("sent"), done = ReclaimState("done"), failed = ReclaimState("failed") }9495/** The Solana side of a Solana ↔ EVM transfer (`solBridgeView`). */96public struct SolanaBridgeSection: Codable, Sendable, Hashable {97 /** `source` (the burn is on Solana: a refundable event-account deposit exists) or `destination` (the mint is on Solana). */98 public let role: String99 public let symbol: String?100 public let recipient: String?101 public let tokenAccount: String?102 public let nonceRentDisplay: String?103 /** The one-time event account created by the burn; known once the signer has built the transaction. */104 public let eventAccount: String?105 /** The refundable rent deposit, lamports. */106 public let deposit: String?107 public let depositDisplay: String?108 public let reclaimableAt: Date?109 /** True while `reclaimableAt` is an estimate (the burn is not mined, or the event account was not read yet). */110 public let reclaimEstimated: Bool?111 /** nil when there is no deposit to reclaim (Solana is the destination). */112 public let reclaimState: ReclaimState?113 public let reclaimError: String?114 public let reclaimTxid: String?115 public let reclaimExplorer: String?116 public let reclaimedDisplay: String?117118 /** The owner can ask for the reclaim now (a failed attempt left the deposit in place and can be repeated). */119 public var canReclaim: Bool { reclaimState == .available || reclaimState == .failed }120 /** True only when the reclaim transaction is confirmed. `sent` is not that. */121 public var isReclaimed: Bool { reclaimState == .done }122}123124/** The `bridge` section of a proposal (`bridgeView`). */125public struct BridgeSection: Codable, Sendable, Hashable {126 public let provider: String127 public let toNetwork: String128 public let toNetworkName: String?129 public let speed: BridgeSpeed?130 public let expectedSeconds: Double?131 public let stage: BridgeStage132 public let phase: BridgePhase133 /** Circle's fee ceiling approved with the burn, USDC base units. */134 public let cctpMaxFee: String135 public let cctpMaxFeeDisplay: String136 public let minReceiveDisplay: String137 public let feeExecutedDisplay: String?138 /** What the wallet received on the destination; nil until the mint is confirmed. */139 public let received: String?140 public let receivedDisplay: String?141 public let destGasSymbol: String?142 public let destGasNeedDisplay: String?143 public let needsApproval: Bool?144 public let simulated: Bool?145 public let approvalTxid: String?146 public let approvalState: String?147 /** Why the transfer is waiting, when it is (`attestation_late`, `destination_gas`, `mint_reverted`, …). */148 public let hold: String?149 public let holdDetail: String?150 public let holdCode: String?151 public let holdParams: [String: JSONValue]?152 public let irisStatus: String?153 public let delayReason: String?154 public let polls: Int?155 /** Circle's attestation of the burn was received and matches the approved transfer. */156 public let attested: Bool?157 public let mintTxid: String?158 public let mintExplorer: String?159 /** `wallet`, or `other` when someone else submitted the (permissionless) mint — the USDC still arrived at the wallet. */160 public let mintedBy: String?161 /** "Finish" can be asked (it runs the next step now; it signs nothing the burn approval did not cover). */162 public let canFinish: Bool?163 /** The mint must be signed again, which needs the owner's passkey (retry-mint). */164 public let needsPasskey: Bool?165 public let sol: SolanaBridgeSection?166167 /**168 True ONLY when the USDC was minted on the destination and the wallet recorded it (`phase == done`). A broadcast, confirming169 or even finalized burn is not that: the proposal's own state says nothing about the second leg.170 */171 public var isComplete: Bool { phase == .done && stage == .done }172 /** The burn itself ended without leaving (rejected, expired, failed, replaced): nothing was burned by this proposal. */173 public var isFailed: Bool { stage == .failed }174 /** Burned (or being burned) and not yet minted: the funds are in transit and stay claimable. */175 public var isInTransit: Bool { !isComplete && !isFailed && stage != .review }176}177178/** POST /bridge/proposals body. */179public struct BridgeRequest: Codable, Sendable, Hashable {180 public let fromNetwork: String181 public let toNetwork: String182 /** Decimal text in USDC ("25.5"). */183 public let amount: String184 public let speed: BridgeSpeed185 /** The reference of the option displayed (`BridgeQuote.Option.quote`). */186 public let quote: QuoteRef?187 public init(fromNetwork: String, toNetwork: String, amount: String, speed: BridgeSpeed = .standard, quote: QuoteRef? = nil) {188 self.fromNetwork = fromNetwork; self.toNetwork = toNetwork; self.amount = amount; self.speed = speed; self.quote = quote189 }190}191192/** GET /bridge/solana/token-account: the wallet's own USDC token account on Solana, where USDC burned elsewhere is minted. */193public struct SolanaTokenAccountStatus: Codable, Sendable, Hashable {194 public let owner: String195 public let tokenAccount: String196 public let exists: Bool197 public let rent: String198 public let rentDisplay: String199 public let symbol: String?200}201202/** POST /bridge/solana/token-account: the creation transaction was signed (and relayed unless the server does not broadcast). */203public struct SolanaTokenAccountCreation: Codable, Sendable, Hashable {204 public let txid: String205 public let explorer: String?206 public let tokenAccount: String207 /** False on a server that signs without relaying: nothing was sent. A `true` is not a confirmation either. */208 public let sent: Bool209}210211// MARK: - THORChain212213/** GET /xswap/execution: the assets the wallet swaps natively, and whether each may be the input, as served. */214public struct XSwapExecutionInfo: Codable, Sendable, Hashable {215 public struct Operator: Codable, Sendable, Hashable { public let id: String; public let host: String? }216 public struct Asset: Codable, Sendable, Hashable { public let network: String; public let asset: String; public let symbol: String; /** May be the INPUT of a swap; false = destination only. */ public let source: Bool }217 public let enabled: Bool218 public let provider: String219 /** How many THORNode operators must confirm the vault. */220 public let minOperators: Int?221 public let operators: [Operator]?222 public let assets: [Asset]223 /** Network → the pinned THORChain router (EVM sources). */224 public let routers: [String: String]?225226 /** The pair can be swapped natively by the wallet: the source may be an input, both are listed, the networks differ. */227 public func canSwap(from: AssetRef, to: AssetRef) -> Bool {228 func find(_ r: AssetRef) -> Asset? { assets.first { $0.network == r.network && AssetRef.sameAssetId($0.asset, r.asset) } }229 guard enabled, from.network != to.network, let s = find(from), find(to) != nil else { return false }230 return s.source231 }232}233234public struct XSwapStage: ServerCode { public let rawValue: String; public init(rawValue: String) { self.rawValue = rawValue }235 public static let review = XSwapStage("review"), sending = XSwapStage("sending"), sent = XSwapStage("sent"), observed = XSwapStage("observed")236 public static let outbound = XSwapStage("outbound"), received = XSwapStage("received"), refunded = XSwapStage("refunded"), failed = XSwapStage("failed") }237238public struct XSwapPhase: ServerCode { public let rawValue: String; public init(rawValue: String) { self.rawValue = rawValue }239 public static let sending = XSwapPhase("sending"), sent = XSwapPhase("sent"), observed = XSwapPhase("observed")240 public static let outbound = XSwapPhase("outbound"), received = XSwapPhase("received"), refunded = XSwapPhase("refunded") }241242/** The `xswap` section of a proposal (`xswapView`). */243public struct XSwapSection: Codable, Sendable, Hashable {244 public let provider: String245 public let toNetwork: String246 public let toNetworkName: String?247 public let toSymbol: String248 public let stage: XSwapStage249 public let phase: XSwapPhase250 public let expectedOutDisplay: String251 public let minOutDisplay: String252 /** Fees THORChain takes from the output (already deducted from the expected amount and from the minimum). */253 public let outboundFeeDisplay: String?254 public let liquidityFeeDisplay: String?255 public let estimatedSeconds: Double?256 public let slippageBps: Int?257 /** The Asgard vault that receives the source asset — shown to the owner before approval. */258 public let vault: String259 public let vaultExplorer: String?260 public let memo: String261 public let router: String?262 public let operators: [String]?263 public let quoteOperators: [String]?264 public let vaultMembers: Int?265 public let churnHeight: Int?266 public let evidenceMultiple: Double?267 public let evidenceTransfersOut: Int?268 public let needsApproval: Bool?269 public let simulated: Bool?270 public let approvalTxid: String?271 public let approvalState: String?272 /** `vault_churned`, `not_observed`, `outbound_late`, `outbound_mismatch`, `outbound_not_seen`, `below_minimum`. */273 public let hold: String?274 public let holdDetail: String?275 public let holdCode: String?276 public let holdParams: [String: JSONValue]?277 public let refundPlanned: Bool?278 public let outTxid: String?279 /** `out` or `refund`. */280 public let outKind: String?281 public let outExplorer: String?282 public let receivedDisplay: String?283 public let refundedDisplay: String?284 /** The outcome is known: received OR refunded. Not a success flag. */285 public let done: Bool?286287 /**288 True ONLY when the wallet's own chain adapters saw the outbound transaction pay the wallet on the destination289 (`phase == received`). A refund is not that; a deposit observed by THORChain is not that.290 */291 public var isComplete: Bool { phase == .received && stage == .received }292 /** THORChain sent the source asset back: the swap did not happen. */293 public var isRefunded: Bool { phase == .refunded && stage == .refunded }294 public var isFailed: Bool { stage == .failed }295 /** Received, but less than the approved minimum: shown as such, never as a plain success. */296 public var receivedBelowMinimum: Bool { isComplete && hold == "below_minimum" }297}298299/** POST /xswap/proposals body. */300public struct XSwapRequest: Codable, Sendable, Hashable {301 public let fromNetwork: String302 public let fromAsset: String303 public let toNetwork: String304 public let toAsset: String305 /** Decimal text in whole units of the source asset. Beyond eight decimals THORChain credits nothing: the server sends nothing finer. */306 public let amount: String307 /** 1…300. */308 public let slippageBps: Int309 public let quote: QuoteRef?310 public init(fromNetwork: String, fromAsset: String, toNetwork: String, toAsset: String, amount: String, slippageBps: Int = 100, quote: QuoteRef? = nil) {311 self.fromNetwork = fromNetwork; self.fromAsset = fromAsset; self.toNetwork = toNetwork; self.toAsset = toAsset; self.amount = amount; self.slippageBps = slippageBps; self.quote = quote312 }313}314315// MARK: - one answer for "is it done?"316317/** Where a swap / bridge / native swap stands, without ever reading success out of the source transaction alone. */318public enum OperationCompletion: Sendable, Hashable {319 /** Not approved yet, or approved and not yet on its way. */320 case notStarted321 /** On its way; for a cross-chain operation this lasts until the destination is confirmed. */322 case inProgress323 /** The destination is confirmed (same-network swap: the transaction is final). */324 case complete325 /** THORChain returned the source asset. */326 case refunded327 /** Ended without moving the funds forward. */328 case failed329}330331public extension Proposal {332 func bridgeSection() throws -> BridgeSection? { try bridge.flatMap { $0.isNull ? nil : try $0.decode(BridgeSection.self) } }333 func xswapSection() throws -> XSwapSection? { try xswap.flatMap { $0.isNull ? nil : try $0.decode(XSwapSection.self) } }334335 /**336 Completion of a swap, a CCTP transfer or a THORChain swap. For a bridge only `bridge.phase == done` is complete, for a337 native swap only `xswap.phase == received`: `ProposalState.finalized` describes the SOURCE transaction and is not enough.338 Throws for another kind of proposal or when the section cannot be read.339 */340 func swapCompletion() throws -> OperationCompletion {341 switch kind {342 case "bridge":343 guard let b = try bridgeSection() else { throw ApprovalError.unsupported("bridge proposal without its bridge section") }344 if b.isComplete { return .complete }345 if b.isFailed || state.isFailure || state == .notBroadcast { return .failed }346 return b.stage == .review || state == .draft ? .notStarted : .inProgress347 case "xswap":348 guard let x = try xswapSection() else { throw ApprovalError.unsupported("xswap proposal without its xswap section") }349 if x.isComplete { return .complete }350 if x.isRefunded { return .refunded }351 if x.isFailed || state.isFailure || state == .notBroadcast { return .failed }352 return x.stage == .review || state == .draft ? .notStarted : .inProgress353 case "swap":354 if state == .finalized { return .complete }355 if state.isFailure || state == .notBroadcast { return .failed }356 return state == .draft || state == .pendingApproval ? .notStarted : .inProgress357 default:358 throw ApprovalError.unsupported("not a swap, bridge or cross-chain swap: \(kind ?? "transfer")")359 }360 }361}362