Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/Security/MandateLogic.swift10// Description : Pure logic of the trading-mandate screens: the creation11// draft in which EVERY limit starts empty and is typed by12// the owner (no default budget, cap, leverage, loss limit,13// market, frequency or expiry), what is still missing, the14// request built from it, and the words for the states,15// phases and enforcement levels the server reports.16// Module : Features17// Repository : https://git.spboucher.ai/sp-wallet-ios18// Created : 2026-11-1819// Last Modified : 2026-11-1820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation94import SPWalletCore9596struct TradingMandateDraft: Equatable {97 static let orderTypes = ["market", "limit", "stop", "take_profit"]98 static let marketKinds = ["perp", "spot"]99 /** `kind`, the member that carries its threshold, and whether it is a decimal (USD) or a whole number */100 static let stops: [(kind: String, decimal: Bool)] = [("loss_gte", true), ("drawdown_gte", false), ("consecutive_rejects_gte", false), ("data_stale_gte", false), ("signer_unreachable_gte", false)]101102 /** `api_key` or `agent`; nil until chosen */103 var principalKind: String?104 var principalId = ""105 /** nil until chosen: paper and live are never preselected */106 var mode: RiskMode?107 var accountId = ""108 var instruments: [String] = []109 var marketKinds: Set<String> = []110 var orderTypes: Set<String> = []111 var budgetCap = ""112 var perOrderCap = ""113 var positionCap = ""114 var maxLeverage = ""115 var dailyLossLimit = ""116 var floorEquity = ""117 var maxFee = ""118 var days = ""119 var perMinute = ""120 var perHour = ""121 var perDay = ""122 var slippageBps = ""123 var stops: [String: String] = [:]124 var strategySha256 = ""125 var label = ""126127 /** A derivative mandate lasts at most 30 days at the signer; a paper mandate 90 (the web client's bound). */128 static func maxDays(_ mode: RiskMode) -> Int { mode == .live ? 30 : 90 }129130 /** Names of what is missing or unreadable; empty when the request can be built. */131 func problems() -> [String] {132 var p: [String] = []133 if principalKind == nil || principalId.isEmpty { p.append("principal") }134 if mode == nil { p.append("mode") }135 if accountId.isEmpty { p.append("account") }136 if instruments.isEmpty { p.append("instruments") }137 if marketKinds.isEmpty { p.append("marketKinds") }138 if orderTypes.isEmpty { p.append("orderTypes") }139 for (v, k) in [(budgetCap, "maxCapitalUsd"), (perOrderCap, "maxOrderNotionalUsd"), (positionCap, "maxPositionNotionalUsd"), (maxLeverage, "maxLeverage"), (dailyLossLimit, "maxDailyLossUsd")] where RiskInput.positiveDecimal(v) == nil { p.append(k) }140 for (v, k) in [(floorEquity, "floorEquityUsd"), (maxFee, "maxFeeUsd")] where RiskInput.decimal(v) == nil { p.append(k) }141 if let d = RiskInput.integer(days), let m = mode { if d < 1 || d > Self.maxDays(m) { p.append("days") } } else if RiskInput.integer(days) == nil { p.append("days") }142 for (v, k) in [(perMinute, "frequency.perMinute"), (perHour, "frequency.perHour"), (perDay, "frequency.perDay")] { if (RiskInput.integer(v) ?? 0) < 1 { p.append(k) } }143 if (RiskInput.integer(slippageBps) ?? 0) < 1 { p.append("maxSlippageBps") }144 for s in Self.stops { let t = (stops[s.kind] ?? "").trimmingCharacters(in: .whitespaces); if !t.isEmpty, stop(s.kind, s.decimal, t) == nil { p.append("stop.\(s.kind)") } }145 if principalKind == "agent", strategySha256.range(of: "^[0-9a-f]{64}$", options: .regularExpression) == nil { p.append("strategySha256") }146 let l = label.trimmingCharacters(in: .whitespacesAndNewlines)147 if l.isEmpty || l.utf16.count > 60 { p.append("label") }148 return p149 }150151 private func stop(_ kind: String, _ decimal: Bool, _ text: String) -> TradingMandate.StopCondition? {152 if decimal { return RiskInput.positiveDecimal(text).map { TradingMandate.StopCondition(kind: kind, usd: $0) } }153 guard let n = RiskInput.integer(text), n >= 1 else { return nil }154 switch kind {155 case "drawdown_gte": return .init(kind: kind, bps: n)156 case "consecutive_rejects_gte": return .init(kind: kind, count: n)157 default: return .init(kind: kind, ms: n)158 }159 }160161 /** The creation request, exactly what was typed; nil while anything is missing. */162 func request(locale: String) -> MandateCreateRequest? {163 guard problems().isEmpty, let kind = principalKind, let mode,164 let budget = RiskInput.positiveDecimal(budgetCap), let order = RiskInput.positiveDecimal(perOrderCap), let position = RiskInput.positiveDecimal(positionCap),165 let lev = RiskInput.positiveDecimal(maxLeverage), let loss = RiskInput.positiveDecimal(dailyLossLimit), let floor = RiskInput.decimal(floorEquity), let fee = RiskInput.decimal(maxFee),166 let d = RiskInput.integer(days), let pm = RiskInput.integer(perMinute), let ph = RiskInput.integer(perHour), let pd = RiskInput.integer(perDay), let slip = RiskInput.integer(slippageBps) else { return nil }167 let conditions = Self.stops.compactMap { s -> TradingMandate.StopCondition? in168 let t = (stops[s.kind] ?? "").trimmingCharacters(in: .whitespaces)169 return t.isEmpty ? nil : stop(s.kind, s.decimal, t)170 }171 return MandateCreateRequest(principal: MandatePrincipal(kind: kind, id: principalId), mode: mode, accountIds: [accountId], venues: nil, allowedInstruments: instruments,172 marketKinds: Self.marketKinds.filter(marketKinds.contains), orderTypes: Self.orderTypes.filter(orderTypes.contains),173 budgetCapUsd: budget, perOrderCapUsd: order, positionCapUsd: position, maxLeverage: lev, dailyLossLimitUsd: loss, floorEquityUsd: floor, expiresInDays: d,174 frequency: .init(perMinute: pm, perHour: ph, perDay: pd), maxSlippageBps: slip, maxFeeUsd: fee, stopConditions: conditions,175 strategySha256: kind == "agent" ? strategySha256 : nil, label: label.trimmingCharacters(in: .whitespacesAndNewlines), locale: locale)176 }177}178179enum MandateWords {180 static func problem(_ p: String) -> String {181 switch p {182 case "principal": String(localized: "bénéficiaire")183 case "mode": String(localized: "mode")184 case "account": String(localized: "compte")185 case "instruments": String(localized: "marchés autorisés")186 case "marketKinds": String(localized: "types de marché")187 case "orderTypes": String(localized: "types d’ordre")188 case "maxCapitalUsd": String(localized: "budget")189 case "maxOrderNotionalUsd": String(localized: "plafond par ordre")190 case "maxPositionNotionalUsd": String(localized: "plafond de position")191 case "maxLeverage": String(localized: "levier maximal")192 case "maxDailyLossUsd": String(localized: "perte maximale par jour")193 case "floorEquityUsd": String(localized: "plancher de fonds propres")194 case "maxFeeUsd": String(localized: "frais maximal par ordre")195 case "days": String(localized: "durée")196 case "frequency.perMinute": String(localized: "ordres par minute")197 case "frequency.perHour": String(localized: "ordres par heure")198 case "frequency.perDay": String(localized: "ordres par jour")199 case "maxSlippageBps": String(localized: "glissement maximal")200 case "strategySha256": String(localized: "empreinte de la stratégie")201 case "label": String(localized: "nom du mandat")202 default: p.hasPrefix("stop.") ? String(localized: "condition d’arrêt \(String(p.dropFirst(5)))") : p203 }204 }205 static func kind(_ k: String?) -> String { k == "quoting" ? String(localized: "tenue de marché") : k == "directional" ? String(localized: "directionnel") : (k ?? String(localized: "type non précisé")) }206 static func state(_ s: String) -> String {207 switch s {208 case "created": String(localized: "créé, non approuvé")209 case "pending_signer": String(localized: "en attente du signataire")210 case "active": String(localized: "approuvé")211 case "revoked": String(localized: "révoqué")212 case "failed": String(localized: "échec de l’approbation")213 default: s214 }215 }216 static func phase(_ p: String) -> String {217 switch p {218 case "not_approved": String(localized: "sans effet")219 case "pending": String(localized: "pas encore en vigueur")220 case "active": String(localized: "en vigueur")221 case "wind_down": String(localized: "liquidation : ordres réducteurs seulement")222 case "ended": String(localized: "terminé")223 default: p224 }225 }226 /** Tone of a record: only the SERVER's « active / active » is shown as in force. */227 static func tone(_ m: TradingMandateRecord) -> Tone {228 if m.integrity?.ok == false { return .danger }229 if m.isActive { return .ok }230 switch m.state { case "revoked", "failed": return .neutral; case "created", "pending_signer": return .warn; default: return m.phase == "wind_down" ? .warn : .neutral }231 }232 static func enforcedBy(_ e: String) -> (text: String, tone: Tone, icon: String) {233 switch e {234 case "signer": (String(localized: "signataire isolé"), .ok, "lock.shield.fill")235 case "signer_partial": (String(localized: "signataire en partie, le reste par l’API"), .warn, "lock.trianglebadge.exclamationmark")236 case "api_only": (String(localized: "API seulement"), .danger, "exclamationmark.shield.fill")237 case "not_applicable": (String(localized: "sans objet"), .neutral, "minus.circle")238 default: (e, .neutral, "questionmark.circle")239 }240 }241 static func stopTitle(_ kind: String) -> String {242 switch kind {243 case "loss_gte": String(localized: "Perte atteinte (USD)")244 case "drawdown_gte": String(localized: "Repli atteint (pb)")245 case "consecutive_rejects_gte": String(localized: "Refus consécutifs (nombre)")246 case "data_stale_gte": String(localized: "Données périmées depuis (ms)")247 case "signer_unreachable_gte": String(localized: "Signataire injoignable depuis (ms)")248 default: kind249 }250 }251 static func orderType(_ t: String) -> String {252 switch t { case "market": String(localized: "au marché"); case "limit": String(localized: "à cours limité"); case "stop": String(localized: "stop"); case "take_profit": String(localized: "prise de profit"); default: t }253 }254255 /** Every field of a mandate as label + sentence, in the order of the schema. Nothing is left out; nothing is abbreviated. */256 static func fields(_ m: TradingMandate) -> [(key: String, label: String, value: String, mono: Bool)] {257 func account(_ a: TradingMandate.Account) -> String {258 if a.kind == "vault" { return "vault " + (a.vaultIndex.map { String($0) } ?? "?") + " · " + a.network + " · " + (a.address ?? "") }259 return (a.venue ?? "") + " · " + a.network + " · " + (a.account ?? "")260 }261 func condition(_ c: TradingMandate.StopCondition) -> String {262 let n: Int? = c.bps ?? c.count ?? c.ms263 return c.kind + " " + (c.usd ?? n.map { String($0) } ?? "")264 }265 let accounts: String = m.accounts.map(account).joined(separator: "\n")266 let stops: String = m.stopConditions.isEmpty ? String(localized: "aucune") : m.stopConditions.map(condition).joined(separator: "\n")267 typealias Row = (key: String, label: String, value: String, mono: Bool)268 var rows: [Row] = []269 func add(_ key: String, _ label: String, _ value: String, _ mono: Bool) { rows.append((key, label, value, mono)) }270 add("label", String(localized: "Nom"), m.label, false)271 add("mandateId", String(localized: "Identifiant du mandat"), m.mandateId, true)272 add("mode", String(localized: "Mode"), RiskWords.mode(m.mode) + " (\(m.mode))", false)273 add("principal", String(localized: "Bénéficiaire"), m.principal.label, true)274 add("accounts", String(localized: "Comptes"), accounts, true)275 add("venues", String(localized: "Plateformes"), m.venues.joined(separator: ", "), false)276 add("networks", String(localized: "Réseaux"), m.networks.joined(separator: ", "), false)277 add("instruments", String(localized: "Marchés autorisés"), m.instruments.joined(separator: ", "), true)278 add("marketKinds", String(localized: "Types de marché"), m.marketKinds.joined(separator: ", "), false)279 add("orderTypes", String(localized: "Types d’ordre"), m.orderTypes.joined(separator: ", "), false)280 add("maxCapitalUsd", String(localized: "Budget (capital à risque)"), Fmt.usd(m.maxCapitalUsd), false)281 add("maxOrderNotionalUsd", String(localized: "Plafond par ordre"), Fmt.usd(m.maxOrderNotionalUsd), false)282 add("maxPositionNotionalUsd", String(localized: "Plafond de position, par marché"), Fmt.usd(m.maxPositionNotionalUsd), false)283 add("maxLeverage", String(localized: "Levier maximal"), Money.exact(m.maxLeverage) + " ×", false)284 add("maxDailyLossUsd", String(localized: "Perte maximale par jour"), Fmt.usd(m.maxDailyLossUsd), false)285 add("floorEquityUsd", String(localized: "Plancher de fonds propres (perte totale)"), Fmt.usd(m.floorEquityUsd), false)286 add("frequency", String(localized: "Cadence maximale"), String(localized: "\(m.frequency.perMinute) / min · \(m.frequency.perHour) / h · \(m.frequency.perDay) / 24 h"), false)287 add("maxSlippageBps", String(localized: "Glissement maximal"), "\(m.maxSlippageBps) pb", false)288 add("maxFeeUsd", String(localized: "Frais maximal par ordre"), Fmt.usd(m.maxFeeUsd), false)289 add("stopConditions", String(localized: "Conditions d’arrêt"), stops, true)290 add("createdAt", String(localized: "Créé le"), RiskWords.date(seconds: m.createdAt) ?? "", false)291 add("notBefore", String(localized: "Valide à partir du"), RiskWords.date(seconds: m.notBefore) ?? "", false)292 add("notAfter", String(localized: "Expire le"), RiskWords.date(seconds: m.notAfter) ?? "", false)293 add("strategySha256", String(localized: "Empreinte de la stratégie / du bénéficiaire"), m.strategySha256.value ?? String(localized: "aucune"), true)294 add("v", String(localized: "Version du format"), String(m.v), false)295 return rows296 }297}298