Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Swap/PlanAPI.swift3// Description: Endpoints of the any-to-any plans (services/api/src/plan-exec.ts). Nothing here advances a plan by itself: the4// owner starts it, prepares each leg when its turn comes, approves that leg with a passkey over its own verified5// intent, and decides after a pause (retry, re-plan from the asset held, stop). Reading a plan only makes the6// server look at the current leg's proposal; it creates and signs nothing.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112public struct PlanAPI: SwapOperationAPI {13 public let client: APIClient14 public init(_ client: APIClient) { self.client = client }1516 private func path(_ id: String) -> String { "/plans/\(APIClient.segment(id))" }1718 public func capabilities() async throws -> PlanCapabilities { try await client.get("/plans/capabilities") }1920 /** Candidate plans with real quotes for every leg. Signs nothing, prepares nothing, stores nothing. */21 public func quote(_ r: PlanRequest) async throws -> PlanQuote { try await client.post("/plans/quote", body: r) }2223 /**24 Start a plan: the chosen shape (`PlanCandidate.id`) is priced and checked again, then stored. Nothing is prepared or signed:25 the first leg is `ready`. One plan can be open at a time (`409 plan_open`). `floor` is decimal text in the destination asset.26 */27 public func start(_ r: PlanRequest, plan: String, floor: String? = nil) async throws -> PlanView {28 struct Body: Encodable, Sendable { let from, to, amount: String; let slippageBps: Int; let plan: String; let floor: String? }29 return try await client.post("/plans", body: Body(from: r.from, to: r.to, amount: r.amount, slippageBps: r.slippageBps, plan: plan, floor: floor))30 }3132 public func list(openOnly: Bool = false, limit: Int = 10) async throws -> [PlanView] {33 struct R: Decodable, Sendable { let plans: [PlanView] }34 return try await client.get("/plans", query: ["open": openOnly ? "1" : nil, "limit": String(min(max(limit, 1), 50))], as: R.self).plans35 }3637 /** The plan now. The server first looks at the current leg's proposal and records what it sees (settled, failed, in flight). */38 public func plan(_ id: String) async throws -> PlanView { try await client.get(path(id)) }3940 /**41 Prepare the leg that is ready — the ordinary proposal for it, sized by the server on what the plan actually holds — and42 VERIFY it against the plan AS DISPLAYED (`displayed`): same plan, same position, same leg (kind, provider, assets, networks);43 an amount that does not exceed what the plan held; the wallet's own addresses at both ends; then the intent's hash against44 the challenge. A plan that moved since it was displayed is refused (`ApprovalError.inconsistent`): read it again.45 Returns `operation == nil` when the server paused the plan instead.4647 - Parameter minimumOutput: a plan leg carries no quote reference (the server re-quotes it and applies the plan's floor);48 `.asPrepared` therefore requires the review screen to show the intent's own minimum.49 */50 public func prepareLeg(of displayed: PlanView, accounts: Accounts, minimumOutput: MinimumOutputRule = .asPrepared, maxBridgeFee: String? = nil, now: Date = Date()) async throws -> PlanLegPreparation {51 struct Answer: Decodable, Sendable { let plan: PlanView; let proposal: Proposal?; let intent: JSONValue?; let options: PasskeyRequestOptions? }52 guard let leg = displayed.currentLeg else { throw ApprovalError.inconsistent("the plan has no current step") }53 let a: Answer = try await SwapVerification.post(client, "\(path(displayed.id))/prepare", body: EmptyBody(), idempotencyKey: nil)54 guard a.plan.id == displayed.id else { throw ApprovalError.inconsistent("plan id") }55 guard let proposal = a.proposal else {56 guard a.options == nil, a.intent == nil || a.intent!.isNull else { throw ApprovalError.inconsistent("a challenge without a proposal") }57 return PlanLegPreparation(plan: a.plan, operation: nil)58 }59 guard a.plan.current == displayed.current, a.plan.replans == displayed.replans, let now_ = a.plan.currentLeg else { throw ApprovalError.inconsistent("the plan moved since it was displayed") }60 guard now_.kind == leg.kind, now_.via == leg.via, now_.from.key == leg.from.key, now_.to.key == leg.to.key else { throw ApprovalError.inconsistent("the step is not the one displayed") }61 guard now_.proposalId == proposal.id, a.plan.proposal?.id == proposal.id else { throw ApprovalError.inconsistent("the proposal is not the plan's current step") }62 guard let kind = Intent.Kind(rawValue: leg.kind), [.swap, .bridge, .xswap].contains(kind) else { throw ApprovalError.unsupported("plan step of kind \(leg.kind)") }63 // the leg is sized on what the plan holds — which must be this leg's own source asset64 guard displayed.holding.network == leg.from.network, AssetRef.sameAssetId(displayed.holding.asset, leg.from.asset) else { throw ApprovalError.inconsistent("the plan does not hold this step's source asset") }65 var e = OperationExpectation(kind: kind, network: leg.from.network, asset: leg.from.asset, amount: .atMost(displayed.holding.amount))66 e.provider = leg.via67 e.minimumOutput = SwapVerification.floor(minimumOutput, quote: nil)68 switch kind {69 case .swap:70 guard leg.to.network == leg.from.network else { throw ApprovalError.inconsistent("a swap step changes network") }71 e.toAsset = leg.to.asset72 case .bridge:73 guard leg.from.symbol == "USDC", leg.to.symbol == "USDC" else { throw ApprovalError.inconsistent("a bridge step moves USDC only") }74 e.toNetwork = leg.to.network; e.speed = BridgeSpeed(leg.speed ?? "standard"); e.maxBridgeFee = maxBridgeFee75 default:76 e.toNetwork = leg.to.network; e.toAsset = leg.to.asset77 }78 let answer = SwapVerification.Answer(proposal: proposal, intent: a.intent, options: a.options, replayed: nil)79 return PlanLegPreparation(plan: a.plan, operation: try await SwapVerification.verifyOrWithdraw(client, answer, expecting: e, accounts: accounts, now: now))80 }8182 /** "Retry" after a pause: the same leg becomes ready again (optionally with another overall floor). Signs nothing. */83 public func retry(_ id: String, floor: PlanFloorChange = .unchanged) async throws -> PlanView {84 let body: JSONValue85 switch floor {86 case .unchanged: body = [:]87 case .remove: body = ["floor": nil]88 case .set(let v): body = ["floor": .string(v)]89 }90 return try await client.post("\(path(id))/retry", body: body)91 }9293 /**94 "Stop here": final. An unused challenge of the current leg is withdrawn first; the funds stay where they are, as an ordinary95 balance. Refused (`409 bad_state`) while a leg is in flight.96 */97 public func stop(_ id: String) async throws -> PlanView { try await client.post("\(path(id))/stop") }9899 /**100 "Re-plan from the asset held": the legs not yet done are replaced by a new route to the same destination — the given shape,101 or the best executable one. Signs nothing.102 */103 public func replan(_ id: String, plan: String? = nil) async throws -> PlanView {104 struct Body: Encodable, Sendable { let plan: String? }105 return try await client.post("\(path(id))/replan", body: Body(plan: plan))106 }107}108