Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Execution/RiskCanonical.swift3// Description: The owner's limits of the unified risk engine (packages/trading/src/risk/engine.ts `RiskLimitsSchema`) and the three4// intents the risk service has approved by passkey (services/api/src/risk/service.ts): loosening the limits5// (`SPW-RISK-LIMITS-INTENT-v1`), releasing the kill switch or read-only mode (`SPW-RISK-SWITCH-INTENT-v1`), switching6// an automatic stop off (`SPW-RISK-AUTO-INTENT-v1`). Each challenge is SHA-256 of `<domain>\n<stable JSON of the intent>`7// (risk/passkey.ts `prepareIntent` → derivatives/exec.ts `canonicalIntentHash`): object-bound, never server-random.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213public enum RiskMode: String, Codable, Sendable, CaseIterable { case paper, live }1415/**16 The limit set the owner stores for one mode. EVERY member is optional on purpose: an absent member is a missing limit, and in17 live mode a missing limit on capital DENIES new risk. Money and ratios are exact decimal strings; counts and ages are integers.18 A change replaces the whole set: what is not in the value sent is removed.19 */20public struct EngineRiskLimits: Codable, Sendable, Equatable {21 /** by instrument / asset / venue id, with an optional default */22 public struct Keyed: Codable, Sendable, Equatable {23 public var per: [String: String]24 public var fallback: String?25 public init(per: [String: String] = [:], fallback: String? = nil) { self.per = per; self.fallback = fallback }26 enum CodingKeys: String, CodingKey { case per, fallback = "default" }27 }28 /** oldest acceptable price per source, in milliseconds */29 public struct KeyedAge: Codable, Sendable, Equatable {30 public var per: [String: Int]31 public var fallback: Int?32 public init(per: [String: Int] = [:], fallback: Int? = nil) { self.per = per; self.fallback = fallback }33 enum CodingKeys: String, CodingKey { case per, fallback = "default" }34 }35 /** book depth within `withinBps` of the mid must be at least `multiple` × the order's size */36 public struct MinLiquidity: Codable, Sendable, Equatable {37 public var withinBps: String38 public var multiple: String39 public init(withinBps: String, multiple: String) { self.withinBps = withinBps; self.multiple = multiple }40 }4142 public var allowedVenues: [String]?43 public var allowedInstruments: [String]?44 public var maxPositionNotional: Keyed?45 public var maxOrderLeverage: String?46 public var maxAccountLeverage: String?47 public var maxDailyLoss: String?48 public var maxTotalLoss: String?49 public var maxDrawdownBps: String?50 public var maxGrossExposure: String?51 public var maxNetExposure: String?52 public var maxAssetExposure: Keyed?53 public var maxVenueExposure: Keyed?54 public var maxVenueCollateralShareBps: String?55 public var minLiquidationDistanceBps: String?56 public var maxSlippageBps: String?57 public var maxPriceAgeMs: KeyedAge?58 public var maxBookAgeMs: Int?59 public var minPriceSources: Int?60 public var maxSourceDeviationBps: String?61 public var maxOrdersPerMinute: Int?62 public var maxOrdersPerHour: Int?63 public var maxOrdersPerDay: Int?64 public var maxOrderNotional: String?65 public var maxDailyNotional: String?66 public var minLiquidity: MinLiquidity?6768 public init() {}6970 /** The names of `RiskLimitsSchema`, in its order. */71 public static let fieldNames = ["allowedVenues", "allowedInstruments", "maxPositionNotional", "maxOrderLeverage", "maxAccountLeverage", "maxDailyLoss", "maxTotalLoss", "maxDrawdownBps",72 "maxGrossExposure", "maxNetExposure", "maxAssetExposure", "maxVenueExposure", "maxVenueCollateralShareBps", "minLiquidationDistanceBps", "maxSlippageBps",73 "maxPriceAgeMs", "maxBookAgeMs", "minPriceSources", "maxSourceDeviationBps", "maxOrdersPerMinute", "maxOrdersPerHour", "maxOrdersPerDay", "maxOrderNotional",74 "maxDailyNotional", "minLiquidity"]7576 /** The value constraints of `RiskLimitsSchema` (non-negative decimals, positive where the schema says so, counts ≥ 0, at least one price source). */77 public func validate() throws {78 func nonNeg(_ v: String?, _ k: String) throws { if let v, !ExecutionDecimal.isNonNegative(v) { throw ApprovalError.unsupported("limits.\(k) is not a non-negative decimal") } }79 func pos(_ v: String?, _ k: String) throws { if let v, !ExecutionDecimal.isPositive(v) { throw ApprovalError.unsupported("limits.\(k) is not a positive decimal") } }80 func count(_ v: Int?, _ k: String) throws { if let v, v < 0 || Int64(v) > ExecutionStableJSON.maxSafeInteger { throw ApprovalError.unsupported("limits.\(k) is not a count") } }81 func keyed(_ v: Keyed?, _ k: String) throws { if let v { for (kk, x) in v.per { try nonNeg(x, "\(k).per.\(kk)") }; try nonNeg(v.fallback, "\(k).default") } }82 for (list, k) in [(allowedVenues, "allowedVenues"), (allowedInstruments, "allowedInstruments")] { if let list, list.contains(where: \.isEmpty) { throw ApprovalError.unsupported("limits.\(k) has an empty entry") } }83 try keyed(maxPositionNotional, "maxPositionNotional"); try keyed(maxAssetExposure, "maxAssetExposure"); try keyed(maxVenueExposure, "maxVenueExposure")84 try pos(maxOrderLeverage, "maxOrderLeverage"); try pos(maxAccountLeverage, "maxAccountLeverage")85 for (v, k) in [(maxDailyLoss, "maxDailyLoss"), (maxTotalLoss, "maxTotalLoss"), (maxDrawdownBps, "maxDrawdownBps"), (maxGrossExposure, "maxGrossExposure"), (maxNetExposure, "maxNetExposure"),86 (maxVenueCollateralShareBps, "maxVenueCollateralShareBps"), (minLiquidationDistanceBps, "minLiquidationDistanceBps"), (maxSlippageBps, "maxSlippageBps"),87 (maxSourceDeviationBps, "maxSourceDeviationBps"), (maxOrderNotional, "maxOrderNotional"), (maxDailyNotional, "maxDailyNotional")] { try nonNeg(v, k) }88 if let a = maxPriceAgeMs { for (kk, x) in a.per { try count(x, "maxPriceAgeMs.per.\(kk)") }; try count(a.fallback, "maxPriceAgeMs.default") }89 for (v, k) in [(maxBookAgeMs, "maxBookAgeMs"), (maxOrdersPerMinute, "maxOrdersPerMinute"), (maxOrdersPerHour, "maxOrdersPerHour"), (maxOrdersPerDay, "maxOrdersPerDay")] { try count(v, k) }90 if let n = minPriceSources, n < 1 { throw ApprovalError.unsupported("limits.minPriceSources is below 1") }91 if let l = minLiquidity { try nonNeg(l.withinBps, "minLiquidity.withinBps"); try pos(l.multiple, "minLiquidity.multiple") }92 }93}9495public enum RiskSwitchKind: String, Codable, Sendable, CaseIterable {96 case killSwitch = "kill_switch", readOnly = "read_only"97 /** the path segment of its routes */98 var route: String { self == .killSwitch ? "kill-switch" : "read-only" }99}100101/** `SPW-RISK-LIMITS-INTENT-v1`: the WHOLE new limit set of one mode, and the fields the server found loosened. */102public struct RiskLimitsIntent: Codable, Sendable, Equatable, ExecutionStampedIntent {103 public static let domain = "SPW-RISK-LIMITS-INTENT-v1"104 public let v: Int105 public let kind: String106 public let mode: RiskMode107 public let limits: EngineRiskLimits108 public let loosened: [String]109 public let nonce: String110 public let createdAt, expiresAt: Int111112 public init(served: JSONValue?) throws {113 self = try ExecutionStrict.decode(RiskLimitsIntent.self, from: served, path: "intent")114 guard v == 1, kind == "limits" else { throw ApprovalError.unsupported("limits intent version \(v) kind \(kind)") }115 try limits.validate()116 }117 public func canonicalBytes() throws -> Data { try ExecutionStableJSON.bytes(domain: Self.domain, try JSONValue.from(self)) }118}119120/** `SPW-RISK-SWITCH-INTENT-v1`: the release of ONE switch, naming the very engagement being released (when, by whom, why). */121public struct RiskSwitchReleaseIntent: Codable, Sendable, Equatable, ExecutionStampedIntent {122 public static let domain = "SPW-RISK-SWITCH-INTENT-v1"123 public let v: Int124 public let kind: RiskSwitchKind125 /** unix ms of the engagement; the server serves `null` when the stored switch has none */126 public let engagedAt: Int?127 /** `<actor kind>:<actor id>`, e.g. `owner:owner`, `api_key:spk_…`, `system:supervisor` */128 public let engagedBy: String?129 public let reason: String?130 public let nonce: String131 public let createdAt, expiresAt: Int132133 public init(served: JSONValue?) throws {134 self = try ExecutionStrict.decode(RiskSwitchReleaseIntent.self, from: served, path: "intent")135 guard v == 1 else { throw ApprovalError.unsupported("switch intent version \(v)") }136 }137 // the three nullable members are ALWAYS present in the served object (as a value or as null): written back the same way138 public func encode(to encoder: Encoder) throws {139 var c = encoder.container(keyedBy: CodingKeys.self)140 try c.encode(v, forKey: .v); try c.encode(kind, forKey: .kind); try c.encode(engagedAt, forKey: .engagedAt); try c.encode(engagedBy, forKey: .engagedBy); try c.encode(reason, forKey: .reason)141 try c.encode(nonce, forKey: .nonce); try c.encode(createdAt, forKey: .createdAt); try c.encode(expiresAt, forKey: .expiresAt)142 }143 public func canonicalBytes() throws -> Data { try ExecutionStableJSON.bytes(domain: Self.domain, try JSONValue.from(self)) }144}145146/** The automatic stops of the live book: which measured conditions engage the kill switch by themselves. Switching one OFF is a loosening. */147public struct AutoKillSettings: Codable, Sendable, Equatable {148 public var totalLoss: Bool149 public var drawdown: Bool150 public var dailyLoss: Bool151 public init(totalLoss: Bool, drawdown: Bool, dailyLoss: Bool) { self.totalLoss = totalLoss; self.drawdown = drawdown; self.dailyLoss = dailyLoss }152}153154/** `SPW-RISK-AUTO-INTENT-v1`: the new automatic stops, and which of them the change switches off. */155public struct AutoKillIntent: Codable, Sendable, Equatable, ExecutionStampedIntent {156 public static let domain = "SPW-RISK-AUTO-INTENT-v1"157 public let v: Int158 public let kind: String159 public let auto: AutoKillSettings160 public let loosened: [String]161 public let nonce: String162 public let createdAt, expiresAt: Int163164 public init(served: JSONValue?) throws {165 self = try ExecutionStrict.decode(AutoKillIntent.self, from: served, path: "intent")166 guard v == 1, kind == "auto" else { throw ApprovalError.unsupported("auto intent version \(v) kind \(kind)") }167 }168 public func canonicalBytes() throws -> Data { try ExecutionStableJSON.bytes(domain: Self.domain, try JSONValue.from(self)) }169}170