Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Execution/MandateModels.swift3// Description: Trading mandates as the owner's routes answer them (services/api/src/mandates/service.ts `view`, `create`, `revoke`):4// the stored record with its state, its usage and the field-by-field table of WHO enforces each limit (the isolated5// signer, or only the API), and the creation request — in which every limit is stated by the caller, none defaulted.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011/**12 Who enforces one field of a mandate. `signer`: the isolated signer enforces it as approved. `signer_partial`: the signer enforces a13 related bound, the rest is the API's. `api_only`: only the API enforces it — a compromised API could ignore it. `not_applicable`.14 The screen shows this table verbatim next to the limits.15 */16public struct MandateFieldEnforcement: Codable, Sendable, Hashable {17 public let field: String18 public let enforcedBy: String19 public let signerField: String?20 public let note: String21}22public struct MandateDerivedValue: Codable, Sendable, Hashable { public let field: String; public let value: String; public let from: String }2324/** One trading mandate as stored. */25public struct TradingMandateRecord: Decodable, Sendable, Equatable, Identifiable {26 public struct SignerRef: Decodable, Sendable, Equatable { public let shape: String; public let accountId: String?; public let mandateId: String?; public let hash: String }27 public struct Stop: Decodable, Sendable, Equatable { public let code: String; public let at: Int?; public let detail: String? }28 public struct Approval: Decodable, Sendable, Equatable {29 public let domain: String; public let hash: String; public let tradingMandateHash: String; public let signerMandateHash: String30 public let quotingSectionHash: String?; public let credentialId: String?; public let approvedAt: Int?31 }32 public struct Integrity: Decodable, Sendable, Equatable { public let ok: Bool; public let reason: String? }33 public struct Usage: Decodable, Sendable, Equatable {34 public let ordersAccepted, ordersRejected, consecutiveRejects: Int?35 public let notionalTotal: String?36 public let peakEquity, startEquity: String?37 public let lastOrderAt: Int?38 public let ordersLastMinute, ordersLastHour, ordersToday, openOrders: Int?39 }4041 public let id: String42 /** `directional` or `quoting` (market making) */43 public let kind: String?44 public let principal: MandatePrincipal45 public let mode: String46 /** `created`, `pending_signer`, `active`, `revoked`, `failed` — verbatim */47 public let state: String48 /** `not_approved`, `pending`, `active`, `wind_down` (reducing orders only), `ended` — verbatim */49 public let phase: String50 /** the recorded hash of the mandate (hex) */51 public let hash: String52 /** The limits, ONLY when the served object was read strictly and hashes to `hash`; otherwise nil and `mandateProblem` says why. */53 public let mandate: TradingMandate?54 public let mandateProblem: String?55 public let mandateRaw: JSONValue56 public let label: String?57 public let enforcement: [MandateFieldEnforcement]58 public let derived: [MandateDerivedValue]?59 public let signer: SignerRef?60 public let stop: Stop?61 public let revocation: JSONValue?62 public let approval: Approval?63 /** the server's own re-verification of the stored approval; `ok == false` makes the mandate unusable */64 public let integrity: Integrity?65 public let usage: Usage?66 /** quoting mandates: the sibling record, shown by the market-making domain */67 public let quoting: JSONValue?68 /** unix ms */69 public let createdAt: Int?70 public let approvedAt: Int?71 public let revokedAt: Int?72 public let notBefore: Int?73 public let notAfter: Int?7475 public var isQuoting: Bool { kind == "quoting" || !(quoting?.isNull ?? true) }76 /** True only for an approved mandate inside its validity window, as the SERVER states it. Never inferred from dates by the client. */77 public var isActive: Bool { state == "active" && phase == "active" }7879 enum CodingKeys: String, CodingKey { case id, kind, principal, mode, state, phase, hash, mandate, label, enforcement, derived, signer, stop, revocation, approval, integrity, usage, quoting, createdAt, approvedAt, revokedAt, notBefore, notAfter }80 public init(from decoder: Decoder) throws {81 let c = try decoder.container(keyedBy: CodingKeys.self)82 id = try c.decode(String.self, forKey: .id); kind = try c.decodeIfPresent(String.self, forKey: .kind); principal = try c.decode(MandatePrincipal.self, forKey: .principal)83 mode = try c.decode(String.self, forKey: .mode); state = try c.decode(String.self, forKey: .state); phase = try c.decode(String.self, forKey: .phase); hash = try c.decode(String.self, forKey: .hash)84 mandateRaw = try c.decode(JSONValue.self, forKey: .mandate)85 do {86 let m = try TradingMandate(served: mandateRaw)87 guard try m.hashHex() == hash else { throw ApprovalError.inconsistent("the mandate does not hash to its recorded hash") }88 guard m.mandateId == id, m.principal == principal, m.mode == mode else { throw ApprovalError.inconsistent("the record names another id, principal or mode than the mandate it stores") }89 mandate = m; mandateProblem = nil90 } catch { mandate = nil; mandateProblem = (error as? LocalizedError)?.errorDescription ?? String(describing: error) }91 label = try c.decodeIfPresent(String.self, forKey: .label)92 enforcement = try c.decodeIfPresent([MandateFieldEnforcement].self, forKey: .enforcement) ?? []93 derived = try c.decodeIfPresent([MandateDerivedValue].self, forKey: .derived); signer = try c.decodeIfPresent(SignerRef.self, forKey: .signer); stop = try c.decodeIfPresent(Stop.self, forKey: .stop)94 revocation = try c.decodeIfPresent(JSONValue.self, forKey: .revocation); approval = try c.decodeIfPresent(Approval.self, forKey: .approval); integrity = try c.decodeIfPresent(Integrity.self, forKey: .integrity)95 usage = try c.decodeIfPresent(Usage.self, forKey: .usage); quoting = try c.decodeIfPresent(JSONValue.self, forKey: .quoting)96 createdAt = try c.decodeIfPresent(Int.self, forKey: .createdAt); approvedAt = try c.decodeIfPresent(Int.self, forKey: .approvedAt); revokedAt = try c.decodeIfPresent(Int.self, forKey: .revokedAt)97 notBefore = try c.decodeIfPresent(Int.self, forKey: .notBefore); notAfter = try c.decodeIfPresent(Int.self, forKey: .notAfter)98 }99}100101/**102 POST /mandates (`MandateCreateSchema`). There is NO default in this initializer: the budget cap, the per-order cap, the position103 cap, the two loss limits, the allowed markets, the max leverage and the expiry are each stated by the caller, as are the order104 types, the frequency, the slippage and fee bounds and the stop conditions. A quoting (market-making) mandate is not created here.105 */106public struct MandateCreateRequest: Encodable, Sendable, Equatable {107 public let principal: MandatePrincipal108 /** `paper` or `live` */109 public let mode: RiskMode110 /** ids of the wallet's own accounts: paper accounts (paper) or venue accounts (live) */111 public let accountIds: [String]112 /** nil: the venues of the accounts */113 public let venues: [String]?114 public let instruments: [String]115 public let marketKinds: [String]116 public let orderTypes: [String]117 public let maxCapitalUsd, maxOrderNotionalUsd, maxPositionNotionalUsd, maxLeverage, maxDailyLossUsd, floorEquityUsd: String118 /** validity in days from the creation (1…365; a live derivative mandate lasts at most 30) */119 public let days: Int120 public let frequency: TradingMandate.Frequency121 public let maxSlippageBps: Int122 public let maxFeeUsd: String123 public let stopConditions: [TradingMandate.StopCondition]124 /** agents: the strategy version the mandate is approved for (required by the server); nil for an API key */125 public let strategySha256: String?126 public let label: String127 public let locale: String128129 public init(principal: MandatePrincipal, mode: RiskMode, accountIds: [String], venues: [String]?, allowedInstruments: [String], marketKinds: [String], orderTypes: [String],130 budgetCapUsd: String, perOrderCapUsd: String, positionCapUsd: String, maxLeverage: String, dailyLossLimitUsd: String, floorEquityUsd: String, expiresInDays: Int,131 frequency: TradingMandate.Frequency, maxSlippageBps: Int, maxFeeUsd: String, stopConditions: [TradingMandate.StopCondition], strategySha256: String?, label: String, locale: String) {132 self.principal = principal; self.mode = mode; self.accountIds = accountIds; self.venues = venues; instruments = allowedInstruments; self.marketKinds = marketKinds; self.orderTypes = orderTypes133 maxCapitalUsd = budgetCapUsd; maxOrderNotionalUsd = perOrderCapUsd; maxPositionNotionalUsd = positionCapUsd; self.maxLeverage = maxLeverage; maxDailyLossUsd = dailyLossLimitUsd; self.floorEquityUsd = floorEquityUsd134 days = expiresInDays; self.frequency = frequency; self.maxSlippageBps = maxSlippageBps; self.maxFeeUsd = maxFeeUsd; self.stopConditions = stopConditions; self.strategySha256 = strategySha256135 self.label = label; self.locale = locale136 }137138 /** Refuses what the server would refuse about the limits themselves, before anything is sent (a missing or zero limit never leaves the device). */139 public func validate() throws {140 func bad(_ s: String) -> APIError { APIError(status: 0, code: "invalid_mandate", message: s) }141 for (x, k) in [(maxCapitalUsd, "budget cap"), (maxOrderNotionalUsd, "per-order cap"), (maxPositionNotionalUsd, "position cap"), (maxLeverage, "max leverage"), (maxDailyLossUsd, "daily loss limit")] {142 guard ExecutionDecimal.isPositive(x) else { throw bad("the \(k) must be a positive decimal") }143 }144 guard ExecutionDecimal.isNonNegative(floorEquityUsd), ExecutionDecimal.isNonNegative(maxFeeUsd) else { throw bad("the equity floor and the fee bound must be decimals") }145 guard !instruments.isEmpty, !accountIds.isEmpty, !marketKinds.isEmpty, !orderTypes.isEmpty else { throw bad("allowed markets, accounts, market kinds and order types cannot be empty") }146 guard (1...365).contains(days) else { throw bad("the expiry must be between 1 and 365 days") }147 guard (1...60).contains(label.trimmingCharacters(in: .whitespacesAndNewlines).utf16.count) else { throw bad("the label must have 1 to 60 characters") }148 if principal.kind == "agent" { guard strategySha256 != nil else { throw bad("an agent mandate names the strategy version it is approved for") } }149 }150}151152/** What the caller holds the approval sheet against. */153public enum MandateExpectation: Sendable {154 /** the creation request of this session: every limit, scope and the expiry of the mandate must be the request's */155 case request(MandateCreateRequest)156 /** a mandate created earlier and DISPLAYED from its record (`TradingMandateRecord.mandate`): the sheet must show that very mandate */157 case displayed(TradingMandate)158}159160public struct MandateRevocationResult: Decodable, Sendable, Equatable {161 public let mandate: TradingMandateRecord162 /** cancels requested for the orders resting under the mandate */163 public let cancelled: Int164 /** live: whether the isolated signer revoked its own copy; nil when there was nothing to revoke there; false = it will be asked again */165 public let signerRevoked: Bool?166 public let signerError: String?167}168169public struct QuotingRecovery: Decodable, Sendable, Equatable { public let adopted: [String]; public let revoked: [String]; public let pending: [String] }170