SPB Git

Repository Public

Models.swift 13.5 KB 344 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Wallet/Models.swift3// Description: Models of the wallet's base API (services/api/src/server.ts, transfers.ts): networks, accounts, portfolio, prices,4//              proposals and their states, activity, address book, settings, security overview. Amounts are base-unit strings5//              plus the server's exact decimal text; nothing here converts an amount through floating point.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011public struct AssetDef: Codable, Sendable, Hashable, Identifiable {12    /** `native` or the token contract / mint address. */13    public let id: String14    public let symbol: String15    public let name: String16    public let decimals: Int17    public let program: String?18    public let onchainSymbol: String?19    public var isNative: Bool { id == "native" }20}2122public struct NetworkHealth: Codable, Sendable, Hashable {23    public let network: String?24    public let ok: Bool?25    /** The chain can be read (balances, history). */26    public let readable: Bool?27    /** The node answered with this network's pinned identity (chain id / genesis). */28    public let identityVerified: Bool?29    public let height: JSONValue?30    public let endpoints: JSONValue?31    public let checkedAt: Date?32}3334public struct Network: Codable, Sendable, Hashable, Identifiable {35    public let id: String36    public let name: String37    /** `evm`, `btc` (every Bitcoin-style chain), `sol`, or the name of a plugin family (tron, xrpl, stellar, cosmos, sui, aptos, near, ton, cardano, polkadot…). */38    public let family: String39    public let chainRef: String40    public let native: AssetDef41    public let tokens: [AssetDef]42    /** `text` or `uint32` when transfers on this network carry a destination memo / tag. */43    public let memo: String?44    /** Minimum the account must hold to exist on-chain, in whole units of the native coin. */45    public let activation: String?46    public let explorerAddr: String47    public let minConf: Int48    public let health: NetworkHealth?4950    public var assets: [AssetDef] { [native] + tokens }51    public func asset(_ id: String) -> AssetDef? { id == "native" ? native : tokens.first { $0.id == id } }52}5354public struct Account: Codable, Sendable, Hashable, Identifiable {55    public let network: String56    public let name: String57    public let family: String58    public let address: String59    public let explorer: String60    public var id: String { network }61}6263public struct Accounts: Codable, Sendable, Hashable {64    public let keyId: String65    /** False when the signer node could not be reached: the addresses are the last ones it gave. */66    public let signerReachable: Bool67    public let addressesAsOf: Date?68    public let accounts: [Account]69}7071/** One price with its provenance. `stale` and `divergent` must be shown; a price is an observation of a source, not a fact. */72public struct MarketPrice: Codable, Sendable, Hashable {73    public let priceAt: Date?74    public let stale: Bool75    public let usd: Double76    public let cad: Double77    public let change24h: Double?78    public let change7d: Double?79    public let marketCap: Double?80    public let volume24h: Double?81    public let high24h: Double?82    public let low24h: Double?83    public let ath: Double?84    public let rank: Int?85    public let spark: [Double]86    /** `coingecko`, `apibricks` (labelled fallback)… */87    public let source: String?88    public let fallback: Bool?89    public let divergent: Bool?9091    public func value(in currency: FiatCurrency) -> Double { currency == .usd ? usd : cad }92}9394public enum FiatCurrency: String, Codable, Sendable, CaseIterable { case usd = "USD", cad = "CAD" }9596public struct Balance: Codable, Sendable, Hashable, Identifiable {97    public let network: String98    public let networkName: String99    public let asset: String100    public let symbol: String101    public let name: String102    public let decimals: Int103    /** Base units; nil when the chain read failed (`error` says so). Never shown as zero in that case. */104    public let amount: String?105    public let display: String?106    public let error: String?107    public var id: String { "\(network):\(asset)" }108    public var units: BaseUnits? { amount.flatMap { try? BaseUnits($0) } }109    public var isAvailable: Bool { amount != nil }110    public var isNonZero: Bool { units.map { !$0.isZero } ?? false }111}112113public struct Portfolio: Codable, Sendable, Hashable {114    public struct SignerState: Codable, Sendable, Hashable { public let reachable: Bool; public let addressesAsOf: Date? }115    public let asOf: Date116    public let prices: [String: MarketPrice]?117    public let priceSource: String?118    public let pricesAsOf: Date?119    public let pricesStale: Bool120    public let balances: [Balance]121    public let pending: [Proposal]122    /** nil when the signer cannot be reached (its halt state is unknown). */123    public let halted: Bool?124    public let signer: SignerState?125126    /** Estimated fiat value of one balance: amount × the displayed price. An estimate, labelled as such by the screens. */127    public func estimatedValue(of b: Balance, in currency: FiatCurrency) -> Double? {128        guard let u = b.units, let p = prices?[b.symbol] else { return nil }129        return u.approximate(decimals: b.decimals) * p.value(in: currency)130    }131    /** Sum of the estimates; `complete` is false when a balance could not be read or has no price. */132    public func estimatedTotal(in currency: FiatCurrency) -> (value: Double, complete: Bool) {133        var total = 0.0, complete = true134        for b in balances {135            guard let u = b.units else { complete = false; continue }136            if u.isZero { continue }137            guard let v = estimatedValue(of: b, in: currency) else { complete = false; continue }138            total += v139        }140        return (total, complete)141    }142}143144public enum ProposalState: String, Codable, Sendable, CaseIterable {145    case draft, pendingApproval = "pending_approval", approved, signed, broadcast, confirming, finalized146    case rejected, expired, failed, replaced, reorged, notBroadcast = "not_broadcast"147    /** A state added by a newer server: shown verbatim, never mapped to a known one. */148    case unknown149150    public init(from decoder: Decoder) throws { self = ProposalState(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .unknown }151    public var isTerminal: Bool { [.finalized, .rejected, .expired, .failed, .replaced, .notBroadcast].contains(self) }152    public var isInFlight: Bool { [.approved, .signed, .broadcast, .confirming, .reorged].contains(self) }153    /** Only `finalized` is a success. `broadcast` and `confirming` are not. */154    public var isSuccess: Bool { self == .finalized }155    public var isFailure: Bool { [.rejected, .expired, .failed, .replaced].contains(self) }156}157158/** The owner-facing view of a proposal (`view()` in transfers.ts). Kind-specific sections are kept as JSON for their own modules. */159public struct Proposal: Codable, Sendable, Hashable, Identifiable {160    public let id: String161    public let state: ProposalState162    public let network: String163    public let networkName: String?164    public let asset: String165    public let symbol: String166    public let decimals: Int167    public let amount: String168    public let amountDisplay: String169    public let from: String?170    public let to: String?171    public let note: String?172    public let memo: String?173    public let feeEstimate: String?174    public let maxFee: String?175    public let feeSymbol: String?176    public let feeDecimals: Int?177    public let feeDisplay: String?178    public let maxFeeDisplay: String?179    public let warnings: [String]?180    public let intentHash: String?181    public let txid: String?182    public let explorer: String?183    public let confirmations: Int?184    public let error: String?185    public let errorCode: String?186    public let errorParams: [String: JSONValue]?187    public let createdAt: Date?188    public let updatedAt: Date?189    public let expiresAt: Date?190    public let broadcastAt: Date?191    public let finalizedAt: Date?192    /** `transfer`, `swap`, `bridge`, `xswap`, `gmx`, `nft`. */193    public let kind: String?194    public let swap: JSONValue?195    public let bridge: JSONValue?196    public let xswap: JSONValue?197    public let execution: JSONValue?198    public let nft: JSONValue?199    public let quote: JSONValue?200}201202public struct ProposalStatus: Codable, Sendable, Hashable {203    public let id: String204    public let state: ProposalState205    public let txid: String?206    public let confirmations: Int?207    public let error: String?208    public let errorCode: String?209    public let errorParams: [String: JSONValue]?210    public let explorer: String?211    public let kind: String?212    public let execution: JSONValue?213}214215/** One row of the activity feed: an outgoing proposal (send, swap, bridge, gmx) or an observed deposit (`receive`). */216public struct ActivityItem: Codable, Sendable, Hashable, Identifiable {217    public let id: String218    /** `send`, `swap`, `bridge`, `gmx`, `receive`. */219    public let kind: String220    public let rawKind: String?221    public let at: Date222    public let network: String223    public let networkName: String?224    public let asset: String?225    public let symbol: String226    public let decimals: Int?227    public let amount: String228    public let amountDisplay: String?229    public let from: String?230    public let to: String?231    public let note: String?232    public let memo: String?233    public let txid: String?234    public let explorer: String?235    /** A proposal state, or `confirming` / `finalized` for a deposit. Kept as text: the two vocabularies overlap. */236    public let state: String237    public let confirmations: Int?238    public let feeDisplay: String?239    public let feeSymbol: String?240    public let error: String?241    public let errorCode: String?242    public let swap: JSONValue?243    public let bridge: JSONValue?244    public let xswap: JSONValue?245    public let execution: JSONValue?246    public let nft: JSONValue?247248    public var isIncoming: Bool { kind == "receive" }249    public var proposalState: ProposalState? { isIncoming ? nil : ProposalState(rawValue: state) }250    /** True only when the chain finalized it. */251    public var isSettled: Bool { state == "finalized" }252}253public struct ActivityFeed: Codable, Sendable, Hashable { public let items: [ActivityItem] }254255public struct MarketChart: Codable, Sendable, Hashable {256    public struct Point: Codable, Sendable, Hashable { public let t: Double; public let p: Double; public var date: Date { Date(timeIntervalSince1970: t / 1000) } }257    public let symbol: String258    public let currency: String?259    public let days: String?260    public let points: [Point]261    public let market: MarketPrice?262}263264public struct AddressBookEntry: Codable, Sendable, Hashable, Identifiable {265    public let id: String266    public let network: String267    public let address: String268    public let label: String269    public let createdAt: Date?270    enum CodingKeys: String, CodingKey { case id, network, address, label, createdAt = "created_at" }271}272273public struct WalletSettings: Codable, Sendable, Hashable {274    public var locale: String275    public var currency: FiatCurrency276    public var hideBalances: Bool277    public var prices: Bool278}279280public struct SecurityOverview: Codable, Sendable, Hashable {281    public struct Signer: Codable, Sendable, Hashable {282        public let reachable: Bool283        public let keyId: String?284        public let halted: Bool?285        public let journalLength: Int?286        public let journalHead: String?287        /** The limits in force on the signer machine (per-transfer, per-day, fee ceilings…), as it reports them. */288        public let policy: JSONValue?289        public let spentToday: [String: String]?290    }291    public struct Device: Codable, Sendable, Hashable, Identifiable {292        public let id: String293        public let label: String294        public let deviceType: String?295        public let backedUp: Bool?296        public let createdAt: Date?297        public let lastUsedAt: Date?298        public let enrolledOnSigner: Bool?299    }300    public struct Session: Codable, Sendable, Hashable {301        public let createdAt: Date?302        public let lastSeen: Date?303        public let ua: String?304        public let ip: String?305        enum CodingKeys: String, CodingKey { case createdAt = "created_at", lastSeen = "last_seen", ua, ip }306    }307    public let signer: Signer308    public let devices: [Device]309    public let sessions: [Session]310    public let origin: String?311    /** False when this server signs but deliberately does not relay transactions (test stacks). */312    public let broadcast: Bool?313}314315/** One record of the server's hash-chained audit journal. */316public struct AuditEntry: Codable, Sendable, Hashable, Identifiable {317    public let seq: Int318    public let ts: Date319    /** `login.ok`, `transfer.draft`, `transfer.finalized`, `halt.on`, `device.added`… */320    public let type: String321    public let actor: String322    public let data: JSONValue?323    public let prev: String?324    public let hash: String?325    public var id: Int { seq }326}327328public struct AuditJournal: Codable, Sendable, Hashable {329    /** Most recent first. */330    public let events: [AuditEntry]331    /** False when the server's own verification of the hash chain failed: shown prominently. */332    public let intact: Bool333    public let brokenAt: Int?334    public let total: Int335}336337public struct HealthReady: Codable, Sendable, Hashable {338    public struct SignerHealth: Codable, Sendable, Hashable { public let ok: Bool; public let halted: Bool? }339    public let db: Bool340    public let signer: SignerHealth341    public let networks: [NetworkHealth]342    public let rpcEndpoints: JSONValue?343}344
Files main
Menu

Theme