SPB Git

Repository Public

MandateCanonical.swift 22.3 KB 378 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SPWalletCore9// File             : Sources/SPWalletCore/Domains/Execution/MandateCanonical.swift10// Description      : The three objects behind the approval of a trading11//                    mandate, byte for byte the backend's:12//                    `SPW-TRADING-MANDATE-v1`13//                    (packages/trading/src/mandate/trading-mandate.ts14//                    `tradingMandateBytes`) — what a principal may do, inside15//                    which limits, until when; `SPW-VENUE-MANDATE-v1`16//                    (packages/derivatives/src/live/mandate.ts17//                    `venueMandateBytes`) — the derivative mandate COMPILED18//                    from it, the only part the isolated signer stores and19//                    enforces; `SPW-TRADING-MANDATE-APPROVAL-v1`20//                    (services/api/src/mandates/service.ts) — the API-side21//                    intent that names the hashes of the two. The first is22//                    never a challenge by itself; the two others are, and both23//                    are object-bound.24// Module           : SPWalletCore25// Repository       : https://git.spboucher.ai/sp-wallet-core26// Created          : 2026-11-1827// Last Modified    : 2026-11-1828//29// =============================================================================30// AUTHOR & PROFESSIONAL AFFILIATION31// =============================================================================32//33// Author           : Simon-Pierre Boucher34// Position         : Professor of Finance35// Institution      : Université du Québec en Outaouais (UQO)36// Department       : Département des sciences administratives37// Organization     : SP Boucher38//39// Website          : https://spboucher.ai40// Git              : https://git.spboucher.ai41//42// =============================================================================43// OFFICIAL CONTACT DIRECTORY44// =============================================================================45//46// General          : info@spboucher.ai47// Professional     : contact@spboucher.ai48// Direct           : simon@spboucher.ai49// Research         : research@spboucher.ai50// Development      : dev@spboucher.ai51// Support          : support@spboucher.ai52// Security/Admin   : admin@spboucher.ai53// Notifications    : notifications@spboucher.ai54//55// Preferred Contact: support@spboucher.ai56//57// =============================================================================58// COPYRIGHT & INTELLECTUAL PROPERTY59// =============================================================================60//61// Copyright (c) 202662// Simon-Pierre Boucher63//64// All rights reserved where applicable.65//66// This file is governed by the applicable project license,67// copyright notices, institutional agreements and relevant law.68//69// Unless expressly authorized by the applicable license or70// rights holder, copying, redistribution, sublicensing,71// publication and commercial exploitation are not permitted.72//73// Existing third-party rights and notices remain unaffected.74//75// =============================================================================76// CONFIDENTIALITY & SECURITY77// =============================================================================78//79// Classification   : Public80// Distribution     : Public repository; use is governed by the project license81// Security Contact : admin@spboucher.ai82//83// Access to this source does not independently grant permission84// to redistribute or disclose confidential materials.85//86// Do not embed credentials, private keys, access tokens,87// certificates or confidential personal information.88//89// =============================================================================90// LICENSE & MAINTENANCE91// =============================================================================92//93// License          : None specified (no license file in this repository)94// Maintainer       : Simon-Pierre Boucher95// Technical Contact: dev@spboucher.ai96//97// =============================================================================98// END OF SP BOUCHER SOURCE HEADER99// =============================================================================100101import Foundation102import CryptoKit103104/** A member the schema declares nullable: ALWAYS present in the served object, as a value or as an explicit `null`. */105public struct ExecutionNullable<T: Codable & Sendable & Equatable>: Codable, Sendable, Equatable {106    public let value: T?107    public init(_ value: T?) { self.value = value }108    public init(from decoder: Decoder) throws { let c = try decoder.singleValueContainer(); value = c.decodeNil() ? nil : try c.decode(T.self) }109    public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); if let value { try c.encode(value) } else { try c.encodeNil() } }110}111112enum ExecutionPattern {113    static func matches(_ s: String, _ pattern: String) -> Bool { s.range(of: "^(?:\(pattern))$", options: .regularExpression) != nil && !s.contains("\n") }114    static let id = "[a-z0-9][a-z0-9-]{0,31}"115    static let sha = "[0-9a-f]{64}"116    static let uuid = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"117    static let principalId = "[A-Za-z0-9._:-]{1,64}"118    static let instrument = "[a-z0-9][a-z0-9-]{0,31}:(\\*|[A-Za-z0-9._/-]{1,60})"119    static let address = "0x[0-9a-f]{40}"120    static let signerInstrument = "hyperliquid:[A-Za-z0-9]{1,15}"121    /** unix seconds / milliseconds: positive, exact in a JavaScript number */122    static func timestamp(_ t: Int) -> Bool { t > 0 && Int64(t) <= ExecutionStableJSON.maxSafeInteger }123}124125public struct MandatePrincipal: Codable, Sendable, Hashable {126    /** `agent` or `api_key` */127    public let kind: String128    public let id: String129    public init(kind: String, id: String) { self.kind = kind; self.id = id }130    public var label: String { "\(kind):\(id)" }131}132133/** `SPW-TRADING-MANDATE-v1`. Immutable: a change is a new mandate. Times are unix SECONDS. Money is exact decimal text, in USD. */134public struct TradingMandate: Codable, Sendable, Equatable {135    public static let domain = "SPW-TRADING-MANDATE-v1"136137    /** `vault` (an agent vault of the wallet: vaultIndex, address, network) or `venue_account` (venue, network, account). */138    public struct Account: Codable, Sendable, Equatable {139        public let kind: String140        public let vaultIndex: Int?141        public let address: String?142        public let venue: String?143        public let network: String144        public let account: String?145        var key: String { kind == "vault" ? "vault|\(network)|\(vaultIndex ?? -1)|\(address ?? "")" : "venue_account|\(venue ?? "")|\(network)|\(account ?? "")" }146    }147    /** Declarative: when one is met the mandate takes no new risk. `loss_gte` (usd), `drawdown_gte` (bps), `consecutive_rejects_gte` (count), `data_stale_gte` / `signer_unreachable_gte` (ms). */148    public struct StopCondition: Codable, Sendable, Equatable {149        public let kind: String150        public let usd: String?151        public let bps: Int?152        public let count: Int?153        public let ms: Int?154        public init(kind: String, usd: String? = nil, bps: Int? = nil, count: Int? = nil, ms: Int? = nil) { self.kind = kind; self.usd = usd; self.bps = bps; self.count = count; self.ms = ms }155        func key() throws -> String {156            switch kind {157            case "loss_gte": guard let usd, ExecutionDecimal.isPositive(usd), bps == nil, count == nil, ms == nil else { break }; return "\(kind)|\(try ExecutionDecimal.canon(usd))"158            case "drawdown_gte": guard let bps, (1...10_000).contains(bps), usd == nil, count == nil, ms == nil else { break }; return "\(kind)|\(bps)"159            case "consecutive_rejects_gte": guard let count, (1...1000).contains(count), usd == nil, bps == nil, ms == nil else { break }; return "\(kind)|\(count)"160            case "data_stale_gte", "signer_unreachable_gte": guard let ms, ms >= 1, Int64(ms) <= ExecutionStableJSON.maxSafeInteger, usd == nil, bps == nil, count == nil else { break }; return "\(kind)|\(ms)"161            default: throw ApprovalError.unsupported("stop condition \(kind)")162            }163            throw ApprovalError.unsupported("stop condition \(kind) is malformed")164        }165    }166    public struct Frequency: Codable, Sendable, Equatable {167        public let perMinute, perHour, perDay: Int168        public init(perMinute: Int, perHour: Int, perDay: Int) { self.perMinute = perMinute; self.perHour = perHour; self.perDay = perDay }169    }170171    public let v: Int172    public let mandateId: String173    public let principal: MandatePrincipal174    /** the wallets / accounts the principal may trade from */175    public let accounts: [Account]176    public let venues: [String]177    public let networks: [String]178    /** ALLOWED MARKETS: `venue:symbol`; `venue:*` exists in a paper mandate only */179    public let instruments: [String]180    /** `spot`, `perp` */181    public let marketKinds: [String]182    public let orderTypes: [String]183    /** BUDGET CAP: the capital the principal may put at risk */184    public let maxCapitalUsd: String185    /** PER-ORDER CAP */186    public let maxOrderNotionalUsd: String187    /** the same limit for each instrument */188    public let maxPositionNotionalUsd: String189    /** MAX LEVERAGE */190    public let maxLeverage: String191    /** LOSS LIMIT of a day: no new risk once today's loss reaches it */192    public let maxDailyLossUsd: String193    /** LOSS LIMIT in total, as a floor: no new risk while the equity of the mandated accounts is below it */194    public let floorEquityUsd: String195    public let createdAt, notBefore: Int196    /** EXPIRY, unix seconds */197    public let notAfter: Int198    public let frequency: Frequency199    public let maxSlippageBps: Int200    /** highest fee of ONE order, USD */201    public let maxFeeUsd: String202    public let stopConditions: [StopCondition]203    /** `paper` or `live` */204    public let mode: String205    /** SHA-256 of the strategy code (agents); for an API key the server stores SHA-256 of `spw-principal-v1|api_key|<key id>`; `null` in the schema when there is none */206    public let strategySha256: ExecutionNullable<String>207    public let label: String208209    public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(notAfter)) }210    public var isLive: Bool { mode == "live" }211212    /** Strict reading of a served mandate: an unknown field, a missing one or a malformed value is a refusal. */213    public init(served: JSONValue?) throws {214        self = try ExecutionStrict.decode(TradingMandate.self, from: served, path: "mandate")215        _ = try canonicalBytes()216    }217218    /**219     The backend's `tradingMandateBytes`: length-prefixed pairs in a fixed order, every list sorted (UTF-16 order) and joined by ",".220     The value constraints of `TradingMandateSchema` that keep this encoding unambiguous are enforced first: no element of a221     joined list may contain "," or "|" (the schema leaves a venue ACCOUNT string free; this code refuses those two characters in it).222     */223    public func canonicalBytes() throws -> Data {224        typealias P = ExecutionPattern225        func bad(_ what: String) -> ApprovalError { .unsupported("mandate.\(what)") }226        guard v == 1 else { throw bad("v \(v)") }227        guard P.matches(mandateId, P.uuid) else { throw bad("mandateId") }228        guard ["agent", "api_key"].contains(principal.kind), P.matches(principal.id, P.principalId) else { throw bad("principal") }229        guard (1...8).contains(accounts.count), (1...8).contains(venues.count), (1...8).contains(networks.count), (1...24).contains(instruments.count),230              (1...2).contains(marketKinds.count), !orderTypes.isEmpty, stopConditions.count <= 10 else { throw bad("list sizes") }231        for a in accounts {232            guard P.matches(a.network, P.id) else { throw bad("accounts.network") }233            switch a.kind {234            case "vault":235                guard let i = a.vaultIndex, (1...100_000).contains(i), let addr = a.address, (20...110).contains(addr.utf16.count), a.venue == nil, a.account == nil else { throw bad("accounts (vault)") }236                guard !addr.contains(where: { ",|\n".contains($0) }) else { throw bad("accounts.address") }237            case "venue_account":238                guard let venue = a.venue, P.matches(venue, P.id), let acct = a.account, (1...110).contains(acct.utf16.count), a.vaultIndex == nil, a.address == nil else { throw bad("accounts (venue_account)") }239                guard !acct.contains(where: { ",|\n".contains($0) }) else { throw bad("accounts.account") }240            default: throw bad("accounts.kind \(a.kind)")241            }242        }243        guard venues.allSatisfy({ P.matches($0, P.id) }), networks.allSatisfy({ P.matches($0, P.id) }) else { throw bad("venues / networks") }244        guard instruments.allSatisfy({ P.matches($0, P.instrument) }) else { throw bad("instruments") }245        guard marketKinds.allSatisfy({ ["spot", "perp"].contains($0) }) else { throw bad("marketKinds") }246        guard orderTypes.allSatisfy({ ["market", "limit", "stop", "take_profit"].contains($0) }) else { throw bad("orderTypes") }247        for (x, k) in [(maxCapitalUsd, "maxCapitalUsd"), (maxOrderNotionalUsd, "maxOrderNotionalUsd"), (maxPositionNotionalUsd, "maxPositionNotionalUsd"), (maxLeverage, "maxLeverage"), (maxDailyLossUsd, "maxDailyLossUsd")] {248            guard ExecutionDecimal.isPositive(x) else { throw bad(k) }249        }250        guard ExecutionDecimal.isNonNegative(floorEquityUsd) else { throw bad("floorEquityUsd") }251        guard ExecutionDecimal.isNonNegative(maxFeeUsd) else { throw bad("maxFeeUsd") }252        guard P.timestamp(createdAt), P.timestamp(notBefore), P.timestamp(notAfter) else { throw bad("times") }253        guard (1...600).contains(frequency.perMinute), (1...10_000).contains(frequency.perHour), (1...500).contains(frequency.perDay) else { throw bad("frequency") }254        guard (1...2000).contains(maxSlippageBps) else { throw bad("maxSlippageBps") }255        guard ["paper", "live"].contains(mode) else { throw bad("mode") }256        if let s = strategySha256.value { guard P.matches(s, P.sha) else { throw bad("strategySha256") } }257        guard (1...60).contains(label.utf16.count) else { throw bad("label") }258259        let sorted: ([String]) -> String = { $0.sorted(by: executionCodeUnitOrder).joined(separator: ",") }260        let c = ExecutionDecimal.canon261        var w = CanonicalWriter(domain: Self.domain)262        w.field("v", "1"); w.field("mandateId", mandateId); w.field("principal.kind", principal.kind); w.field("principal.id", principal.id)263        w.field("accounts", sorted(accounts.map(\.key))); w.field("venues", sorted(venues)); w.field("networks", sorted(networks))264        w.field("instruments", sorted(instruments)); w.field("marketKinds", sorted(marketKinds)); w.field("orderTypes", sorted(orderTypes))265        w.field("maxCapitalUsd", try c(maxCapitalUsd)); w.field("maxOrderNotionalUsd", try c(maxOrderNotionalUsd)); w.field("maxPositionNotionalUsd", try c(maxPositionNotionalUsd))266        w.field("maxLeverage", try c(maxLeverage)); w.field("maxDailyLossUsd", try c(maxDailyLossUsd)); w.field("floorEquityUsd", try c(floorEquityUsd))267        w.field("createdAt", createdAt); w.field("notBefore", notBefore); w.field("notAfter", notAfter)268        w.field("frequency.perMinute", frequency.perMinute); w.field("frequency.perHour", frequency.perHour); w.field("frequency.perDay", frequency.perDay)269        w.field("maxSlippageBps", maxSlippageBps); w.field("maxFeeUsd", try c(maxFeeUsd)); w.field("stopConditions", sorted(try stopConditions.map { try $0.key() }))270        w.field("mode", mode); w.field("strategySha256", strategySha256.value ?? ""); w.field("label", label)271        return w.data272    }273    /** `tradingMandateHashHex`: the hash the approval intent names. */274    public func hashHex() throws -> String { Data(SHA256.hash(data: try canonicalBytes())).hex }275276    /** `principalDescriptorSha256` of mandates/service.ts: what the server stores as `strategySha256` for an API key. */277    public static func principalDescriptorSha256(kind: String, id: String) -> String { Data(SHA256.hash(data: Data("spw-principal-v1|\(kind)|\(id)".utf8))).hex }278}279280/**281 `SPW-VENUE-MANDATE-v1`: the derivative mandate the ISOLATED SIGNER stores and enforces (Hyperliquid). Its hash is the challenge of282 the first passkey prompt of a live approval. Times are unix seconds.283 */284public struct CompiledVenueMandate: Codable, Sendable, Equatable, PasskeyApprovable {285    public static let domain = "SPW-VENUE-MANDATE-v1"286    public struct Instrument: Codable, Sendable, Equatable {287        public let instrument: String288        /** highest leverage SETTING under which the signer signs an order that can add exposure */289        public let maxLeverage: Int290        public let maxPositionNotional: String291    }292    public let v: Int293    public let mandateId: String294    /** the venue authorization this mandate extends; revoking either stops the mandate */295    public let authorizationId: String296    public let keyId: String297    public let venue: String298    public let network: String299    public let account: String300    public let agentAddress: String301    public let strategySha256: String302    public let agentId: String303    public let instruments: [Instrument]304    public let maxOrderNotional: String305    public let maxGrossExposure: String306    public let maxOrdersPerDay: Int307    public let maxOrdersPerHour: Int308    public let maxDailyTurnover: String309    /** loss limit: below this account value the signer signs only reduce-only orders and cancels */310    public let floorEquity: String311    public let maxPriceDeviationBps: Int312    public let createdAt, expiresAt: Int313    /** SHA-256 of the jurisdiction acknowledgement displayed at the approval */314    public let ackSha256: String315316    public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }317318    public init(served: JSONValue?) throws {319        self = try ExecutionStrict.decode(CompiledVenueMandate.self, from: served, path: "signer.mandate")320        _ = try canonicalBytes()321    }322323    public func canonicalBytes() throws -> Data {324        typealias P = ExecutionPattern325        func bad(_ what: String) -> ApprovalError { .unsupported("signer.mandate.\(what)") }326        guard v == 1 else { throw bad("v \(v)") }327        guard P.matches(mandateId, P.uuid), P.matches(authorizationId, P.uuid) else { throw bad("ids") }328        guard (8...80).contains(keyId.utf16.count), !keyId.contains("\n") else { throw bad("keyId") }329        guard venue == "hyperliquid", ["mainnet", "testnet"].contains(network) else { throw bad("venue / network") }330        guard P.matches(account, P.address), P.matches(agentAddress, P.address) else { throw bad("account / agentAddress") }331        guard P.matches(strategySha256, P.sha), P.matches(ackSha256, P.sha), P.matches(agentId, P.principalId) else { throw bad("strategySha256 / ackSha256 / agentId") }332        guard (1...8).contains(instruments.count) else { throw bad("instruments") }333        for i in instruments { guard P.matches(i.instrument, P.signerInstrument), (1...20).contains(i.maxLeverage), ExecutionDecimal.isPositive(i.maxPositionNotional) else { throw bad("instruments.\(i.instrument)") } }334        for (x, k) in [(maxOrderNotional, "maxOrderNotional"), (maxGrossExposure, "maxGrossExposure"), (maxDailyTurnover, "maxDailyTurnover"), (floorEquity, "floorEquity")] { guard ExecutionDecimal.isPositive(x) else { throw bad(k) } }335        guard (1...500).contains(maxOrdersPerDay), (1...60).contains(maxOrdersPerHour), (10...2000).contains(maxPriceDeviationBps) else { throw bad("counts") }336        guard P.timestamp(createdAt), P.timestamp(expiresAt) else { throw bad("times") }337338        let c = ExecutionDecimal.canon339        let inst = try instruments.sorted { executionCodeUnitOrder($0.instrument, $1.instrument) }.map { "\($0.instrument)|\($0.maxLeverage)|\(try c($0.maxPositionNotional))" }.joined(separator: ",")340        var w = CanonicalWriter(domain: Self.domain)341        w.field("v", "1"); w.field("mandateId", mandateId); w.field("authorizationId", authorizationId); w.field("keyId", keyId); w.field("venue", venue); w.field("network", network); w.field("account", account)342        w.field("agentAddress", agentAddress); w.field("strategySha256", strategySha256); w.field("agentId", agentId)343        w.field("instruments", inst)344        w.field("maxOrderNotional", try c(maxOrderNotional)); w.field("maxGrossExposure", try c(maxGrossExposure)); w.field("maxOrdersPerDay", maxOrdersPerDay); w.field("maxOrdersPerHour", maxOrdersPerHour)345        w.field("maxDailyTurnover", try c(maxDailyTurnover)); w.field("floorEquity", try c(floorEquity)); w.field("maxPriceDeviationBps", maxPriceDeviationBps)346        w.field("createdAt", createdAt); w.field("expiresAt", expiresAt); w.field("ackSha256", ackSha256)347        return w.data348    }349}350351/**352 `SPW-TRADING-MANDATE-APPROVAL-v1`: what the second passkey prompt of a live approval commits to on the API side — the FULL353 trading mandate hash (every field, the API-only ones included) and the hash of the signer mandate compiled from it.354 Verified by the API against its own credentials table: it protects the stored record against alteration, not against a compromised API.355 */356public struct MandateApprovalIntent: Codable, Sendable, Equatable, ExecutionStampedIntent {357    public static let domain = "SPW-TRADING-MANDATE-APPROVAL-v1"358    public struct Signer: Codable, Sendable, Equatable { public let shape: String; public let mandateHash: String }359    public let v: Int360    public let kind: String361    public let mandateId: String362    public let tradingMandateHash: String363    /** `<kind>:<id>` */364    public let principal: String365    public let mode: String366    public let signer: Signer367    /** quoting mandates only; the key is absent otherwise */368    public let quotingSectionHash: String?369    public let nonce: String370    public let createdAt, expiresAt: Int371372    public init(served: JSONValue?) throws {373        self = try ExecutionStrict.decode(MandateApprovalIntent.self, from: served, path: "binding.intent")374        guard v == 1, kind == "trading_mandate_approval", mode == "live" else { throw ApprovalError.unsupported("mandate approval intent version \(v) kind \(kind) mode \(mode)") }375    }376    public func canonicalBytes() throws -> Data { try ExecutionStableJSON.bytes(domain: Self.domain, try JSONValue.from(self)) }377}378
Files main
Menu

Theme