PlatformWalletManager {
return Err(err);
}
+ // Past the rollback point. Accounting is display-only, so a failure
+ // here is logged and never fails the load.
+ for (wallet_id, _) in &inserted_in_wallets {
+ self.backfill_history_accounting(*wallet_id).await;
+ }
+
// Past the rollback point: every registration here is one this load
// actually committed, so the transactions now have a wallet to belong
// to for as long as it stays registered.
@@ -735,6 +743,53 @@ impl PlatformWalletManager {
Ok(())
}
+
+ /// Hand the persister the per-wallet accounting of every stored
+ /// transaction it flags as lacking one (see
+ /// [`PlatformWalletPersistence::load_core_history_for_accounting`]).
+ async fn backfill_history_accounting(&self, wallet_id: WalletId) {
+ let persister = Arc::clone(&self.persister);
+ let history =
+ match run_blocking_load(move || persister.load_core_history_for_accounting(wallet_id))
+ .await
+ {
+ Ok(history) => history,
+ Err(e) => {
+ tracing::warn!(
+ wallet_id = %hex::encode(wallet_id),
+ error = ?e,
+ "load: reading stored history for the accounting backfill failed"
+ );
+ return;
+ }
+ };
+ if !history.iter().any(|stored| stored.needs_accounting) {
+ return;
+ }
+ let rows = {
+ let wm = self.wallet_manager.read().await;
+ let Some(info) = wm.get_wallet_info(&wallet_id) else {
+ return;
+ };
+ history_accounting(&info.core_wallet, &history)
+ };
+ if rows.is_empty() {
+ return;
+ }
+ let persister = Arc::clone(&self.persister);
+ let count = rows.len();
+ if let Err(e) =
+ run_blocking_load(move || persister.store_transaction_accounting(wallet_id, &rows))
+ .await
+ {
+ tracing::warn!(
+ wallet_id = %hex::encode(wallet_id),
+ rows = count,
+ error = ?e,
+ "load: persisting backfilled transaction accounting failed"
+ );
+ }
+ }
}
/// What one re-dispatch attempt did, so a caller — and a test — can tell the
@@ -1312,6 +1367,113 @@ mod idempotent_load_tests {
);
}
+ /// Hands back a stored history for the accounting backfill and records
+ /// what the manager persists from it.
+ struct HistoryPersister {
+ wallet: Wallet,
+ managed: ManagedWalletInfo,
+ history: Vec,
+ stored: std::sync::Mutex)>>,
+ }
+
+ impl PlatformWalletPersistence for HistoryPersister {
+ fn store(
+ &self,
+ _wallet_id: WalletId,
+ _changeset: PlatformWalletChangeSet,
+ ) -> Result<(), PersistenceError> {
+ Ok(())
+ }
+
+ fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> {
+ Ok(())
+ }
+
+ fn load(&self) -> Result {
+ SingleWalletPersister {
+ wallet: self.wallet.clone(),
+ managed: self.managed.clone(),
+ }
+ .load()
+ }
+
+ fn load_core_history_for_accounting(
+ &self,
+ _wallet_id: WalletId,
+ ) -> Result, PersistenceError> {
+ Ok(self.history.clone())
+ }
+
+ fn store_transaction_accounting(
+ &self,
+ wallet_id: WalletId,
+ rows: &[crate::changeset::WalletAccounting],
+ ) -> Result<(), PersistenceError> {
+ self.stored.lock().unwrap().push((wallet_id, rows.to_vec()));
+ Ok(())
+ }
+ }
+
+ async fn load_with_history(
+ flagged: bool,
+ ) -> (
+ WalletId,
+ dashcore::Transaction,
+ Vec<(WalletId, Vec)>,
+ ) {
+ let (ctx, funding) = TestWalletContext::new_random()
+ .with_mempool_funding(100_000)
+ .await;
+ let wallet_id = ctx.wallet.compute_wallet_id();
+ let persister = Arc::new(HistoryPersister {
+ wallet: ctx.wallet,
+ managed: ctx.managed_wallet,
+ history: vec![crate::changeset::StoredCoreTransaction {
+ transaction: funding.clone(),
+ needs_accounting: flagged,
+ }],
+ stored: std::sync::Mutex::new(Vec::new()),
+ });
+ let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk"));
+ let event_handler: Arc = Arc::new(NoopTestEventHandler);
+ let manager = PlatformWalletManager::new(sdk, Arc::clone(&persister), event_handler);
+ manager
+ .load_from_persistor()
+ .await
+ .expect("the wallet must load");
+ let stored = persister.stored.lock().unwrap().clone();
+ (wallet_id, funding, stored)
+ }
+
+ /// Rows the host stored before it kept per-wallet accounting are
+ /// backfilled at load from the restored wallet's own view of its scripts.
+ #[tokio::test]
+ async fn load_backfills_accounting_for_stored_history_the_host_flags() {
+ let (wallet_id, funding, stored) = load_with_history(true).await;
+
+ assert_eq!(stored.len(), 1, "one backfill write for the wallet");
+ let (written_for, rows) = &stored[0];
+ assert_eq!(written_for, &wallet_id);
+ assert_eq!(
+ rows.as_slice(),
+ &[crate::changeset::WalletAccounting {
+ txid: funding.txid(),
+ net_amount: 100_000,
+ direction:
+ key_wallet::managed_account::transaction_record::TransactionDirection::Incoming,
+ fee: None,
+ }]
+ );
+ }
+
+ /// A host whose history is all accounted writes nothing.
+ #[tokio::test]
+ async fn load_skips_the_backfill_when_nothing_is_flagged() {
+ let (_, _, stored) = load_with_history(false).await;
+
+ assert!(stored.is_empty());
+ }
+
fn make_pending_manager(
persister: PendingSendPersister,
) -> Arc> {
From c081e8711333c6e570523c838f62f13e9d5f8783 Mon Sep 17 00:00:00 2001
From: Lukasz Klimek <842586+lklimek@users.noreply.github.com>
Date: Wed, 28 Oct 2026 16:45:33 +0000
Subject: [PATCH 08/21] feat(swift-sdk): persist Rust-emitted per-wallet
transaction accounting
SwiftData now stores the accounting rs-platform-wallet emits, one
`PersistentTransactionAccounting` row per (walletId, txid), and shows it.
It no longer recomputes or overwrites it.
- Live schema V5 (unreleased) carries the new entity in place of the
`netAmountUnavailable` marker; V4 -> V5 stays a lightweight migration.
- The handler wires the three new extension slots: rows from each round
stage with it, and the load-time backfill commits on its own. History is
offered to Rust only when some transaction lacks this wallet's row.
- `netAmount(for:)`, `direction(for:)` and `fee(for:)` are lookups that fall
back to the shared last-writer scalars when Rust has emitted no row.
- `upsertTransaction` writes the record's shared values as delivered. The
asset-lock "recovery record" veto is gone; Rust now says "no accounting"
by sending no row.
- The load, round-end and TXO-heal reconcile passes and `accountingDirty` are
removed. Deleting a wallet deletes its accounting rows.
- `CoreDirectionCode` binds the exported `PLATFORM_WALLET_TRANSACTION_DIRECTION_*`
constants instead of re-declaring the values.
- Example app: the account-detail transaction rows and sheet are now scoped
to their wallet, and fees come from the wallet's row.
Not built here: no Swift toolchain on this host.
Co-Authored-By: Claude Opus 5.5
---
packages/swift-sdk/SCHEMA_RELEASES.md | 13 +-
.../Persistence/DashModelContainer.swift | 3 +-
.../Models/PersistentTransaction.swift | 165 ++-------
.../PersistentTransactionAccounting.swift | 48 +++
.../PlatformWallet/CoreDirectionCode.swift | 11 +
.../PlatformWalletPersistenceHandler.swift | 346 +++++++++---------
.../Core/Views/AccountDetailView.swift | 4 +-
.../Core/Views/TransactionDetailView.swift | 9 +-
.../Core/Views/TransactionListView.swift | 7 +-
packages/swift-sdk/schema-models.json | 3 +-
10 files changed, 293 insertions(+), 316 deletions(-)
create mode 100644 packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTransactionAccounting.swift
create mode 100644 packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/CoreDirectionCode.swift
diff --git a/packages/swift-sdk/SCHEMA_RELEASES.md b/packages/swift-sdk/SCHEMA_RELEASES.md
index 0714ae16766..ee711319892 100644
--- a/packages/swift-sdk/SCHEMA_RELEASES.md
+++ b/packages/swift-sdk/SCHEMA_RELEASES.md
@@ -24,12 +24,13 @@ schema. The former live V2 is accepted only when its complete graph matches
frozen V3 exactly, entity hashes and checksum alike. The alias remains supported
when the live graph changes; other stores labelled `2.0.0` fail closed.
-V5 adds the optional `PersistentTransaction.netAmountUnavailable` marker through
-a lightweight migration. Existing rows receive `nil`, preserving their stored
-accounting. When deleting one participant of a shared transaction, the remaining
-wallet's amount and direction are saved before the ownership links disappear.
-If its amount was unresolved, the marker keeps it unavailable across restart;
-an authoritative wallet record or complete accounting reconciliation clears it.
+V5 adds the `PersistentTransactionAccounting` entity through a lightweight
+migration: one row per `(walletId, txid)` holding the net amount, direction and
+fee `rs-platform-wallet` emitted for that wallet. Migrated stores start with no
+rows; at the first load Rust reads the stored history back
+(`on_load_core_history_for_accounting_fn`), computes the accounting of every
+transaction lacking a row and hands it to `on_persist_transaction_accounting_fn`.
+Deleting a wallet deletes its rows; deleting a transaction cascades to them.
The route decision is logged as `store_migration_route` with the validated
`source_version`, `source_checksum` and one of `new-store`,
diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift
index c45fadd05b8..d21ed19427f 100644
--- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift
+++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift
@@ -94,7 +94,8 @@ public enum DashModelContainer {
PersistentInvitation.self,
PersistentMasternode.self,
PersistentTrackedMasternode.self,
- PersistentIdentityBalanceMetadata.self
+ PersistentIdentityBalanceMetadata.self,
+ PersistentTransactionAccounting.self
]
}
diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTransaction.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTransaction.swift
index cc84271d68f..bfd3811ba9c 100644
--- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTransaction.swift
+++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTransaction.swift
@@ -84,12 +84,12 @@ public final class PersistentTransaction {
/// replaces it with the real discriminant on touch. Accessors
/// treat the sentinel as unknown (no branch fires).
public var transactionTypeKind: UInt8 = 0xFF
- /// Net Core amount in duffs across locally owned TXOs (positive=received, negative=sent).
+ /// Net amount in duffs (signed: positive=received, negative=sent) as the
+ /// last recording wallet's `TransactionRecordFFI` carried it. Shared by
+ /// every wallet in the transaction; per-wallet values live in
+ /// [`walletAccounting`]; `netAmount(for:)` prefers the wallet's row.
public var netAmount: Int64
- /// Set when removing a wallet left no authoritative amount for the survivor.
- /// `nil` preserves the accounting of rows migrated from V3.
- public var netAmountUnavailable: Bool? = nil
- /// Fee in duffs (nil if unknown).
+ /// Fee in duffs (nil if unknown); same last-writer caveat as `netAmount`.
public var fee: UInt64?
/// User-assigned label.
public var label: String
@@ -183,6 +183,11 @@ public final class PersistentTransaction {
@Relationship(inverse: \PersistentAccount.involvedTransactions)
public var involvedAccounts: [PersistentAccount] = []
+ /// Rust-emitted accounting per wallet, one row per `(wallet, txid)`.
+ /// Cascade-deletes with the transaction.
+ @Relationship(deleteRule: .cascade, inverse: \PersistentTransactionAccounting.transaction)
+ public var walletAccounting: [PersistentTransactionAccounting] = []
+
public init(
txid: Data,
transactionData: Data,
@@ -231,93 +236,36 @@ public final class PersistentTransaction {
}
}
- /// Core value movement for one wallet; `nil` when it cannot be derived yet.
- ///
- /// The stored scalar is the last recording wallet's (Rust `net_amount`,
- /// or the reconciliation over its own TXOs), so it answers only when
- /// `walletId` is the sole participant. Pending inputs do not veto that
- /// answer: `upsertTransaction` writes one for every input whose prevout
- /// has no local TXO — every foreign input of an incoming payment — and
- /// never prunes them, so they cannot tell a late input of ours apart.
- public func netAmount(for walletId: Data) -> Int64? {
- func owned(_ rows: [PersistentTxo]) -> [PersistentTxo] {
- var seen = Set()
- return rows.filter {
- PlatformWalletPersistenceHandler.isWalletOwnedTxo($0)
- && PlatformWalletPersistenceHandler.resolvedWalletId(of: $0) == walletId
- && seen.insert($0.outpoint).inserted
- }
- }
- let unownedTxos = (inputs + outputs).filter { !PlatformWalletPersistenceHandler.isWalletOwnedTxo($0) }
- let isSoleParticipant = participatingWalletIds == [walletId]
- if isSoleParticipant, unownedTxos.isEmpty {
- return netAmountUnavailable == true ? nil : netAmount
- }
- let walletInputs = owned(inputs)
- let walletOutputs = owned(outputs)
- guard !walletInputs.isEmpty || !walletOutputs.isEmpty else { return nil }
- let computed = Self.reconciledAccounting(
- inputs: walletInputs, ownedOutputAmounts: walletOutputs.map(\.amount),
- allOutputsOwned: false, previousDirection: direction, isAssetLock: isAssetLock
- )?.netAmount
- // Computed from TXOs alone: a pending input this wallet recorded may be
- // one of its own still-unlinked coins, so the sum is only provisional.
- // It stands when only a contact's watch-only TXOs kept the sole
- // participant off its stored amount and that amount agrees with it.
- // TODO(wallet-scoped-accounting-from-rust): a foreign payment to two
- // local wallets leaves an unresolvable pending input per wallet, so both
- // show "Amount unavailable". Store Rust's per-wallet net amount instead
- // (tracked in #5226).
- if pendingInputs.contains(where: { $0.walletId == walletId }) {
- guard isSoleParticipant, netAmountUnavailable != true, computed == netAmount,
- unownedTxos.allSatisfy(PlatformWalletPersistenceHandler.isContactTxo) else { return nil }
- }
- return computed
+ /// The accounting Rust emitted for `walletId`, if any.
+ public func accounting(for walletId: Data) -> PersistentTransactionAccounting? {
+ walletAccounting.first { $0.walletId == walletId }
}
- /// Direction relative to one wallet for transactions shared by multiple local wallets.
+ /// Core value movement for one wallet: its Rust-emitted row, else the
+ /// shared stored amount (a transaction Rust has no accounting for).
+ public func netAmount(for walletId: Data) -> Int64 {
+ accounting(for: walletId)?.netAmount ?? netAmount
+ }
+
+ /// `CoreDirectionCode` for one wallet, with the same fallback as `netAmount(for:)`.
public func direction(for walletId: Data) -> UInt32 {
- guard participatingWalletIds.count > 1, direction != CoreDirectionCode.coinJoin,
- typedKind != .coinJoin else { return direction }
- let spendsOurs = inputs.contains {
- PlatformWalletPersistenceHandler.isWalletOwnedTxo($0)
- && PlatformWalletPersistenceHandler.resolvedWalletId(of: $0) == walletId
- }
- if isAssetLock {
- let ownedOutputs = outputs.filter(PlatformWalletPersistenceHandler.isWalletOwnedTxo)
- if spendsOurs {
- return ownedOutputs.contains {
- PlatformWalletPersistenceHandler.resolvedWalletId(of: $0) != walletId
- } ? CoreDirectionCode.outgoing : direction
- }
- return ownedOutputs.contains {
- PlatformWalletPersistenceHandler.resolvedWalletId(of: $0) == walletId
- } ? CoreDirectionCode.incoming : direction
- }
- return spendsOurs ? CoreDirectionCode.outgoing : CoreDirectionCode.incoming
+ accounting(for: walletId)?.direction ?? direction
}
- /// Retain the sole surviving wallet's accounting before ownership links disappear.
- func preserveAccounting(removingWallet walletId: Data) {
- let participants = participatingWalletIds
- guard participants.count == 2, participants.contains(walletId),
- let survivor = participants.first(where: { $0 != walletId }) else { return }
- let amount = netAmount(for: survivor)
- let survivorDirection = direction(for: survivor)
- if let amount { netAmount = amount }
- netAmountUnavailable = amount == nil
- direction = survivorDirection
+ /// Fee for one wallet, with the same fallback as `netAmount(for:)`.
+ public func fee(for walletId: Data) -> UInt64? {
+ guard let row = accounting(for: walletId) else { return fee }
+ return row.fee
}
/// Format the wallet's Core value movement in DASH.
public func formattedAmount(for walletId: Data) -> String {
- guard let amount = netAmount(for: walletId) else { return "Amount unavailable" }
- return Self.format(duffs: amount)
+ Self.format(duffs: netAmount(for: walletId))
}
/// Net amount for `walletId`, or the stored scalar when no wallet scope is given.
- public func displayNetAmount(for walletId: Data?) -> Int64? {
- walletId.map { netAmount(for: $0) } ?? (netAmountUnavailable == true ? nil : netAmount)
+ public func displayNetAmount(for walletId: Data?) -> Int64 {
+ walletId.map { netAmount(for: $0) } ?? netAmount
}
/// `CoreDirectionCode` for `walletId`, or the stored direction when no wallet scope is given.
@@ -325,6 +273,11 @@ public final class PersistentTransaction {
walletId.map { direction(for: $0) } ?? direction
}
+ /// Fee for `walletId`, or the stored fee when no wallet scope is given.
+ public func displayFee(for walletId: Data?) -> UInt64? {
+ walletId.map { fee(for: $0) } ?? fee
+ }
+
/// Formatted amount for `walletId`, or the stored scalar's when no wallet scope is given.
public func displayFormattedAmount(for walletId: Data?) -> String {
walletId.map { formattedAmount(for: $0) } ?? formattedAmount
@@ -335,47 +288,6 @@ public final class PersistentTransaction {
String(format: "%@%.8f DASH", duffs >= 0 ? "+" : "-", Double(duffs.magnitude) / 100_000_000)
}
- /// Local wallets owning one of this transaction's TXOs or having recorded it
- /// (`involvedAccounts`), whose last writer's accounting is the stored scalar.
- private var participatingWalletIds: Set {
- let owning = (inputs + outputs).filter(PlatformWalletPersistenceHandler.isWalletOwnedTxo)
- .compactMap { PlatformWalletPersistenceHandler.resolvedWalletId(of: $0) }
- let recording = involvedAccounts.compactMap { account -> Data? in
- let wallet: PersistentWallet? = account.wallet
- return wallet?.walletId
- }
- return Set(owning + recording)
- }
-
- static func reconciledAccounting(
- inputs: [PersistentTxo], ownedOutputAmounts: [UInt64],
- allOutputsOwned: Bool, previousDirection: UInt32, isAssetLock: Bool
- ) -> (netAmount: Int64, direction: UInt32)? {
- func total(_ amounts: [UInt64]) -> Int64? {
- var sum: Int64 = 0
- for amount in amounts {
- guard let value = Int64(exactly: amount) else { return nil }
- let addition = sum.addingReportingOverflow(value)
- guard !addition.overflow else { return nil }
- sum = addition.partialValue
- }
- return sum
- }
- guard let received = total(ownedOutputAmounts), let spent = total(inputs.map(\.amount)) else {
- return nil
- }
- // Same rule as Rust (`platform_wallet::changeset::wallet_direction`):
- // internal only when nothing leaves the wallet and something stays in
- // it, or an asset lock burns into Platform. Both sides test one table.
- let direction: UInt32
- if previousDirection == CoreDirectionCode.coinJoin { direction = CoreDirectionCode.coinJoin }
- else if inputs.isEmpty { direction = CoreDirectionCode.incoming }
- else if allOutputsOwned && (!ownedOutputAmounts.isEmpty || isAssetLock) {
- direction = CoreDirectionCode.internalTransfer
- } else { direction = CoreDirectionCode.outgoing }
- return (received - spent, direction)
- }
-
public var directionName: String {
switch direction {
case CoreDirectionCode.incoming: return "Incoming"
@@ -485,19 +397,10 @@ public final class PersistentTransaction {
}
public var formattedAmount: String {
- netAmountUnavailable == true ? "Amount unavailable" : Self.format(duffs: netAmount)
+ Self.format(duffs: netAmount)
}
}
-/// Wire values of `PersistentTransaction.direction`, matching `directionName`
-/// and the FFI's `TransactionDirection` discriminants.
-public enum CoreDirectionCode {
- public static let incoming: UInt32 = 0
- public static let outgoing: UInt32 = 1
- public static let internalTransfer: UInt32 = 2
- public static let coinJoin: UInt32 = 3
-}
-
/// Typed mirror of Rust's
/// `key_wallet::transaction_checking::transaction_router::TransactionType`,
/// pinned to the `u8` discriminants emitted by
diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTransactionAccounting.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTransactionAccounting.swift
new file mode 100644
index 00000000000..e2da437cbef
--- /dev/null
+++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTransactionAccounting.swift
@@ -0,0 +1,48 @@
+import Foundation
+import SwiftData
+
+/// One transaction's Core accounting for ONE wallet, exactly as
+/// `rs-platform-wallet` emitted it (`TransactionAccountingFFI`, through
+/// `on_persist_transaction_accounting_fn`).
+///
+/// A transaction shared by several local wallets has one row per wallet,
+/// so each wallet shows its own side of it. A wallet with no row has no
+/// accounting from Rust yet (a payload-only provider transaction, or a
+/// stored row the load-time backfill has not reached). Pure storage:
+/// nothing on the Swift side derives, corrects or vetoes these values.
+@Model
+public final class PersistentTransactionAccounting {
+ #Unique([\.walletId, \.txid])
+ #Index([\.walletId], [\.txid])
+
+ /// The wallet this accounting belongs to (32 bytes).
+ public var walletId: Data
+ /// Transaction id, raw wire bytes like `PersistentTransaction.txid`.
+ public var txid: Data
+ /// Net Core amount in duffs for this wallet (positive = received).
+ public var netAmount: Int64
+ /// `CoreDirectionCode` wire value for this wallet.
+ public var direction: UInt32
+ /// Fee in duffs; `nil` unless this wallet funded every input.
+ public var fee: UInt64?
+ /// Inverse of `PersistentTransaction.walletAccounting`, which cascades.
+ public var transaction: PersistentTransaction?
+ public var lastUpdated: Date
+
+ public init(
+ walletId: Data,
+ txid: Data,
+ netAmount: Int64,
+ direction: UInt32,
+ fee: UInt64?,
+ transaction: PersistentTransaction?
+ ) {
+ self.walletId = walletId
+ self.txid = txid
+ self.netAmount = netAmount
+ self.direction = direction
+ self.fee = fee
+ self.transaction = transaction
+ self.lastUpdated = Date()
+ }
+}
diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/CoreDirectionCode.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/CoreDirectionCode.swift
new file mode 100644
index 00000000000..27f3c9abf4f
--- /dev/null
+++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/CoreDirectionCode.swift
@@ -0,0 +1,11 @@
+import DashSDKFFI
+
+/// Swift names for the `direction` wire values of `PersistentTransaction`
+/// and `PersistentTransactionAccounting`, bound to the constants the Rust
+/// FFI exports (`PLATFORM_WALLET_TRANSACTION_DIRECTION_*`), never re-declared.
+public enum CoreDirectionCode {
+ public static let incoming = UInt32(PLATFORM_WALLET_TRANSACTION_DIRECTION_INCOMING)
+ public static let outgoing = UInt32(PLATFORM_WALLET_TRANSACTION_DIRECTION_OUTGOING)
+ public static let internalTransfer = UInt32(PLATFORM_WALLET_TRANSACTION_DIRECTION_INTERNAL)
+ public static let coinJoin = UInt32(PLATFORM_WALLET_TRANSACTION_DIRECTION_COIN_JOIN)
+}
diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift
index 16bfee78e95..c0606d0955a 100644
--- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift
+++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift
@@ -271,7 +271,6 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
var coreAddressesByAddress: [String: PersistentCoreAddress] = [:]
}
private var roundIndex: ChangesetRoundIndex?
- private var accountingDirty: [Data: PersistentTransaction] = [:]
/// Number of persistence rounds committed by this handler, read and
/// compared on `serialQueue`. The store reconcile classifies rows off
/// this queue and applies the verdicts on it; a round committed in
@@ -437,8 +436,6 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
error: error
)
backgroundContext.rollback()
- // Rows staged by the failed save are gone; never reconcile them.
- accountingDirty.removeAll()
}
}
@@ -2655,11 +2652,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
record.hasBlockPosition = tx.has_block_position
let blockHashBytes = hashData(tx.block_hash)
record.blockHash = blockHashBytes.allSatisfy { $0 == 0 } ? nil : blockHashBytes
- // Empty asset-lock recovery records cannot replace a funded debit or an unavailable amount.
- let preserveLockAccounting = tx.transaction_type_kind == TransactionTypeKind.assetLock.rawValue
- && tx.net_amount == 0 && !tx.has_fee
- && (record.netAmount < 0 || record.netAmountUnavailable == true)
- if !preserveLockAccounting { record.direction = tx.direction }
+ record.direction = tx.direction
if let typeName = tx.transaction_type {
record.transactionType = String(cString: typeName)
}
@@ -2681,12 +2674,10 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
record.providerVotingKeyHash = tx.has_provider_voting_key_hash
? withUnsafeBytes(of: tx.provider_voting_key_hash) { Data($0) }
: nil
- if !preserveLockAccounting {
- record.netAmount = tx.net_amount
- record.netAmountUnavailable = false
- record.fee = tx.has_fee ? tx.fee : nil
- }
- accountingDirty[record.txid] = record
+ // The shared last-writer scalars, kept for unscoped display. The
+ // per-wallet values arrive through `persistTransactionAccounting`.
+ record.netAmount = tx.net_amount
+ record.fee = tx.has_fee ? tx.fee : nil
if let labelPtr = tx.label {
record.label = String(cString: labelPtr)
}
@@ -3030,8 +3021,6 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
/// (`reconcileHealMissingTxos`), so both writers honour the same
/// tombstone precedence and spender-adoption rules.
private func drainPendingInputs(into record: PersistentTxo, resolvedWalletId: Data) {
- if let parent = record.transaction { accountingDirty[parent.txid] = parent }
- if let spender = record.spendingTransaction { accountingDirty[spender.txid] = spender }
let pendingRows = pendingInputRows(outpoint: record.outpoint)
if !pendingRows.isEmpty {
// A tombstone is not an observation — it is a sweep's settled
@@ -3164,9 +3153,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
spender: PersistentTransaction,
inputIndex: UInt32?
) {
- accountingDirty[spender.txid] = spender
let currentSpender = txo.spendingTransaction
- if let currentSpender { accountingDirty[currentSpender.txid] = currentSpender }
let verdict = Self.reconcileSpendObservation(
currentSpenderTxid: currentSpender?.txid,
currentSpenderContext: currentSpender?.context,
@@ -3329,6 +3316,14 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
extensionCallbacks.on_load_identity_balance_block_time_fn = loadIdentityBalanceBlockTimeCallback
extensionCallbacks.on_persist_asset_lock_operation_id_fn = persistAssetLockOperationIdCallback
extensionCallbacks.on_load_asset_lock_operation_id_fn = loadAssetLockOperationIdCallback
+ // Per-wallet transaction accounting exactly as Rust computes it:
+ // after each round's changeset, and once at load for stored rows
+ // that have none yet (Rust reads the history back, computes, and
+ // hands the rows to the persist slot).
+ extensionCallbacks.on_persist_transaction_accounting_fn = persistTransactionAccountingCallback
+ extensionCallbacks.on_load_core_history_for_accounting_fn = loadCoreHistoryForAccountingCallback
+ extensionCallbacks.on_load_core_history_for_accounting_free_fn =
+ loadCoreHistoryForAccountingFreeCallback
return extensionCallbacks
}
@@ -3412,11 +3407,6 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
self.inChangeset = true
self.roundUtxoCreditVerdicts = [:]
self.roundUtxoCreditTally = UtxoCreditVerdictTally()
- // Out-of-round writers stage entries too (deferred backfills, a
- // heal step that stopped before reconciling its own); they are
- // not this round's to reconcile and may point at rows a failed
- // save rolled back. Load-time accounting repairs whatever is left.
- self.accountingDirty.removeAll()
SDKLogger.event(
"persistence_changeset_started",
category: .persistence,
@@ -3503,7 +3493,6 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
self.roundUtxoCreditVerdicts = [:]
self.roundUtxoCreditTally = UtxoCreditVerdictTally()
self.roundIndex = nil
- self.accountingDirty.removeAll()
self.roundAdvancedFinalityBoundary = false
self.inChangeset = false
self.drainDeferredBackfills()
@@ -3546,20 +3535,6 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
if roundAdvancedFinalityBoundary {
collectFinalizedSweptTombstones(walletId: walletId)
}
- // Display-only accounting: a failure here must not fail the
- // round, and is reported under its own event, not save_failed.
- // Recomputed values that did land are consistent on their own.
- // TODO(test-round-accounting-failure): cover this catch with a
- // FetchFaultInjector test; pinning which read faults needs a Swift run.
- do {
- try reconcileTransactionAccounting(Array(accountingDirty.values))
- } catch {
- SDKLogger.event(
- "persistence_transaction_accounting_failed", category: .persistence, severity: .error,
- fields: ["phase": .publicText("round"), "wallet_reference": .reference(walletId)],
- error: error
- )
- }
do {
try backgroundContext.save()
committedRoundGeneration &+= 1
@@ -6708,9 +6683,12 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
}
if let walletRow = walletRow {
- // Shared scalars must be scoped while the departing wallet's TXOs still exist.
- for transaction in try backgroundContext.fetch(FetchDescriptor()) {
- transaction.preserveAccounting(removingWallet: walletId)
+ // The departing wallet's accounting rows go with it; a
+ // shared transaction keeps the other wallets' rows.
+ let accountingRows = FetchDescriptor(
+ predicate: #Predicate { $0.walletId == walletId })
+ for row in try backgroundContext.fetch(accountingRows) {
+ backgroundContext.delete(row)
}
// Wallet → identities is `.nullify`; this delete
// path cascades them explicitly.
@@ -7133,77 +7111,6 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
return txids
}
- /// Repair only fully resolved spends; missing prevouts are not evidence of external ownership.
- func reconcileTransactionAccounting(
- _ transactions: [PersistentTransaction], txos: [Data: PersistentTxo]? = nil,
- addresses: [String: PersistentCoreAddress]? = nil
- ) throws {
- for transaction in transactions where !transaction.isDeleted {
- guard let transactionNetwork = network
- ?? Self.walletNetwork(of: transaction.involvedAccounts.first)
- ?? Self.walletNetwork(of: transaction.inputs.first?.account)
- ?? Self.walletNetwork(of: transaction.outputs.first?.account),
- let decoded = try? TransactionDecoder.decode(
- transaction.transactionData, network: transactionNetwork
- ), !decoded.inputs.isEmpty else { continue }
- var inputs: [PersistentTxo] = []
- var complete = true
- for input in decoded.inputs {
- let key = PersistentTxo.makeOutpoint(txid: input.prevTxid, vout: input.prevVout)
- let row: PersistentTxo?
- if let txos { row = txos[key] }
- else { row = try fetchTxoRowChecked(outpoint: key) }
- guard let row, !row.isDeleted, Self.isWalletOwnedTxo(row) else {
- complete = false
- break
- }
- inputs.append(row)
- }
- guard complete else { continue }
- var amounts: [UInt64] = []
- var allOutputsOwned = true
- // An output counts only for the spending wallets — a linked TXO by
- // its wallet, an address-matched one by its address's: another local
- // wallet's credit must not hide inside the sender's scalar.
- let spendingWallets = Set(inputs.compactMap { Self.resolvedWalletId(of: $0) })
- let ownedVouts = Set(transaction.outputs.filter { output -> Bool in
- guard !output.isDeleted, Self.isWalletOwnedTxo(output),
- let owner = Self.resolvedWalletId(of: output) else { return false }
- return spendingWallets.contains(owner)
- }.map(\.vout))
- for (index, output) in decoded.outputs.enumerated() {
- // OP_RETURN burns (including asset locks) are not spendable Core outputs.
- if output.isOpReturn { continue }
- var belongs = ownedVouts.contains(UInt32(index))
- if !belongs, let address = output.address {
- let descriptor = FetchDescriptor(predicate: #Predicate { $0.address == address })
- let owner: PersistentCoreAddress?
- if let cached = roundIndex?.coreAddressesByAddress[address] { owner = cached }
- else if let addresses { owner = addresses[address] }
- else { owner = try modelFetcher.fetch(descriptor, in: backgroundContext).first }
- if let account = owner?.account, account.accountType != Self.dashpayExternalAccountTypeTag {
- let ownerWallet: PersistentWallet? = account.wallet
- if let ownerWallet, spendingWallets.contains(ownerWallet.walletId) {
- belongs = true
- }
- }
- }
- if belongs { amounts.append(output.valueDuffs) }
- else { allOutputsOwned = false }
- }
- if let accounting = PersistentTransaction.reconciledAccounting(
- inputs: inputs, ownedOutputAmounts: amounts, allOutputsOwned: allOutputsOwned,
- previousDirection: transaction.typedKind == .coinJoin
- ? CoreDirectionCode.coinJoin : transaction.direction,
- isAssetLock: transaction.isAssetLock
- ) {
- transaction.netAmount = accounting.netAmount
- transaction.netAmountUnavailable = false
- transaction.direction = accounting.direction
- }
- }
- }
-
/// Returns `(nil, 0)` if nothing is restorable.
func loadWalletList() -> (entries: UnsafePointer?, count: Int, errored: Bool) {
SDKLogger.event(
@@ -7249,42 +7156,6 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable {
)
return (nil, 0, true)
}
- // Mid-round the context holds another round's staged writes: saving
- // would commit half of it and rolling back would silently drop it.
- // That round reconciles its own dirty rows; the next load repairs the rest.
- // TODO(persist-accounting-backfill-marker): this pass re-reads all
- // history on every launch; a persisted completion marker needs a
- // SwiftData shape change (a new live schema version) or a side
- // channel, which is a product decision.
- if !inChangeset {
- do {
- let walletIds = Set(wallets.map(\.walletId))
- let transactions = try modelFetcher.fetch(FetchDescriptor