Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Execution/MandatesAPI.swift3// Description: The owner's routes of trading mandates (/api/v1/mandates). A PAPER mandate is approved by the session alone (nothing4// is signed in paper mode). A LIVE mandate takes TWO passkey prompts in one approval: (1) over the hash of the5// derivative mandate compiled for the isolated signer, (2) over an intent naming the FULL trading mandate hash.6// Both challenges are recomputed here; the mandate is compared with what was asked; the compiled signer mandate is7// re-derived from the mandate field by field. Anything that does not line up is refused before the passkey.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213/** The verified approval sheet of a mandate. */14public struct MandateApprovalSheet: Sendable {15 public struct Acknowledgement: Decodable, Sendable, Equatable { public let locale: String?; public let sha256: String; public let version: String?; public let title: String?; public let text: String? }16 /** The live part: the two verified challenges and the texts the owner must be shown before he confirms. */17 public struct Live: Sendable {18 /** prompt 1 — judged by the ISOLATED SIGNER: the derivative mandate it will store and enforce */19 public let signer: VerifiedApproval<CompiledVenueMandate>20 /** prompt 2 — judged by the API: the full trading mandate hash and that signer mandate */21 public let binding: VerifiedApproval<MandateApprovalIntent>22 /** the venue account the signer mandate is for */23 public let accountId: String?24 /** the jurisdiction acknowledgement to display; its hash is inside the signer mandate */25 public let acknowledgement: Acknowledgement26 public let warning: String?27 public let enforcedBySigner: JSONValue?28 public let trustedBySigner: JSONValue?29 public let notEnforced: JSONValue?30 public let windDown: JSONValue?31 }32 public let mandateId: String33 /** every limit of the mandate, read strictly; it hashes to `hash` */34 public let mandate: TradingMandate35 public let hash: String36 public let enforcement: [MandateFieldEnforcement]37 public let derived: [MandateDerivedValue]38 /** `spw-principal-v1|api_key|<id>` for an API key: what `strategySha256` is the hash of */39 public let principalDescriptor: String?40 public let note: String?41 /** nil for a paper mandate: no signer, no passkey */42 public let live: Live?43}4445public struct MandatesAPI: Sendable {46 let client: APIClient47 public init(_ client: APIClient) { self.client = client }4849 private struct One: Decodable, Sendable { let mandate: TradingMandateRecord }5051 public func list() async throws -> [TradingMandateRecord] {52 struct R: Decodable, Sendable { let mandates: [TradingMandateRecord] }53 return try await client.get("/mandates", as: R.self).mandates54 }55 public func mandate(_ id: String) async throws -> TradingMandateRecord { try await client.get("/mandates/\(APIClient.segment(id))", as: One.self).mandate }5657 /**58 Create a mandate (state `created`: nothing is in force yet). The answer is checked against the request: the stored mandate59 must carry exactly the limits asked. The server protects this route with no Idempotency-Key: after a lost answer, read60 `list()` before creating again.61 */62 public func create(_ r: MandateCreateRequest, now: Date = Date()) async throws -> TradingMandateRecord {63 try r.validate()64 let m = try await client.post("/mandates", body: r, as: One.self).mandate65 guard let terms = m.mandate else { throw ApprovalError.unsupported("the created mandate cannot be read: \(m.mandateProblem ?? "unknown")") }66 try Self.check(mandate: terms, against: r)67 return m68 }6970 /**71 Step 1 of an approval. Verified before anything can be signed:72 - the mandate is read strictly, hashes to the stated hash, and is the one expected (the creation request, or the mandate displayed);73 - live: the signer mandate is read strictly, is exactly what this mandate compiles to (instruments, leverage, per-order cap,74 position cap, capital × leverage, frequency, floor, price band, expiry, principal, strategy), and its hash is challenge 1;75 - live: the approval intent names this mandate's hash and that signer mandate's hash, and its hash is challenge 2.76 A quoting (market-making) mandate is refused here: its signer shape and its quoting section are not this module's.77 */78 public func prepareApproval(id: String, expecting: MandateExpectation, locale: String, now: Date = Date()) async throws -> MandateApprovalSheet {79 struct Body: Encodable, Sendable { let locale: String }80 let a: JSONValue = try await client.post("/mandates/\(APIClient.segment(id))/approve/prepare", body: Body(locale: locale))81 return try Self.verify(sheet: a, id: id, expecting: expecting, rpId: client.configuration.rpId, now: now)82 }8384 static func verify(sheet a: JSONValue, id: String, expecting: MandateExpectation, rpId: String, now: Date) throws -> MandateApprovalSheet {85 let mandate = try TradingMandate(served: a["mandate"])86 guard let hash = a["hash"]?.stringValue, try mandate.hashHex() == hash else { throw ApprovalError.inconsistent("the mandate does not hash to the stated hash") }87 guard a["mandateId"]?.stringValue == id, mandate.mandateId == id else { throw ApprovalError.inconsistent("the sheet is for another mandate") }88 guard a["mode"]?.stringValue == mandate.mode else { throw ApprovalError.inconsistent("mode") }89 switch expecting {90 case .request(let r): try check(mandate: mandate, against: r)91 case .displayed(let m): guard m == mandate else { throw ApprovalError.inconsistent("the mandate to approve is not the mandate displayed") }92 }93 guard mandate.expiry > now else { throw ApprovalError.expired }94 let descriptor = a["principalDescriptor"]?.stringValue95 if mandate.principal.kind == "api_key" {96 guard descriptor == "spw-principal-v1|api_key|\(mandate.principal.id)" else { throw ApprovalError.inconsistent("principal descriptor") }97 } else { guard descriptor == nil else { throw ApprovalError.inconsistent("principal descriptor") } }98 let enforcement: [MandateFieldEnforcement] = try (a["enforcement"] ?? []).decode()99 let derived: [MandateDerivedValue] = try (a["derived"] ?? []).decode()100 guard let passkey = a["passkey"]?.boolValue else { throw ApprovalError.unsupported("the sheet does not say whether a passkey is needed") }101 guard passkey == mandate.isLive else { throw ApprovalError.inconsistent("a live mandate needs the passkey and a paper mandate needs none; the sheet says otherwise") }102 var live: MandateApprovalSheet.Live?103 if passkey {104 guard a["kind"]?.stringValue == "directional", a["quoting"] == nil, let s = a["signer"], s["shape"]?.stringValue == CompiledVenueMandate.domain else {105 throw ApprovalError.unsupported("a quoting mandate (or an unknown signer shape) is not approved from this module")106 }107 let compiled = try CompiledVenueMandate(served: s["mandate"])108 try check(compiled: compiled, against: mandate)109 if case .request(let r) = expecting, let acct = s["accountId"]?.stringValue {110 guard r.accountIds.contains(where: { $0.lowercased() == acct.lowercased() }) else { throw ApprovalError.inconsistent("the signer mandate is for a venue account that was not requested") }111 }112 try ApprovalBinding.requireStatedHash(s["hash"]?.stringValue, of: compiled, what: "signer mandate")113 guard let ackJSON = s["acknowledgement"], let ack = try? ackJSON.decode(MandateApprovalSheet.Acknowledgement.self), ack.sha256 == compiled.ackSha256 else {114 throw ApprovalError.inconsistent("the acknowledgement displayed is not the one the signer mandate carries")115 }116 guard let so = s["options"], let signerOptions = try? so.decode(PasskeyRequestOptions.self) else { throw ApprovalError.unsupported("no passkey request for the signer mandate") }117 let signer = try ApprovalBinding.verify(compiled, options: signerOptions, rpId: rpId)118119 guard let b = a["binding"], b["domain"]?.stringValue == MandateApprovalIntent.domain else { throw ApprovalError.unsupported("no binding intent in the sheet") }120 let intent = try MandateApprovalIntent(served: b["intent"])121 guard intent.mandateId == id, intent.tradingMandateHash == hash else { throw ApprovalError.inconsistent("the approval intent names another mandate or another hash") }122 guard intent.principal == mandate.principal.label else { throw ApprovalError.inconsistent("the approval intent names another principal") }123 guard intent.signer.shape == CompiledVenueMandate.domain, intent.signer.mandateHash == signer.digest.hex else { throw ApprovalError.inconsistent("the approval intent names another signer mandate") }124 guard intent.quotingSectionHash == nil else { throw ApprovalError.unsupported("the approval intent names a quoting section") }125 try RiskAPI.checkStamp(intent, statedExpiry: b["expiresAt"]?.intValue.map(Int.init), statedHash: b["hash"]?.stringValue, now: now)126 guard let bo = b["options"], let bindingOptions = try? bo.decode(PasskeyRequestOptions.self) else { throw ApprovalError.unsupported("no passkey request for the binding intent") }127 let binding = try ApprovalBinding.verify(intent, options: bindingOptions, rpId: rpId)128 live = .init(signer: signer, binding: binding, accountId: s["accountId"]?.stringValue, acknowledgement: ack, warning: s["warning"]?.stringValue,129 enforcedBySigner: s["enforcedBySigner"], trustedBySigner: s["trustedBySigner"], notEnforced: s["notEnforced"], windDown: s["windDown"])130 } else {131 guard a["signer"]?.isNull ?? true, a["binding"] == nil else { throw ApprovalError.inconsistent("a paper mandate carries a signer section") }132 }133 return MandateApprovalSheet(mandateId: id, mandate: mandate, hash: hash, enforcement: enforcement, derived: derived, principalDescriptor: descriptor, note: a["note"]?.stringValue, live: live)134 }135136 /**137 Step 2. Paper: the session alone. Live: `acknowledgementConfirmed` must be true — the owner read the acknowledgement of the138 sheet — then the passkey signs challenge 1 (signer) and challenge 2 (binding), and both assertions go in ONE request.139 */140 public func approve(_ sheet: MandateApprovalSheet, acknowledgementConfirmed: Bool, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> TradingMandateRecord {141 guard sheet.mandate.expiry > now else { throw ApprovalError.expired }142 guard let live = sheet.live else {143 return try await client.post("/mandates/\(APIClient.segment(sheet.mandateId))/approve", body: EmptyBody(), as: One.self).mandate144 }145 guard acknowledgementConfirmed else { throw ApprovalError.inconsistent("the acknowledgement was not confirmed") }146 try live.binding.object.requireCurrent(now)147 let rp = client.configuration.rpId148 let assertion = try await authenticator.assert(live.signer.options, rpId: rp)149 let bindingAssertion = try await authenticator.assert(live.binding.options, rpId: rp)150 return try await submitApproval(mandateId: sheet.mandateId, assertion: assertion, bindingAssertion: bindingAssertion)151 }152 /** Second half of a live `approve`: after a lost answer read `mandate(id)` (state `active` or `failed`) instead of signing again. */153 public func submitApproval(mandateId: String, assertion: PasskeyAssertion, bindingAssertion: PasskeyAssertion) async throws -> TradingMandateRecord {154 struct Body: Encodable, Sendable { let assertion: PasskeyAssertion; let bindingAssertion: PasskeyAssertion; let acknowledged: Bool }155 return try await client.post("/mandates/\(APIClient.segment(mandateId))/approve", body: Body(assertion: assertion, bindingAssertion: bindingAssertion, acknowledged: true), as: One.self).mandate156 }157158 /**159 Revoke: final, no passkey (it only removes authority). The API stops accepting orders under the mandate at once; live: the160 signer's copy is revoked first. Strictly reducing orders stay possible for the wind-down period.161 */162 public func revoke(id: String, cancelOpenOrders: Bool, detail: String? = nil) async throws -> MandateRevocationResult {163 struct Body: Encodable, Sendable { let cancelOpenOrders: Bool; let detail: String? }164 return try await client.post("/mandates/\(APIClient.segment(id))/revoke", body: Body(cancelOpenOrders: cancelOpenOrders, detail: detail.map { String($0.prefix(300)) }))165 }166167 /** Market making: settles quoting approvals whose answer was lost, and revokes quoting mandates the signer holds that no record accounts for. */168 public func recoverQuoting() async throws -> QuotingRecovery { try await client.post("/mandates/recover-quoting") }169170 // MARK: checks171172 /** The stored mandate must carry exactly what was asked: principal, mode, allowed markets, every cap and limit, leverage, expiry. */173 public static func check(mandate m: TradingMandate, against r: MandateCreateRequest) throws {174 func same(_ a: String, _ b: String, _ what: String) throws { guard ExecutionDecimal.equal(a, b) else { throw ApprovalError.inconsistent(what) } }175 guard m.principal == r.principal else { throw ApprovalError.inconsistent("principal") }176 guard m.mode == r.mode.rawValue else { throw ApprovalError.inconsistent("mode") }177 guard m.instruments == r.instruments else { throw ApprovalError.inconsistent("allowed markets") }178 guard m.marketKinds == r.marketKinds else { throw ApprovalError.inconsistent("market kinds") }179 guard m.orderTypes == r.orderTypes else { throw ApprovalError.inconsistent("order types") }180 if let v = r.venues { guard m.venues == v else { throw ApprovalError.inconsistent("venues") } }181 for i in m.instruments { guard let venue = i.split(separator: ":").first, m.venues.contains(String(venue)) else { throw ApprovalError.inconsistent("an allowed market is on a venue outside the mandate") } }182 guard m.accounts.count <= r.accountIds.count else { throw ApprovalError.inconsistent("more accounts than requested") }183 try same(m.maxCapitalUsd, r.maxCapitalUsd, "budget cap"); try same(m.maxOrderNotionalUsd, r.maxOrderNotionalUsd, "per-order cap"); try same(m.maxPositionNotionalUsd, r.maxPositionNotionalUsd, "position cap")184 try same(m.maxLeverage, r.maxLeverage, "max leverage"); try same(m.maxDailyLossUsd, r.maxDailyLossUsd, "daily loss limit"); try same(m.floorEquityUsd, r.floorEquityUsd, "equity floor")185 try same(m.maxFeeUsd, r.maxFeeUsd, "fee bound")186 guard m.notBefore == m.createdAt, m.notAfter - m.createdAt == r.days * 86_400 else { throw ApprovalError.inconsistent("expiry") }187 guard m.frequency == r.frequency else { throw ApprovalError.inconsistent("frequency") }188 guard m.maxSlippageBps == r.maxSlippageBps else { throw ApprovalError.inconsistent("slippage bound") }189 guard m.stopConditions == r.stopConditions else { throw ApprovalError.inconsistent("stop conditions") }190 guard m.label == r.label.trimmingCharacters(in: .whitespacesAndNewlines) else { throw ApprovalError.inconsistent("label") }191 let strategy = r.principal.kind == "api_key" ? TradingMandate.principalDescriptorSha256(kind: "api_key", id: r.principal.id) : r.strategySha256192 guard m.strategySha256.value == strategy else { throw ApprovalError.inconsistent("strategy") }193 }194195 /**196 The signer mandate must be what `compileToVenueMandate` (packages/trading/src/mandate/trading-mandate.ts) derives from the197 trading mandate — recomputed here with exact decimal arithmetic. What the signer stores can then never be wider than what is shown.198 */199 public static func check(compiled c: CompiledVenueMandate, against m: TradingMandate) throws {200 func bad(_ s: String) -> ApprovalError { .inconsistent("signer mandate: \(s)") }201 guard m.isLive else { throw bad("a paper mandate has no signer form") }202 guard c.mandateId == m.mandateId else { throw bad("mandate id") }203 guard c.agentId == m.principal.id else { throw bad("principal") }204 guard let strategy = m.strategySha256.value, c.strategySha256 == strategy else { throw bad("strategy") }205 let accounts = m.accounts.filter { $0.kind == "venue_account" && $0.venue == c.venue }206 guard accounts.count == 1, accounts[0].account?.lowercased() == c.account, accounts[0].network == c.network else { throw bad("venue account") }207 let wanted = m.instruments.filter { $0.hasPrefix("\(c.venue):") }208 guard !wanted.isEmpty, Set(wanted) == Set(c.instruments.map(\.instrument)), wanted.count == c.instruments.count else { throw bad("allowed markets") }209 let lev = try ExecutionDecimal.canon(m.maxLeverage)210 guard let leverage = UInt32(lev), leverage >= 1 else { throw bad("the venue takes integer leverage") }211 for i in c.instruments {212 guard i.maxLeverage == Int(leverage) else { throw bad("max leverage of \(i.instrument)") }213 guard ExecutionDecimal.equal(i.maxPositionNotional, m.maxPositionNotionalUsd) else { throw bad("position cap of \(i.instrument)") }214 }215 guard ExecutionDecimal.equal(c.maxOrderNotional, m.maxOrderNotionalUsd) else { throw bad("per-order cap") }216 guard try ExecutionDecimal.equal(c.maxGrossExposure, ExecutionDecimal.multiply(m.maxCapitalUsd, by: leverage)) else { throw bad("gross exposure is not budget cap × leverage") }217 guard c.maxOrdersPerDay == m.frequency.perDay, c.maxOrdersPerHour == m.frequency.perHour else { throw bad("frequency") }218 guard try ExecutionDecimal.equal(c.maxDailyTurnover, ExecutionDecimal.multiply(m.maxOrderNotionalUsd, by: UInt32(m.frequency.perDay))) else { throw bad("daily turnover is not per-order cap × orders per day") }219 guard ExecutionDecimal.equal(c.floorEquity, m.floorEquityUsd) else { throw bad("loss limit (equity floor)") }220 guard c.maxPriceDeviationBps == m.maxSlippageBps else { throw bad("price band") }221 guard c.createdAt == m.createdAt, c.expiresAt == m.notAfter else { throw bad("expiry") }222 }223}224