SPB Git

Repository Public

BridgeAPI.swift 12.9 KB 171 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Swap/BridgeAPI.swift3// Description: USDC between networks through Circle CCTP V2 (services/api/src/bridge.ts, bridge-sol.ts): quote, preparation of4//              the burn (the approval covers the burn and the first mint), "finish", the passkey-approved re-signature of a5//              mint, and the Solana side — the reclaim of the event-account deposit and the creation of the wallet's USDC6//              token account. Every passkey here signs an object this code recomputed; when the server does not return that7//              object, the function refuses (`ApprovalError.unsupported`) instead of approving blind.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213/** A verified approval of the re-signature of a mint. */14public struct MintRetryApproval: Sendable {15    public let proposal: Proposal16    public let approval: VerifiedApproval<BridgeMintRetry>17    public var object: BridgeMintRetry { approval.object }18}1920/** A verified approval of the reclaim of a Solana event-account deposit. */21public struct DepositReclaimApproval: Sendable {22    public let proposal: Proposal23    public let approval: VerifiedApproval<BridgeDepositReclaim>24    /** The deposit that comes back (lamports) and the network fee of the reclaim, as served and checked against the budget. */25    public let deposit: String26    public let networkFee: String27    public var object: BridgeDepositReclaim { approval.object }28}2930/** A verified approval of the creation of the wallet's USDC token account on Solana. */31public struct TokenAccountApproval: Sendable {32    public let approval: VerifiedApproval<SolanaTokenAccountRequest>33    public let rent: String34    public let rentDisplay: String?35    public let networkFee: String36    public let networkFeeDisplay: String?37    public var request: SolanaTokenAccountRequest { approval.object }38}3940public struct BridgeAPI: SwapOperationAPI {41    public let client: APIClient42    public init(_ client: APIClient) { self.client = client }4344    /** The networks between which the wallet moves USDC itself. */45    public func execution() async throws -> BridgeExecutionInfo { try await client.get("/bridge/execution") }4647    /** What a transfer would cost and need, for both speeds. `amount` is decimal USDC text. */48    public func quote(from: String, to: String, amount: String) async throws -> BridgeQuote {49        try await client.get("/bridge/quote", query: ["from": from, "to": to, "amount": amount])50    }5152    /**53     Prepare a firm transfer and VERIFY it: the intent must burn exactly the requested USDC amount on the source network, from the54     wallet to the wallet, toward the requested network; the recipient must be the wallet's OWN address there (`accounts`);55     Circle's fee ceiling must not exceed the fee displayed — `maxFee` when given, otherwise the fee of the quote reference56     (amount − its minimum received). `sourceUSDC` is the registry id of USDC on the source network (`WalletAPI.networks()`):57     give it so that the asset burned is compared with the registry and not only by its symbol.58     */59    public func prepare(_ r: BridgeRequest, accounts: Accounts, sourceUSDC: String? = nil, maxFee: String? = nil, idempotencyKey: String, now: Date = Date()) async throws -> PreparedOperation {60        let a: SwapVerification.Answer = try await SwapVerification.post(client, "/bridge/proposals", body: r, idempotencyKey: idempotencyKey)61        // USDC has six decimals on every CCTP network; the request names no asset, so the registry id is checked when the caller gives it62        guard a.proposal.symbol == "USDC", a.proposal.decimals == 6 else { throw ApprovalError.inconsistent("asset") }63        let amount = try SwapVerification.requestedUnits(r.amount, decimals: 6, kind: .bridge)64        var e = OperationExpectation(kind: .bridge, network: r.fromNetwork, asset: sourceUSDC ?? a.proposal.asset, amount: .exactly(amount))65        e.toNetwork = r.toNetwork; e.provider = "cctp"; e.speed = r.speed66        if let maxFee { e.maxBridgeFee = maxFee }67        else if let q = r.quote {68            guard q.provider == "cctp", let out = try? BaseUnits(q.minAmountOut), let fee = try? SwapVerification.units(amount, "amount").subtracting(out) else { throw ApprovalError.inconsistent("the quote reference is not for this transfer") }69            e.maxBridgeFee = fee.description70        }71        return try await SwapVerification.verifyOrWithdraw(client, a, expecting: e, accounts: accounts, now: now)72    }7374    /** "Finish": run the next step now instead of waiting for the worker. Safe at any time; it needs no passkey and signs nothing new. */75    public func finish(_ proposalId: String) async throws -> Proposal { try await client.post("\(path(proposalId))/finish") }7677    private func path(_ id: String) -> String { "/bridge/proposals/\(APIClient.segment(id))" }7879    // MARK: the mint must be signed again (reverted, replaced or expired): only with the owner's passkey8081    /**82     Ask for the challenge of a new mint signature and VERIFY it: the object returned (`approval`) must name this transfer, and its83     hash must be the challenge. Show `object.parameters` (the fee ceiling of the new transaction) before asking the passkey.84     */85    public func retryMintOptions(_ proposalId: String) async throws -> MintRetryApproval {86        struct Answer: Decodable, Sendable { let proposal: Proposal; let options: PasskeyRequestOptions; let approval: JSONValue? }87        let a: Answer = try await client.post("\(path(proposalId))/retry-mint/options")88        guard a.proposal.id == proposalId, a.proposal.kind == "bridge" else { throw ApprovalError.inconsistent("proposal id") }89        guard let served = a.approval, !served.isNull else { throw ApprovalError.unsupported(SwapVerification.notReturned) }90        let object = try BridgeMintRetry(served: served)91        guard object.proposalId == proposalId else { throw ApprovalError.inconsistent("the approval is for another transfer") }92        guard let b = try SwapVerification.section(a.proposal.bridgeSection(), "bridge"), b.phase == .mintFailed else { throw ApprovalError.inconsistent("this transfer does not need a new mint signature") }93        return MintRetryApproval(proposal: a.proposal, approval: try ApprovalBinding.verify(object, options: a.options, rpId: client.configuration.rpId))94    }9596    /** Sign the verified challenge and submit it. The answer is the transfer with its mint sent again — not yet received. */97    public func retryMint(_ a: MintRetryApproval, with authenticator: PasskeyAuthenticator) async throws -> Proposal {98        let assertion = try await authenticator.assert(a.approval.options, rpId: client.configuration.rpId)99        return try await client.post("\(path(a.proposal.id))/retry-mint", body: AssertionBody(assertion: assertion))100    }101102    // MARK: Solana → EVM: the event-account deposit back to the wallet103104    /**105     Ask for the challenge of the reclaim and VERIFY it: the object returned must name this transfer and the event account its106     proposal shows; the network fee served must be the fee of the budget approved; the hash must be the challenge.107     The server answers `409 reclaim_not_yet` before the program's five-day window is over.108     */109    public func reclaimOptions(_ proposalId: String) async throws -> DepositReclaimApproval {110        struct Answer: Decodable, Sendable { let proposal: Proposal; let options: PasskeyRequestOptions; let approval: JSONValue?; let deposit: String; let networkFee: String }111        let a: Answer = try await client.post("\(path(proposalId))/reclaim/options")112        guard a.proposal.id == proposalId, a.proposal.kind == "bridge" else { throw ApprovalError.inconsistent("proposal id") }113        guard let served = a.approval, !served.isNull else { throw ApprovalError.unsupported(SwapVerification.notReturned) }114        let object = try BridgeDepositReclaim(served: served)115        guard object.proposalId == proposalId else { throw ApprovalError.inconsistent("the approval is for another transfer") }116        guard let sol = try SwapVerification.section(a.proposal.bridgeSection(), "bridge")?.sol, sol.role == "source", let account = sol.eventAccount else { throw ApprovalError.inconsistent("this transfer has no deposit to reclaim") }117        guard object.eventAccount == account else { throw ApprovalError.inconsistent("event account") }118        guard let fee = object.budget.singleSignerNetworkFee, fee.description == a.networkFee else { throw ApprovalError.inconsistent("network fee") }119        let deposit = try SwapVerification.units(a.deposit, "the deposit")120        guard sol.deposit == nil || sol.deposit == a.deposit, fee < deposit else { throw ApprovalError.inconsistent("deposit") }121        return DepositReclaimApproval(proposal: a.proposal, approval: try ApprovalBinding.verify(object, options: a.options, rpId: client.configuration.rpId), deposit: a.deposit, networkFee: a.networkFee)122    }123124    /** Sign and submit the reclaim. `sol.reclaimState` is then `sent` (or `failed`: the deposit is still there); `done` comes later. */125    public func reclaim(_ a: DepositReclaimApproval, with authenticator: PasskeyAuthenticator) async throws -> Proposal {126        let assertion = try await authenticator.assert(a.approval.options, rpId: client.configuration.rpId)127        return try await client.post("\(path(a.proposal.id))/reclaim", body: AssertionBody(assertion: assertion))128    }129130    // MARK: EVM → Solana: the wallet's own USDC token account must exist BEFORE the burn131132    public func solanaTokenAccount() async throws -> SolanaTokenAccountStatus { try await client.get("/bridge/solana/token-account") }133134    /**135     Ask for the challenge of the creation and VERIFY it: the request returned must open, on Solana, the USDC token account of the136     wallet's own address (`accounts`), for the mint the registry names (`usdcMint` — the USDC token id of the `solana` network137     in `WalletAPI.networks()`), within a fee ceiling that covers exactly what is displayed; its hash must be the challenge.138     */139    public func solanaTokenAccountOptions(accounts: Accounts, usdcMint: String, now: Date = Date()) async throws -> TokenAccountApproval {140        struct Answer: Decodable, Sendable {141            let requestId: String; let owner: String; let tokenAccount: String; let rent: String; let rentDisplay: String?142            let networkFee: String; let networkFeeDisplay: String?; let expiresAt: Int; let options: PasskeyRequestOptions; let request: JSONValue?143        }144        let a: Answer = try await client.post("/bridge/solana/token-account/options")145        guard let served = a.request, !served.isNull else { throw ApprovalError.unsupported(SwapVerification.notReturned) }146        let q = try SolanaTokenAccountRequest(served: served)147        guard q.requestId == a.requestId else { throw ApprovalError.inconsistent("request id") }148        guard q.network == "solana" else { throw ApprovalError.inconsistent("network") }149        guard q.owner == (try SwapVerification.address(accounts, "solana")), q.owner == a.owner else { throw ApprovalError.inconsistent("owner is not the wallet's Solana address") }150        guard q.mint == usdcMint else { throw ApprovalError.inconsistent("mint") }151        guard q.tokenAccount == a.tokenAccount else { throw ApprovalError.inconsistent("token account") }152        guard q.expiresAt == a.expiresAt else { throw ApprovalError.inconsistent("expiry") }153        guard q.expiry > now else { throw ApprovalError.expired }154        // the fee served is the fee of the budget approved, and the ceiling covers it plus the rent displayed155        guard let fee = q.budget.singleSignerNetworkFee, fee.description == a.networkFee else { throw ApprovalError.inconsistent("network fee") }156        guard fee + (try SwapVerification.units(a.rent, "the rent")) <= (try SwapVerification.units(q.maxFee, "the fee ceiling")) else { throw ApprovalError.inconsistent("the fee ceiling does not cover the rent and the fee displayed") }157        return TokenAccountApproval(approval: try ApprovalBinding.verify(q, options: a.options, rpId: client.configuration.rpId),158                                    rent: a.rent, rentDisplay: a.rentDisplay, networkFee: a.networkFee, networkFeeDisplay: a.networkFeeDisplay)159    }160161    /** Sign and submit the creation. `sent == false` means the server signed without relaying; `true` is not a confirmation. */162    public func createSolanaTokenAccount(_ a: TokenAccountApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> SolanaTokenAccountCreation {163        guard a.request.expiry > now else { throw ApprovalError.expired }164        struct Body: Encodable, Sendable { let requestId: String; let assertion: PasskeyAssertion }165        let assertion = try await authenticator.assert(a.approval.options, rpId: client.configuration.rpId)166        return try await client.post("/bridge/solana/token-account", body: Body(requestId: a.request.requestId, assertion: assertion))167    }168}169170struct AssertionBody: Encodable, Sendable { let assertion: PasskeyAssertion }171
Files main
Menu

Theme