Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Swap/SwapApproval.swift3// Description: What every preparation of this domain goes through before a passkey is asked (swap, CCTP transfer, THORChain swap,4// plan leg): the answer `{ proposal, intent, options, replayed? }` is decoded, the intent is parsed STRICTLY, compared5// field by field with what was requested and with the proposal that will be displayed, and only then bound to the6// challenge with `ApprovalBinding.verify`. Without the intent (a server that does not return it) nothing is7// approvable: `ApprovalError.unsupported`. The approval itself is the transfers route, as on the server.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213/** A prepared operation whose challenge was verified against the intent displayed. The only thing the approve functions accept. */14public struct ApprovableOperation: Sendable {15 public let proposal: Proposal16 public let approval: VerifiedApproval<Intent>17 public var intent: Intent { approval.object }18 init(proposal: Proposal, approval: VerifiedApproval<Intent>) { self.proposal = proposal; self.approval = approval }19}2021/** The answer of a preparation route, after verification. */22public struct PreparedOperation: Sendable {23 public let proposal: Proposal24 /** True when the server answered a proposal that this Idempotency-Key had already produced. */25 public let replayed: Bool26 /**27 nil ONLY for a replay whose proposal can no longer be approved (already approved, expired, rejected…): the server then issues28 no challenge; read `proposal.state` and follow it instead.29 */30 public let approvable: ApprovableOperation?31}3233/** How the guaranteed minimum of the intent is compared with what the owner was shown before preparing. */34public enum MinimumOutputRule: Sendable, Hashable {35 /**36 With a quote reference: the intent's minimum output must be at least the minimum of the quote displayed. STRICTER than the37 server (which refuses — `quote_moved` — only when the firm EXPECTED output is below that minimum): a firm minimum a few units38 under the quoted one is normal whenever the price moved within the tolerance, so this rule refuses often. Opt-in only.39 Without a reference: as `asPrepared`.40 */41 case notBelowQuote42 /** An explicit floor in base units of the destination asset. */43 case atLeast(String)44 /**45 DEFAULT. The firm minimum is accepted as prepared (the server has already refused a firm expected output below the quoted46 minimum). The review screen MUST show `intent.swap.minOut` / `intent.xswap.minOut`47 (never the earlier quote) before the passkey is asked.48 */49 case asPrepared50}5152/** What the operation to approve must be, derived from the request (or from the plan leg) — never from the answer. */53struct OperationExpectation: Sendable {54 enum Amount: Sendable { case exactly(String), atMost(String) }55 let kind: Intent.Kind56 let network: String57 let asset: String58 let amount: Amount59 var toNetwork: String?60 var toAsset: String?61 var provider: String?62 var minimumOutput: String?63 var maxBridgeFee: String?64 var speed: BridgeSpeed?65}6667enum SwapVerification {68 static let notReturned = "the server did not return the object to approve"6970 struct Answer: Decodable, Sendable {71 let proposal: Proposal72 let intent: JSONValue?73 let options: PasskeyRequestOptions?74 let replayed: Bool?75 }7677 /** POST a preparation; `409 quote_moved` becomes the typed `QuoteMoved` (nothing was prepared). */78 static func post<T: Decodable & Sendable>(_ client: APIClient, _ path: String, body: any Encodable & Sendable, idempotencyKey: String?) async throws -> T {79 do { return try await client.post(path, body: body, idempotencyKey: idempotencyKey) }80 catch let e as APIError { if let moved = QuoteMoved(e) { throw moved }; throw e }81 }8283 /** Base units of a decimal request amount, exactly as the server computes them for this kind. */84 static func requestedUnits(_ text: String, decimals: Int, kind: Intent.Kind) throws -> String {85 let units: BaseUnits86 do { units = try BaseUnits.parse(text, decimals: decimals) } catch { throw ApprovalError.inconsistent("the requested amount cannot be read") }87 var s = units.description88 // THORChain credits eight decimals: the server sends nothing finer (xswap.ts `amount -= amount % 10^(decimals-8)`)89 if kind == .xswap, decimals > 8 { let cut = decimals - 8; s = s.count <= cut ? "0" : String(s.dropLast(cut)) + String(repeating: "0", count: cut) }90 return s91 }9293 static func units(_ s: String, _ what: String) throws -> BaseUnits {94 do { return try BaseUnits(s) } catch { throw ApprovalError.inconsistent("\(what) is not a base-unit integer") }95 }9697 static func address(_ accounts: Accounts, _ network: String) throws -> String {98 guard let a = accounts.accounts.first(where: { $0.network == network })?.address, !a.isEmpty else { throw ApprovalError.inconsistent("the wallet has no known address on \(network)") }99 return a100 }101102 /** The proposal must be the operation requested. Compared before anything about the challenge is looked at. */103 static func check(proposal p: Proposal, against e: OperationExpectation, accounts: Accounts) throws {104 guard p.kind == e.kind.rawValue else { throw ApprovalError.inconsistent("a \(e.kind.rawValue) was requested; the proposal is a \(p.kind ?? "transfer")") }105 guard p.network == e.network else { throw ApprovalError.inconsistent("network") }106 guard AssetRef.sameAssetId(p.asset, e.asset) else { throw ApprovalError.inconsistent("asset") }107 let amount = try units(p.amount, "the proposal amount")108 guard !amount.isZero else { throw ApprovalError.inconsistent("amount") }109 switch e.amount {110 case .exactly(let want): guard p.amount == want else { throw ApprovalError.inconsistent("amount") }111 case .atMost(let ceiling): guard amount <= (try units(ceiling, "the amount held")) else { throw ApprovalError.inconsistent("amount above what the plan holds") }112 }113 guard p.from == (try address(accounts, e.network)) else { throw ApprovalError.inconsistent("source is not the wallet's address") }114 }115116 /**117 The whole verification of a preparation answer. Order: the proposal against the request; then the intent against the proposal118 (what the review screen shows), against the request and against the wallet's own addresses; then the challenge.119 */120 static func verify(_ a: Answer, expecting e: OperationExpectation, accounts: Accounts, rpId: String, now: Date) throws -> PreparedOperation {121 let p = a.proposal, replayed = a.replayed ?? false122 try check(proposal: p, against: e, accounts: accounts)123 guard let options = a.options else {124 // no challenge: legitimate only for the replay of a proposal that is no longer waiting for an approval125 // (already approved, rejected, or its window ran out on the server's clock)126 guard replayed else { throw ApprovalError.unsupported("the server issued no challenge for this proposal") }127 return PreparedOperation(proposal: p, replayed: true, approvable: nil)128 }129 guard p.state == .pendingApproval else { throw ApprovalError.inconsistent("a challenge was issued for a proposal that is \(p.state.rawValue)") }130 guard let served = a.intent, !served.isNull else { throw ApprovalError.unsupported(notReturned) }131 let i = try Intent(served: served)132133 try TransfersAPI.check(intent: i, against: p, now: now)134 guard i.kind == e.kind else { throw ApprovalError.inconsistent("a \(e.kind.rawValue) was requested; the intent is a \(i.kind.rawValue)") }135 guard i.memo == nil else { throw ApprovalError.inconsistent("memo") }136 guard let hash = p.intentHash, Data(hex: hash) == (try i.approvalDigest()) else { throw ApprovalError.inconsistent("the proposal's fingerprint is not the intent's") }137 let me = try address(accounts, e.network)138 guard i.from == me else { throw ApprovalError.inconsistent("source is not the wallet's address") }139140 switch e.kind {141 case .swap: try checkSwap(i, p, e)142 case .bridge: try checkBridge(i, p, e, accounts)143 case .xswap: try checkXSwap(i, p, e, accounts, now)144 default: throw ApprovalError.unsupported("operation kind \(e.kind.rawValue)")145 }146 let verified = try ApprovalBinding.verify(i, options: options, rpId: rpId)147 return PreparedOperation(proposal: p, replayed: replayed, approvable: ApprovableOperation(proposal: p, approval: verified))148 }149150 /**151 Verify a prepared operation; when the verification refuses it, WITHDRAW the proposal the server just created (best effort)152 before rethrowing, so that nothing the owner will not approve stays pending (or holds a plan leg "proposed").153 */154 static func verifyOrWithdraw(_ client: APIClient, _ a: Answer, expecting e: OperationExpectation, accounts: Accounts, now: Date) async throws -> PreparedOperation {155 do { return try verify(a, expecting: e, accounts: accounts, rpId: client.configuration.rpId, now: now) }156 catch let refusal as ApprovalError {157 let _: Proposal? = try? await client.post("/transfers/proposals/\(APIClient.segment(a.proposal.id))/reject")158 throw refusal159 }160 }161162 static func checkMinimum(_ minOut: String, floor: String?) throws {163 let m = try units(minOut, "the minimum output")164 guard !m.isZero else { throw ApprovalError.inconsistent("minimum output is zero") }165 if let floor { guard m >= (try units(floor, "the minimum displayed")) else { throw ApprovalError.inconsistent("minimum output below the minimum displayed") } }166 }167168 static func checkSwap(_ i: Intent, _ p: Proposal, _ e: OperationExpectation) throws {169 guard let s = i.swap else { throw ApprovalError.inconsistent("the intent carries no swap") }170 guard i.to == i.from else { throw ApprovalError.inconsistent("a swap must deliver to the wallet itself") }171 if let want = e.toAsset { guard AssetRef.sameAssetId(s.toAsset, want) else { throw ApprovalError.inconsistent("destination asset") } }172 guard !AssetRef.sameAssetId(s.toAsset, i.asset) else { throw ApprovalError.inconsistent("input and output are the same asset") }173 if let want = e.provider { guard s.provider == want else { throw ApprovalError.inconsistent("provider") } }174 // the review screen is built from the proposal: it must say what the intent says175 guard let shown = try section(p.swapSection(), "swap") else { throw ApprovalError.inconsistent("the proposal carries no swap section") }176 guard shown.provider == s.provider, AssetRef.sameAssetId(shown.toAsset, s.toAsset), shown.minOut == s.minOut else { throw ApprovalError.inconsistent("the proposal's swap is not the intent's") }177 try checkMinimum(s.minOut, floor: e.minimumOutput)178 }179180 static func checkBridge(_ i: Intent, _ p: Proposal, _ e: OperationExpectation, _ accounts: Accounts) throws {181 guard let b = i.bridge else { throw ApprovalError.inconsistent("the intent carries no bridge") }182 guard i.to == i.from else { throw ApprovalError.inconsistent("a bridge must go from the wallet to the wallet") }183 guard b.provider == (e.provider ?? "cctp") else { throw ApprovalError.inconsistent("provider") }184 guard let toNetwork = e.toNetwork, b.toNetwork == toNetwork, toNetwork != i.network else { throw ApprovalError.inconsistent("destination network") }185 // the destination is the wallet's own address there: the named recipient when the key family differs, the same address otherwise186 let destination = try address(accounts, toNetwork)187 guard (b.recipient ?? i.to) == destination else { throw ApprovalError.inconsistent("recipient is not the wallet's address on the destination network") }188 let fee = try units(b.maxFee, "the CCTP fee ceiling")189 guard fee < i.amountUnits else { throw ApprovalError.inconsistent("the CCTP fee ceiling is not below the amount") }190 if let ceiling = e.maxBridgeFee { guard fee <= (try units(ceiling, "the fee displayed")) else { throw ApprovalError.inconsistent("CCTP fee above the fee displayed") } }191 guard let shown = try section(p.bridgeSection(), "bridge") else { throw ApprovalError.inconsistent("the proposal carries no bridge section") }192 guard shown.provider == b.provider, shown.toNetwork == b.toNetwork, shown.cctpMaxFee == b.maxFee else { throw ApprovalError.inconsistent("the proposal's bridge is not the intent's") }193 if let speed = e.speed { guard shown.speed == speed else { throw ApprovalError.inconsistent("speed") } }194 // Circle's finality thresholds (packages/core/src/cctp.ts): 1000 = Fast, 2000 = Standard195 switch shown.speed {196 case .some(.fast): guard b.minFinalityThreshold == 1000 else { throw ApprovalError.inconsistent("finality threshold is not the Fast one") }197 case .some(.standard): guard b.minFinalityThreshold == 2000 else { throw ApprovalError.inconsistent("finality threshold is not the Standard one") }198 default: throw ApprovalError.unsupported("bridge speed \(shown.speed?.rawValue ?? "absent")")199 }200 }201202 static func checkXSwap(_ i: Intent, _ p: Proposal, _ e: OperationExpectation, _ accounts: Accounts, _ now: Date) throws {203 guard let x = i.xswap else { throw ApprovalError.inconsistent("the intent carries no cross-chain swap") }204 guard x.provider == (e.provider ?? "thorchain") else { throw ApprovalError.inconsistent("provider") }205 guard let toNetwork = e.toNetwork, x.toNetwork == toNetwork, toNetwork != i.network else { throw ApprovalError.inconsistent("destination network") }206 guard let toAsset = e.toAsset, AssetRef.sameAssetId(x.toAsset, toAsset) else { throw ApprovalError.inconsistent("destination asset") }207 guard i.to == x.vault, x.vault != i.from else { throw ApprovalError.inconsistent("the transfer does not pay the vault named") }208 // memo `=:<ASSET>:<DESTINATION>:<LIMIT>`: the destination must be the wallet's own address there, the limit the one approved209 let destination = try address(accounts, toNetwork)210 let memo = x.memo.split(separator: ":", omittingEmptySubsequences: false).map(String.init)211 guard memo.count == 4, memo[0] == "=", !memo[1].isEmpty else { throw ApprovalError.inconsistent("memo is not a plain swap memo") }212 guard memo[2] == destination else { throw ApprovalError.inconsistent("the memo does not deliver to the wallet's address on the destination network") }213 guard memo[3] == x.limit, !(try units(x.limit, "the limit")).isZero else { throw ApprovalError.inconsistent("the memo limit is not the approved limit") }214 guard Date(timeIntervalSince1970: TimeInterval(x.expiry)) > now else { throw ApprovalError.expired }215 guard let shown = try section(p.xswapSection(), "xswap") else { throw ApprovalError.inconsistent("the proposal carries no cross-chain section") }216 guard shown.provider == x.provider, shown.toNetwork == x.toNetwork, shown.vault == x.vault, shown.memo == x.memo else { throw ApprovalError.inconsistent("the proposal's cross-chain swap is not the intent's") }217 if let s = try section(p.swapSection(), "swap") { guard s.minOut == x.minOut, AssetRef.sameAssetId(s.toAsset, x.toAsset) else { throw ApprovalError.inconsistent("the proposal's minimum is not the intent's") } }218 try checkMinimum(x.minOut, floor: e.minimumOutput)219 }220221 /** A section that cannot be decoded is a refusal, not an absence. */222 static func section<T>(_ read: @autoclosure () throws -> T?, _ name: String) throws -> T? {223 do { return try read() } catch { throw ApprovalError.unsupported("the proposal's \(name) section cannot be read") }224 }225226 static func floor(_ rule: MinimumOutputRule, quote: QuoteRef?) -> String? {227 switch rule {228 case .notBelowQuote: quote?.minAmountOut229 case .atLeast(let v): v230 case .asPrepared: nil231 }232 }233234 // MARK: approval (the server approves a swap, a CCTP burn and a THORChain deposit on the transfers route: transfers.ts)235236 static func approve(_ op: ApprovableOperation, with authenticator: PasskeyAuthenticator, client: APIClient, now: Date) async throws -> Proposal {237 try await TransfersAPI(client).approve(TransferApproval(proposal: op.proposal, approval: op.approval), with: authenticator, now: now)238 }239}240241/** What the three single-operation APIs share once a proposal exists. */242public protocol SwapOperationAPI: Sendable {243 var client: APIClient { get }244}245public extension SwapOperationAPI {246 /**247 Ask the passkey to sign the verified challenge and hand the assertion to the server (POST /transfers/proposals/:id/approve —248 the route the server uses for swaps, CCTP burns and THORChain deposits). The answer is the proposal after signing: for a249 cross-chain operation it is the START of the journey, not its completion.250 */251 func approve(_ op: ApprovableOperation, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> Proposal {252 try await SwapVerification.approve(op, with: authenticator, client: client, now: now)253 }254 /** Second half of `approve`: a lost answer is followed by a status read, never by a second signature. */255 func submit(assertion: PasskeyAssertion, for op: ApprovableOperation) async throws -> Proposal {256 try await TransfersAPI(client).submit(assertion: assertion, proposalId: op.proposal.id)257 }258 /** Withdraw a proposal that was not approved. */259 func reject(_ proposalId: String) async throws -> Proposal { try await TransfersAPI(client).reject(proposalId) }260 func proposal(_ id: String) async throws -> Proposal { try await TransfersAPI(client).proposal(id) }261 func status(_ id: String) async throws -> ProposalStatus { try await TransfersAPI(client).status(id) }262}263