Repository navigation
feat(platform)!: platform-wallet backend + iOS SDK wiring - #3531
Conversation
…, cleanup - Add PR-29 (asset lock test coverage) to PLAN.md - Add doc comments to SpvEventForwarder explaining why it exists - Remove process_mempool_transaction from broadcast (SPV handles it via bloom filter) - Minor cleanups in lib.rs, wallet_adapter, changeset traits Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ncState - Remove `manager` feature flag — SPV/manager code always compiled - Make key-wallet-manager and dash-spv non-optional dependencies - Remove all #[cfg(feature = "manager")] guards from events.rs, lib.rs - Extract synced_height/filter_committed_height/monitor_revision into shared SpvSyncState (Arc, no lock) — fixes synced_height() returning 0 during process_block() when adapter write lock is held - SpvWalletAdapter and SpvRuntime share Arc<SpvSyncState> Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…r handling - Fix stale broadcast_transaction doc comment (no longer feeds to adapter) - Fix run() error shadowing — log stop() failures instead of masking the actual SPV run result Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…-aware trait - Change PlatformWalletPersistence trait to &self with wallet_id parameter (one persister handles all wallets, can aggregate cross-wallet) - Move persister from PlatformWallet to PlatformWalletManager - PlatformWallet holds Arc<dyn Persistence>, calls queue/flush with wallet_id - create_wallet_from_seed_bytes() now creates, loads state, registers, notifies SPV — one call, fully configured, returns Arc<PlatformWallet> - Remove set_persister() and load_persisted_state() from PlatformWallet - Remove register_wallet() — registration is internal to create method Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Avoids blocking_write() on tokio RwLock which can deadlock if called from async context. Uses .write().await instead. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- queue() → store() (buffer changeset) - initialize() → load() (load wallet state from storage) - flush() stays Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…r.rs WalletPersister wraps Arc<dyn PlatformWalletPersistence> + wallet_id so callers don't pass wallet_id on every store/flush/load call. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ger (PR-25) - Add TransactionBroadcaster trait in asset_lock/broadcaster.rs - DapiBroadcaster implementation (existing DAPI gRPC logic) - AssetLockManager accepts Arc<dyn TransactionBroadcaster> at construction - PlatformWallet injects DapiBroadcaster by default - SPV broadcast can be injected via PlatformWalletManager in the future - Remove inline DAPI broadcast code from AssetLockManager Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…adcaster - Move broadcaster.rs from wallet/asset_lock/ to src/ (broadcasting is a wallet-level concern, not asset-lock specific) - Add SpvBroadcaster (delegates to SpvRuntime::broadcast_transaction) - Remove broadcast_transaction wrapper method from AssetLockManager, call self.broadcaster.broadcast() directly Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…(crate) - Apps should use PlatformWalletManager::broadcast_transaction() or AssetLockManager's injected broadcaster, not call SPV directly - Add broadcast_transaction() convenience method to PlatformWalletManager Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
SpvWalletAdapter::subscribe_events() was creating a dead channel (immediately dropping the sender). The SPV client's event monitor subscribes to this channel and crashed with "channel closed unexpectedly". Fix: maintain a live broadcast::Sender<WalletEvent> on the adapter. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…dresses Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ormWalletInfo> Replace all independent Arc<RwLock<...>> locks in PlatformWallet with a single Arc<RwLock<PlatformWalletInfo>> per wallet. Sub-wallets (CoreWallet, IdentityWallet, DashPayWallet, etc.) become facades that hold the shared lock and manage locking internally. - Add PlatformWalletInfo struct aggregating all mutable wallet state - Add WalletCreationOptions struct for create_wallet_from_seed_bytes - Add birth_height support for SPV filter scan optimization - Rename field info -> state, getters -> state()/state_mut()/etc. - Rename WalletInfoWriteGuard -> PlatformWalletInfoWriteGuard - Update SpvWalletAdapter to use single lock per wallet - Update example with meaningful API usage - 76 lib tests pass Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Add TransactionBroadcaster to CoreWallet (same pattern as AssetLockManager) - broadcast_transaction() delegates to broadcaster trait instead of inline DAPI gRPC - Remove dead methods: next_receive_address_for_account_blocking(), next_change_address_for_account_blocking() (0 callers) - Make next_change_address() pub(crate) (internal only) - Remove unused consensus import Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Use platform_wallet.load_persisted() instead of calling the shared persister directly with wallet_id. All persistence ops (store, flush, load) now go through the per-wallet WalletPersister wrapper. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
CoreAddressInfo is a UI-only type that doesn't belong in the wallet library. Move it to dash-evo-tool's platform_wallet_bridge module. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
SpvRuntime gains reset_filter_committed_height() so tests can force a filter rescan when wallet state isn't persisted yet. Also promote monitored_addresses log to info level for test diagnostics. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…formWallet State access methods (state, state_mut, state_blocking, try_state, try_state_mut) are now public on PlatformWallet and pub(crate) on CoreWallet. External callers use wallet.state() instead of wallet.core().state(). Sub-wallets remain facades that manage locking internally. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…nd current status Add current status section (2026-04-08) reflecting completed locking refactoring. Add single-lock architecture diagram. Mark old architecture and struct definitions as outdated. Condense PR history for completed PRs. Also add TODO notes in CoreWallet and PlatformWallet for future cleanup. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add detailed spec for PR-30: replace SpvWalletAdapter, SpvSyncState, and PlatformWalletInfoWriteGuard with dashcore's WalletManager<T>. Introduces ManagedWalletState in dashcore, per-wallet Arc<RwLock<T>> in WalletManager, and BalanceUpdated event-driven balance updates. Supersedes PR-23 and PR-27. Also update E2E test status to PASS. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
PR-20 core API (one-call identity methods + IS→CL fallback) is done in platform-wallet. PR-21 TransactionBuilder already unified. Remaining gaps filed as PR-31: switch evo-tool to one-call identity APIs, and implement asset lock changeset restore (restore_from_changeset_blocking). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…etry path IdentityFunding needs Clone so evo-tool can retry identity registration with the same funding method on version-mismatch errors. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…vWalletAdapter PR-30 Phase 2: Replace custom SpvWalletAdapter with dashcore's WalletManager<PlatformWalletInfo> for SPV integration. Key changes: - PlatformWalletInfo uses ManagedWalletState<PlatformWalletPersisterBridge> for automatic changeset persistence during check_core_transaction (C2) - Arc<WalletBalance> shared between PlatformWalletInfo and CoreWallet for lock-free balance reads; updated via BalanceUpdated events (C1) - Delete SpvWalletAdapter (~330 lines) — WalletManager implements WalletInterface directly - Delete SpvSyncState (~55 lines) — WalletManager tracks heights - Delete PlatformWalletInfoWriteGuard — balance via events not Drop - SpvRuntime holds Arc<RwLock<WalletManager<PlatformWalletInfo>>> - PlatformWalletManager shares Arc<RwLock<PlatformWalletInfo>> between WalletManager (SPV) and PlatformWallet handles (sub-wallets) - wallets map behind RwLock for interior mutability (&self methods) (W3) - Trait impls split to platform_wallet_traits.rs (W8) - Remove dead CoreWallet state accessors (I1) - PlatformWalletPersisterBridge bridges WalletChangeSet to PlatformWalletChangeSet for persistence - Remove notify_wallets_changed (W5) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…nnel capacity - mark_instant_send_utxos now takes &InstantLock parameter - TransactionContext::InstantSend(_) pattern match - PlatformWalletEvent channel capacity increased to match dashcore's DEFAULT_SYNC_EVENT_CAPACITY (10000) to prevent broadcast lag Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Rewrite platform-wallet to use dashcore's unchanged v0.42-dev WalletManager (two separate maps for Wallet keys and WalletInfo state) instead of the feat/platform-wallet single-map Arc<RwLock<T>> design that caused 7x SPV slowdown. Key changes: - PlatformWalletInfo wraps ManagedWalletInfo directly (field: core_wallet), no longer holds Wallet key material or ManagedWalletState - Sub-wallets hold wallet_manager + wallet_id instead of Arc<RwLock<PlatformWalletInfo>>, access state through WalletManager lock - WalletStateReadGuard/WalletStateWriteGuard with Deref/DerefMut to PlatformWalletInfo plus .wallet() for key material access - Remove WalletPersistence/ManagedWalletState/changeset dependencies from dashcore (don't exist on v0.42-dev) - Remove standalone PlatformWallet constructors (unused, evo-tool uses PlatformWalletManager exclusively) - Remove WalletCreationOptions wrapper, accept WalletAccountCreationOptions directly from dashcore - Remove reset_filter_committed_height and synced_height from SpvRuntime Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Verifies that PlatformWalletManager can create a wallet from a mnemonic, start SPV, sync with testnet, and see a non-zero spendable balance. Requires SPV_TEST_MNEMONIC env var and network access. Marked #[ignore]. Run: SPV_TEST_MNEMONIC="..." cargo test -p platform-wallet --test spv_sync -- --ignored --nocapture Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Use real testnet DAPI addresses + NoopContextProvider instead of mock SDK - Add tracing-subscriber for RUST_LOG support - Increase timeout to 600s for cold-start header sync Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ntManager Replace the cloning broadcast::Sender<PlatformWalletEvent> with a trait-based event system: - PlatformEventHandler: EventHandler supertrait for app consumers - PlatformEventManager: dispatches to Vec<Arc<dyn PlatformEventHandler>> by reference (no clone), implements EventHandler for DashSpvClient - LockNotifyHandler: PlatformEventHandler that wakes AssetLockManager async waiters on InstantLock/ChainLock events via tokio::sync::Notify - AssetLockManager wait_for_proof/wait_for_chain_lock use Notify instead of broadcast channel subscription Apps pass their handler to PlatformWalletManager::new(). Internally, LockNotifyHandler is added to the handler list automatically. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… partial read migration Checkpoint commit for the AppState.identities removal work. Adds the canonical wallet-identity relationship and migrates the 3 simplest balance-sum readers off the legacy ObservableObject mirror; full removal of `AppState.identities` + `IdentityModel` to follow. Schema: - `PersistentWallet` gains `@Relationship(deleteRule: .nullify, inverse: \PersistentIdentity.wallet) var identities: [PersistentIdentity]` — cardinality 1..N with nullify so wallet deletion orphans its identities rather than cascading them. Matches the existing `accounts` relationship pattern. - `PersistentIdentity` gets a plain `wallet: PersistentWallet?` stored property (inverse lives on the wallet side). `walletId` is kept alongside it as a denormalized key because Rust-side changesets ship `[u8; 32]` directly and multiple predicates already filter by it; the invariant is `wallet?.walletId == walletId`. - `identityIndex: UInt32` stays — meaningful iff `wallet != nil`, always present with default 0. Persister wiring: - `persistIdentities` now calls `fetchWalletForLink(walletId:)` after writing the scalar `walletId`, assigns the result to `row.wallet`, and SwiftData keeps the inverse collection in sync. The helper is non-creating so a stray identity upsert never materializes a placeholder wallet. PersistentIdentity helper surface: - `PersistentIdentity.fetch(in:identityId:)` — one-row lookup by raw 32-byte id. - `updateBalance(in:identityId:balance:)`, `updateDpnsName(in:identityId:dpnsName:)`, `updateMainDpnsName(in:identityId:mainDpnsName:)`, `remove(in:identityId:)` — fetch + set + bump `lastUpdated`, leave `save()` to the caller. Replaces the equivalent mutators on `AppState` that wrote through `DataManager` + mirrored to the `@Published [IdentityModel]` array. Migrated readers: - `CoreContentView.WalletRowView.platformBalance`, `WalletDetailView.platformBalance`, and `SendTransactionView.platformBalance` now sum `persistentWallets.first?.identities` via the relationship rather than filtering `platformState.identities` by walletId + network. One less place that has to be kept in sync. Still to do in follow-up: - Migrate the remaining 10-ish views off `appState.identities`. - Delete `IdentityModel` entirely (detail-view params → `PersistentIdentity`, DPP bridge + toIdentityModel helpers removed). - Drop `@Published var identities` + mutators from `AppState`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…tityModel onto PersistentIdentity Second batch of the AppState.identities removal. Every `let identity: IdentityModel` parameter on these views flips to `let identity: PersistentIdentity`, reads pull fields from the live SwiftData row directly, and alias/main-name mutations go through either `PersistentIdentity.update*` static helpers or a direct write on the live row — no more `appState.updateIdentity*` indirection. Affected views: - `KeyDetailView` / `KeysListView` — use `identity.identityPublicKeys` (new projection helper on PersistentIdentity that compactMaps `PersistentPublicKey` → DPP `IdentityPublicKey`) so the row-level UI keeps working against the DPP type while the parent carries the SwiftData entity. - `RegisterNameView` — deletes the manual `appState.identities` mirror update after DPNS registration. The Rust persister already writes the new label via `persistIdentities` → `PersistentIdentity.dpnsName`, and every `@Query` view refreshes reactively; the mirror was pure redundancy. - `SelectMainNameView` — pulls `dpnsNames` / `contestedDpnsNames` from the wallet's `ManagedIdentity` FFI (`getDpnsNames` / `getContestedDpnsNames`) on appear, writes the main-name selection via `PersistentIdentity.updateMain- DpnsName`. Prior impl read these lists off IdentityModel's UI-only mirror, which was populated from the same FFI calls. - `IdentityDetailView` — tracks the live row via `@Query` with an `identityId` predicate; inline alias edit writes through `@Environment(\.modelContext)`. PersistentIdentity helper surface expanded: - `identityPublicKeys: [IdentityPublicKey]` — DPP projection. - `displayName: String` — alias → mainDpnsName → dpnsName → truncated hex, mirroring the old `IdentityModel.displayName` extension. - `updateBalance` / `updateDpnsName` / `updateMainDpnsName` / `remove` / `fetch` — one-shot static mutation helpers, replacing the equivalent AppState mutators that wrote via DataManager + mirrored to the ObservableObject array. Full `IdentityModel` removal + `AppState.identities` deletion still to come. The remaining ~10 views (IdentitiesView, IdentitiesContentView, TokensView, FriendsView, DocumentsView, ContestDetailView, TransitionDetailView, LoadIdentityView, OptionsView's loadSampleIdentities, SendViewModel) continue to build against the IdentityModel surface for now — this commit is a clean checkpoint, no regressions. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…section
`AppState.loadSampleIdentities` built three fake local
identities (Alice / Bob / Charlie) with 0x11/0x22/0x33-repeat
ids, isLocal: true, and stuffed them into SwiftData + the
`@Published` array. The accompanying "Load Sample Identities"
button sat in `OptionsView`'s Developer section next to two
already-disabled placeholder toggles.
None of it is useful now:
- The fake ids don't round-trip — not valid Platform
identifiers, no signer can sign with them, no wallet owns
them. Pure placeholder data.
- Every tap clobbered `appState.identities` with the same three
rows, losing real identities that had been loaded.
- Rows persisted to SwiftData with no undo, accumulating
test garbage across app launches.
- Create Identity / Load Identity / Search Wallets for
Identities all produce real identities now; the dev seeder
covers nothing the real paths don't.
- It was also the last live `IdentityModel` construction site
outside the UI-level refactor queue — one fewer thing blocking
the IdentityModel deletion.
Drop the method, the button, and the two placeholder Developer-
section toggles ("Show Test Data", "Enable Debug Logging" — both
`.disabled(true)` since inception). Trivial to restore if/when
developer-tools gain actual wired-up content.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…odel The three legacy value-type models were a pre-SwiftData relic. Every view already had a `PersistentIdentity` / `PersistentDataContract` / `PersistentDocument` available via `@Query`, but AppState still mirrored identities as a `@Published [IdentityModel]`, DocumentsView/ContractsView still seeded sample `*Model` structs on first appearance, and a tree of `from(_:)` / `toXxxModel()` bridges ferried data through an unnecessary detour. Two sources of truth, one always stale. This removes the value-type layer entirely: - Delete `IdentityModel.swift`, `DocumentModel.swift`, and `ContractModel.swift` from the SDK. - Strip the `from(_:)` / `toXxxModel()` bridges from the `Persistent*` rows. App-side `Models/SwiftData/` and `Models/DPP/` files are now just typealiases + a `paddedToLength` helper. AppState loses its `identities` / `contracts` / `documents` `@Published` arrays and all 11 identity mutators (`addIdentity`, `updateIdentityBalance`, `updateIdentityDPNSName`, `updateIdentityMainName`, `updateIdentityDPNSNames`, `updateIdentityPublicKeys`, `removeIdentity`, `associateIdentityWithWallet`, `removePrivateKeyReference`, `addContract`, `addDocument`). Views own a `ModelContext` and mutate `PersistentIdentity` rows directly, using the small static mutation helpers added in the earlier migration pass. `DataManager` drops ~250 lines — every `saveIdentity`/`fetchIdentities`/`saveDocument`/ `fetchDocuments`/`saveContract`/`fetchContracts`/ `fetchIdentitiesNeedingSync`/`removePrivateKeyReference` helper is gone. What remains is token-balance upserts, `clearAllData`, `getDataStatistics`, and the `currentNetwork` pointer. View migrations: - `LoadIdentityView` builds the `PersistentIdentity` row directly, copies fetched public keys into `PersistentPublicKey` rows, matches user-supplied private keys via `KeyValidation.matchPrivateKeyToPublicKeys` and stores them in the keychain, and routes the DPNS label update through `PersistentIdentity.updateDpnsName`. - `IdentityDetailView` writes balance/public-key refreshes straight to the queried `PersistentIdentity` row (preserving existing `privateKeyKeychainIdentifier`s across a public-key replace) and assigns the fetched DPNS name/contest lists to local `@State` — the previous `appState.updateIdentityDPNSNames` call wrote into the IdentityModel cache but the view's state was never bound to it, so nothing rendered. - `KeyDetailView` / `KeysListView` clear `privateKeyKeychainIdentifier` on the matching `PersistentPublicKey` directly. - `DocumentsView` / `ContractsView` rewritten around `@Query PersistentDocument` / `@Query PersistentDataContract`. No more hard-coded Alice/Bob/DPNS/DashPay sample rows. - `SendViewModel.platformToShielded` takes a `ModelContext`, fetches a wallet-scoped identity with sufficient balance via `FetchDescriptor`, and pulls the first keychain-stored private key via `retrievePrivateKey(identityId:keyIndex:)`. Private keys no longer live on the identity row itself. Net diff: +626 / -1911. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Every upsert of a `PersistentIdentity` already fetched the
matching `PersistentWallet` row and set `row.wallet` (to preserve
the `deleteRule: .nullify` invariant). The scalar `walletId`
field on the side was a second source of truth that had to be
kept in sync with the relationship forever — one new column of
maintenance for no new capability.
Only one SwiftData predicate actually filtered identities by the
scalar (`SendViewModel.platformToShielded`), and the
`wallet?.walletId` form used by `PersistentAccount` predicates
works the same way. So the field earns its keep twice: once when
the persister writes it, never when anyone reads it in a way the
relationship couldn't satisfy.
This deletes the field + init parameter + init body assignment.
The persister's `persistIdentities` still calls
`fetchWalletForLink` and assigns `row.wallet` on every upsert;
the `row.walletId = entry.walletId` line that ran immediately
before is gone. Reads across the app:
- `SendViewModel` predicate → `identity.wallet?.walletId`
- `IdentityDetailView` (×5) — DashPay profile lookup, contest
fetch, DPNS-name fetch, name-selection — all via
`identity.wallet?.walletId`.
- `FriendsView` (×5: wallet resolution, recipient metadata,
balance, send, `SendDashPayPaymentSheet`) — same hop.
- `SelectMainNameView`, `RegisterNameView`, `ContestDetailView`
(×1 each) — same hop.
- `StorageModelListViews.walletGroups` — the `Dictionary(grouping:
identities) { $0.walletId ?? Data() }` cluster key becomes
`$0.wallet?.walletId ?? Data()`; placeholder-last sort works
identically.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`TokenModel` was a flat value-type package of token config +
balance state that a demo view clobbered into
`AppState.tokens` via `loadSampleTokens()` on first appearance.
`PersistentToken` and `PersistentTokenBalance` cover the same
territory as first-class SwiftData rows — plus supply
rules, freeze/mint/burn control, distribution configs, history
events, and everything else the real DPP token spec requires.
Carrying the flat struct alongside them was dead weight.
This migration follows the same playbook as the
`IdentityModel` / `DocumentModel` / `ContractModel` removals:
- `TokensView` now reads `selectedIdentity.tokenBalances`
through the `@Relationship` already on `PersistentIdentity`.
No separate `@Query` needed.
- `TokenRow` takes `PersistentTokenBalance`, reads the headline
from `token?.name ?? tokenName`, surfaces `displayBalance`
for amounts, and renders `token?.maxSupply ?? token?.baseSupply`
for the supply line.
- `TokenActionsView` / `TokenActionDetailView` take the same
balance row plus the optional `identity` (for credits
rendering in the "Selected Identity" section). Every action
branch survives — they were stubs that only
`appState.showError(...)` with a message anyway.
- Demo-only UI gone:
- `availableClaims` list (always empty in prod; claims come
from `PersistentToken.perpetualDistribution` /
`preProgrammedDistribution` when that flow actually
ships).
- `pricePerToken` / "total cost" math for direct purchase
(price belongs on a direct-pricing document, not the
token row).
- `loadSampleTokens()` and the onAppear that seeded DPT/TEST
rows.
- `AppState.tokens: [TokenModel]` deleted; `switchNetwork`
stops clearing it (the remaining `@Query` consumers filter by
`network` scope automatically).
- `TokenModel.swift` removed. `TokenAction.swift` stays — it's a
standalone enum.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
On Thai / Japanese / ROC regions `Calendar.current` is Buddhist / Japanese / ROC, so bare `Date.formatted(...)` and `Text(date, style: .date)` render "24 Apr 2569 BE" instead of "24 Apr 2026". The app's strings are English and its on-chain timestamps are Unix epoch seconds — a non-CE year is wrong for both. Adds `Utils/AppDateFormatting.swift` with three entry points: - `AppDate.formatted(_:dateStyle:timeStyle:)` for display text. Keeps the user's locale for month name / 12-vs-24h choice; only the calendar is swapped to Gregorian. - `AppDate.formatted(optional:…)` for the `Date?` variant with a placeholder (matches the old ad-hoc `dateString(_:)` helper). - `AppDate.relative(_:)` for "5 minutes ago" strings. - `DateFormatter.gregorian()` factory for the legacy-API callsites that still want a `DateFormatter` (custom `dateFormat` strings). - `DateFormatter.posixGregorian()` for machine-readable output (UTC, logs) — pins locale as well as calendar. Call-site routing: - `StorageRecordDetailViews.dateString` → `AppDate.formatted`. The inline UTC formatter at the sync-watermark section uses `DateFormatter.posixGregorian()` so its "yyyy-MM-dd HH:mm:ss UTC" stays stable across devices. - `DocumentsView` detail rows (`document.createdAt.formatted()`) and the private `dateFormatter` singleton. - `DataContractDetailsView` date + relative init branches. - `Text(Date, style: .date)` / `Text(Date, style: .time)` sites in `WalletDetailView`, `CoreContentView` (block-time row), `StorageModelListViews` (token history row) swap to explicit `Text(AppDate.formatted(...))`. `.relative` sites stay put — `RelativeDateTimeFormatter` doesn't expose year numbers. - `KeychainExplorerView`, `CoreContentView`, `TransactionDetailView`, `DiagnosticsView` date formatters gain the Gregorian calendar. - SDK-side `PersistentDocument.summary` formatter gets an inline Gregorian calendar (can't depend on the app's `AppDate`). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The identity storage detail view had a Relationships section that listed Public Keys / Documents / Token Balances, but left the owning wallet invisible — `PersistentIdentity.wallet` and `identityIndex` shipped with the SwiftData model migration but never made it onto this screen, so there was no way to tell from the explorer whether an identity was anchored to a wallet or orphaned. Adds: - `Wallet` row in the identity's Relationships section. Priority is wallet name → short hex fingerprint of the wallet id (`"deadbeef…"`) → `"None"` for detached rows. Uses a new file-private `walletLabel(_:)` helper so future relationship-carrying storage views can reuse the same presentation. - `Identity Index` row in the identity's Core section, rendered as `"—"` when no wallet is attached (the index is ignored in that case by the model contract). - `Identities` row in the wallet's Relationships section — the inverse side, so the mapping is visible from both ends of the relationship. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
New identities registered via `ManagedPlatformWallet.registerIdentityFromAddresses(...)` landed in SwiftData with `wallet = nil`, even though the identity was created under a specific wallet's scope — the storage explorer's "Wallet" field showed "None" immediately after a successful registration. Root cause: the Rust side emits the `IdentityEntryFFI` for a freshly-registered identity with `wallet_id_is_some == false` (the identity object isn't wallet-linked in its own Rust struct at emit time — the link is implicit via the wallet- scoped changeset, not stamped per-entry). The Swift persister then called `fetchWalletForLink(walletId: entry.walletId)`, which short-circuits to `nil` on a nil input, orphaning the row. Fix: use `entry.walletId ?? walletId` (the scope parameter the callback was invoked with) in `persistIdentities`. The scope `walletId` is always the wallet whose changeset we're applying, so every identity in the upsert list belongs to it by construction — the per-entry field becomes a refinement for corner cases (e.g. a future BLAST pass surfacing identities anchored to a *different* wallet) rather than a required setter. Applied the same fallback to `persistIdentityKeys`: the derivation path requires the owning wallet's mnemonic, so defaulting to the scope wallet when `entry.walletId` is nil is the natural resolution and keeps freshly-registered keys re-derivable from their wallet's seed. The now-redundant `_ = walletId` placeholder at the bottom of the function is gone. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…fresh identities Opening the identity detail view for a just-registered identity crashed with EXC_BAD_ACCESS deep inside Rust's `Identifier::from_bytes` on the first frame above `platform_wallet_get_dashpay_profile`. The crash only surfaced after the prior fix started actually linking new identities to their wallets — before that, `identity.wallet?.walletId` was nil and the entire code path was skipped. The root cause is still being investigated (the wallet-level by-id FFI does not obviously mishandle the `IdentifierBytes` pass-by-value argument, yet the crash is reproducible on this one call path only). What we can do immediately is side-step the problematic entry point: both `DashPayProfile` FFI readers return the same cached data, but `managed_identity_get_dashpay_profile` takes a `Handle` (u64) rather than `IdentifierBytes` pass-by-value. Change `IdentityDetailView`'s two profile reads (`loadCachedDashPayProfile` on appear, and `refreshDashPayProfilesFromPlatform` after sync) to: 1. Resolve the `ManagedIdentity` via `wallet.managedIdentity(identityId:)`. This is the same pattern FriendsView / SelectMainNameView / RegisterNameView already use without issue. 2. Call the resolved identity's `getDashPayProfile()` — handle- based, no aggregate arg. Fresh-register race is handled by catching `PlatformWalletError.identityNotFound` and returning silently — the background `syncDashPayProfiles()` task (also triggered on appear) will pick up the profile once the Rust-side `IdentityManager` has observed the new entry. FriendsView's two existing `wallet.getDashPayProfile(identityId:)` calls read profiles for *contact* identities (not managed by the local wallet, so `wallet.managedIdentity(identityId:)` would return `.identityNotFound`). Those call sites stay — they've been in daily use without the crash. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…n PersistentWallet
`HDWallet` was the app's original `@Model` wallet row, created
alongside `PersistentWallet` by every wallet-creation path —
two sources of truth for every wallet, with a standing TODO in
`CreateWalletView` to "Replace HDWallet with PersistentWallet
as the canonical SwiftData model for the UI". `HDWalletModels`
declared four supporting types (`AccountCategory`,
`AccountInfo`, `AddressDetail`, `AccountDetailInfo`) that had
zero external references; the file's own header even pointed
at companion files (`HDTransaction.swift`, `UTXO.swift`,
`HDAccount`, `HDAddress`) that no longer exist.
Changes:
- `HDWalletModels.swift` deleted outright (dead code,
including an empty `Core/Models/` directory cleaned up).
- `HDWallet.swift` deleted. Schema entry removed from
`ModelContainerHelper`.
- `PersistentWallet` gains three bits of compatibility surface:
- `isWatchOnly: Bool = false` + `isImported: Bool = false`
stored properties (default values for painless schema
migration on existing containers).
- `label: String` computed fallback (prefers `name`, else
`"Wallet <first-4-bytes-hex>…"`) so view code keeps working
without conditionally unwrapping `name` at every site.
- `networkEnum: AppNetwork` computed helper (parses the
stored `network: String` back into the app enum, falls
back to `.testnet` on unknown strings).
- `CreateWalletView` stops instantiating the duplicate HDWallet
row. The persister callback already creates the
`PersistentWallet` row downstream of
`walletManager.createWallet(...)` — we only have to patch
`isImported` after-the-fact via a main-context fetch
(autosave from the background context has run by then).
`Mnemonic.toSeed(...)` call gone — the seed that was stashed
in `serializedWalletBytes` lives only in the keychain now.
- `ContentView` (orphan-mnemonic recovery) routes through
`persistentWallets: [PersistentWallet]` instead of
`hdWallets`; the recreate path drops the HDWallet insert
for the same reason.
- Thirteen downstream views migrated — `WalletsContentView`,
`WalletDetailView`, `CoreContentView`, `AccountListView`,
`AccountDetailView`, `ReceiveAddressView`,
`TransactionListView`, `SendTransactionView`,
`SendViewModel`, `CreateIdentityView`,
`StorageModelListViews`, `SearchWalletsForIdentitiesView`,
and their @query sources / function parameters. Reads of
`wallet.network.rawValue` became `wallet.network` (already a
String); enum-switch sites got `wallet.networkEnum`; the
write at `saveWalletName` became `wallet.name` (the
`label` computed form has no setter). Several views had a
redundant `@Query<PersistentWallet>` for the same walletId
they were handed — those queries are gone.
- `BalanceCardView` / `WalletRowView` / `SendTransactionView`
all read balance/identities/accounts directly off the
passed-in `wallet` instead of re-fetching through a local
@query.
Net diff: +181 / -282.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Important Review skippedToo many files! This PR contains 299 files, which is 149 over the limit of 150. ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (299)
You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…let-only # Conflicts: # Cargo.lock # Cargo.toml # packages/rs-platform-wallet-ffi/Cargo.toml # packages/rs-platform-wallet-ffi/src/platform_wallet_info.rs # packages/rs-platform-wallet/src/platform_wallet_info/wallet_info_interface.rs # packages/rs-sdk-ffi/Cargo.toml # packages/rs-sdk-ffi/src/address_sync/mod.rs # packages/rs-sdk-ffi/src/address_sync/provider.rs # packages/rs-sdk/src/platform/address_sync/mod.rs # packages/rs-sdk/src/platform/address_sync/provider.rs # packages/rs-sdk/tests/fetch/address_sync.rs # packages/swift-sdk/Sources/SwiftDashSDK/Core/Models/HDWalletModels.swift # packages/swift-sdk/Sources/SwiftDashSDK/Core/SPV/SPVClient.swift # packages/swift-sdk/Sources/SwiftDashSDK/Core/SPV/SPVEventHandler.swift # packages/swift-sdk/Sources/SwiftDashSDK/Core/Services/WalletService.swift # packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/CoreWalletManager.swift # packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/HDWallet.swift # packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift # packages/swift-sdk/Sources/SwiftDashSDK/KeyWallet/KeyWalletTypes.swift # packages/swift-sdk/Sources/SwiftDashSDK/KeyWallet/ManagedAccount.swift # packages/swift-sdk/Sources/SwiftDashSDK/KeyWallet/ManagedWallet.swift # packages/swift-sdk/Sources/SwiftDashSDK/KeyWallet/Transaction.swift # packages/swift-sdk/Sources/SwiftDashSDK/KeyWallet/WalletManager.swift # packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletFFI.swift # packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletTypes.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/ContentView.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/ViewModels/SendViewModel.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/AccountDetailView.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/AccountListView.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CoreContentView.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CreateWalletView.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/TransactionDetailView.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/TransactionListView.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletsContentView.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift # packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/UnifiedAppState.swift
Review GateCommit:
|
Switches from ../rust-dashcore/* path deps to git+rev so CI can build
without the local checkout. Rev 4c8bec36 is the current tip of
feat/platform-wallet2 on rust-dashcore, which carries the DIP-13 identity
auth accounts, async Signer trait, WalletPersistence + BDK-style
changesets, DIP-17 platform addresses, and the mutable wallet-info
accessors (insert_wallet, get_wallet_{and,mut_and}_info_mut) that
platform-wallet depends on.
Addresses ~170 clippy errors surfaced by `-D warnings` after merging
v3.1-dev and switching rust-dashcore to feat/platform-wallet2 rev, where
PlatformAddress and AuthorizedActionTakers became Copy, the Network enum
lost non-exhaustive coverage, and several stricter lints became errors in
Rust 1.92.
Mechanical cleanups:
- Strip .clone() on Copy types (PlatformAddress 38x, AuthorizedActionTakers 57x,
plus scattered Identifier/BlockInfo/AccountType/Option<(_,u64)>).
- Replace `match X { Y::V0(d) => d }` with irrefutable-let for V0-only enums.
- Remove `_ => …` dead arms after Network variants were fully covered.
- assert_eq!(x, true|false) → assert!(x) / assert!(!x).
- Fix needless_borrows_for_generic_args, manual_range_contains, len_zero,
useless_vec, useless_conversion, for_kv_map, map_entry, irrefutable_let,
unnecessary_get_then_check, redundant_closure, field_reassign_with_default
where the fix is purely stylistic.
- Drop unused imports (DataContractV1Getters, OutPoint/Txid) and unused vars.
Judgment-call #[allow]s where the intentional pattern is pervasive:
- Test-heavy crates (rs-drive-abci, strategy_tests, rs-platform-wallet,
rs-platform-wallet-ffi) get cfg_attr(test, allow(…)) for clone_on_copy,
useless_vec, bool_assert_comparison, field_reassign_with_default,
module_inception on intentional nested test modules.
- Per-module #[allow(clippy::approx_constant)] for test code that uses
3.14/2.718 as serialization fixtures, not mathematical constants.
- Per-crate allow(result_large_err, large_enum_variant) on PlatformWalletError
where a proper fix requires Box<…> variants — tracked for a later refactor.
Also fixes a couple of real issues the stricter lints caught:
- Non-binding `let _ = …read()` on a sync-lock in rs-drive tests.
- `provider.pending_addresses().is_empty()` on an opaque Iterator in
rs-sdk-ffi test — now `.count() == 0`.
- Contact-request test helpers in rs-platform-wallet-ffi were calling
add_sent_/add_incoming_contact_request with the old 1-arg signature;
updated to pass a noop WalletPersister.
`cargo clippy --workspace --all-features --locked --all-targets --
--no-deps -D warnings` is clean. `cargo fmt --all --check` is clean.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## v3.1-dev #3531 +/- ##
=========================================
Coverage 88.18% 88.19%
=========================================
Files 2474 2474
Lines 298763 298726 -37
=========================================
- Hits 263477 263447 -30
+ Misses 35286 35279 -7
🚀 New features to boost your workflow:
|
…ella
packages/swift-sdk/build_ios.sh generates an umbrella header that
#includes "platform-wallet-ffi/platform-wallet-ffi.h", and the unified
xcframework layout expects each FFI crate to contribute its own
subdir under target/<profile>/include/ via a cbindgen build.rs.
This matches rs-sdk-ffi/build.rs exactly (same helper, same cbindgen
call). I reverted this file earlier during the v3.1-dev merge thinking
our crate was more advanced — but the build.rs + cbindgen.toml pair
is the mechanism that produces the umbrella-referenced header, so
without it the Swift CI job fails with:
error: 'platform-wallet-ffi/platform-wallet-ffi.h' file not found
Two FFI functions exposed Rust-native types in their signatures,
which cbindgen emitted unresolved into the generated header:
- platform_wallet_info_create_from_{seed,mnemonic} took `network: Network`
by value. cbindgen wrote `Network network` into the header with no
typedef, breaking the Swift build with `unknown type name 'Network'`.
Switched to `network: u32` with 0/1/2/3 → Mainnet/Testnet/Devnet/Regtest,
matching the existing convention used by platform_wallet_manager_create_wallet_from_seed.
- platform_wallet_manager_create takes `sdk_ptr: *const Sdk` where `Sdk`
is from the external dash-sdk crate. cbindgen can't introspect external
crates, so the emitted `const Sdk *` had no forward declaration. Added
an `after_includes` block to cbindgen.toml that injects
`typedef struct Sdk Sdk;`, which build_ios.sh's post-processor then
expands into an opaque `{ uint8_t _opaque; }` definition — the same
mechanism the umbrella header relies on for all other FFI types.
Updated call sites in integration_tests.rs and the in-crate test module
to pass `1 /* Testnet */` instead of `Network::Testnet`.
… platform-wallet-ffi
After bumping rust-dashcore to feat/platform-wallet2 rev 4c8bec36 and
resolving the v3.1-dev merge, the Swift layer had 18 compile errors
against the refreshed C ABI. Fixes them plus a handful of related
drift items that only surfaced once the first batch cleared.
**Umbrella header / module map (packages/swift-sdk/build_ios.sh)**
- dash-network.h comes first (defines FFINetwork referenced by everyone).
- dashcore/dashcore.h excluded via `exclude header` — it duplicates
FFINetwork with dash-network.h and triggers typedef-redefinition
(dash-network was extracted as a standalone crate upstream).
- platform-wallet-ffi headers stay excluded: Swift uses @_silgen_name
shims in PlatformWalletFFI.swift as the source of truth.
**@_silgen_name shim realignment (PlatformWalletFFI.swift)**
- platform_wallet_info_create_from_{seed,mnemonic}: added `network: u32`
first arg (see sibling commit making the Rust side C-ABI clean).
- platform_wallet_info_{get,set}_identity_manager: dropped network arg.
- contact_request_create: added missing `core_height_created_at: u32`.
- managed_identity_send/accept_contact_request: reduced to
(identity_handle, request_handle, out_error).
- platform_wallet_bytes_free: added `len` param.
- *_destroy shims (contact_request, established_contact, identity_manager,
managed_identity, platform_wallet_info): return PlatformWalletFFIResult
now, not Void.
**Swift call-site adjustments**
- ContactRequest.swift / IdentityManager.swift: Int for usize-typed lens.
- ManagedIdentity.swift: dropped UInt wrapper; renamed stale
PlatformBlockTime references to BlockTime / FFIBlockTime.
- ManagedPlatformWallet.swift: let ffiInputs (never-mutated).
- PlatformWallet.swift: drop UInt(seed.count) wrapper.
**KeyWalletTypes.swift**
- Deleted the duplicate public `enum TransactionContext: UInt32` that
collided with the `TransactionContext` class in TransactionContext.swift.
- TransactionContextDetails.context now typed as TransactionContextType.
- Transaction.swift / ManagedWallet.swift: follow the rename in their
default arg types.
**Swift 6.2 compat (ConcurrencyCompat.swift)**
- Swift 6.2 stdlib restates OpaquePointer's Sendable conformance as
`@available(*, unavailable)`, which makes our retroactive
`extension OpaquePointer: @unchecked Sendable` trip
"already stated in type's module 'Swift'" under -warnings-as-errors,
while simultaneously blocking bare-OpaquePointer round-trips through
concurrency boundaries.
- Gate the retroactive shim behind `#if compiler(<6.2)` and add a
SendableOpaquePointer wrapper for 6.2 call sites.
- TransitionDetailView.swift: all 14 `try await MainActor.run { ... } ->
OpaquePointer` sites now wrap/unwrap SendableOpaquePointer.
**Dead-code cleanup**
- Deleted AddAccountView.swift — referenced the already-removed
WalletService / HDWallet types (commit 6ee01f9), only surviving
because the Xcode project uses PBXFileSystemSynchronizedRootGroup.
- ReceiveAddressView.swift: unifiedAppState.platformState → platformState
(UnifiedAppState removed in the iOS SDK refactor).
**Rust side (packages/rs-platform-wallet-ffi/)**
- Dropped the earlier build.rs + cbindgen build-dep: now that Swift is
not consuming the generated header, the cbindgen emit is dead work.
- Kept the earlier Network-by-value → u32 signature fix on the two
entry points (independently correct; matches rest of the crate).
Verification:
- `bash packages/swift-sdk/build_ios.sh --target sim --profile dev` → clean
- `cargo clippy --workspace --all-features --locked --all-targets --
--no-deps -D warnings` → 0 errors
- `cargo machete` → no unused deps
Pushed by sibling commits; this one closes the loop on CI red.
CI runs xcodebuild with -swift-version 6, which enforces strict Sendable checks. CreatedIdentity is returned across a Task boundary in CreateIdentityView.swift:411, so it must cross the isolation boundary — failing under Swift 6 with: error: non-sendable result type 'ManagedPlatformWallet.CreatedIdentity' cannot be sent from nonisolated context Its only stored property is a ManagedIdentity, which is already @unchecked Sendable. Marking the wrapping struct Sendable is safe and matches the pattern used elsewhere in the SDK. My local Xcode 26 / iOS 26.2 SDK didn't surface this — the CI runner is on iOS 18.5 SDK with stricter Swift 6 enforcement.
|
✅ DashSDKFFI.xcframework built for this PR.
SwiftPM (host the zip at a stable URL, then use): .binaryTarget(
name: "DashSDKFFI",
url: "https://your.cdn.example/DashSDKFFI.xcframework.zip",
checksum: "90e4733bfa73139bf4c05cc75c5fa10a0fb772de32ac23ab5cf4c5e59c181bd4"
)Xcode manual integration:
|
|
Merging this in as a merge commit so we have a basis to go on. |
Issue being fixed or feature implemented
Introduces
rs-platform-wallet+rs-platform-wallet-ffi— a wallet-centricidentity/DashPay/DPNS backend — and rewires the iOS SDK and SwiftExampleApp
onto it, replacing the old
HDWallet/IdentityModel/ContractModel/DocumentModel/TokenModellayer with SwiftData-backedPersistent*rowsdriven entirely by Rust-side changeset callbacks.
What was done?
rs-platform-wallet(new crate)register_from_addresses, top-up, transfer, keymanagement (split out of
IdentityEntry), balance persistence.DashPayWalletintoIdentityWallet<B>; profileread/edit, contacts, payments.
TransactionBroadcasterleaf type; typedPlatformWalletPersistenceerrors; layered identity/ module split.
rs-platform-wallet-ffi(new crate)payment surface, DPNS, identity+key changeset forwarding to Swift.
derivation; nonce auto-fetch moved into
rs-sdk.round; identity registration runs on 8 MB-stack worker.
swift-sdk(iOS SDK)PlatformWalletManagerholds N wallets; persistence handler drivesSwiftData from Rust callbacks.
registerIdentityFromAddresseswrapper; identity keys stored viaderivation breadcrumb (client-side re-derivation, no seed export).
PersistentIdentity/PlatformAddress/PublicKey/Transactionwith compound indices; legacyIdentityModel/
ContractModel/DocumentModel/HDWalletmodels deleted.org.dashfoundation.wallet.SwiftExampleAppSettings.
amount, identity-registration-index pickers.
FriendsView wired to platform-wallet.
migrated to
PersistentIdentity.How Has This Been Tested?
cargo test -p rs-platform-wallet/-p rs-platform-wallet-ffiagainst testnet: create wallet → receive DASH → fund Platform Payment
account → Create Identity → DPNS register → DashPay profile → send
DashPay payment → contested-name vote.
packages/swift-sdk/build_ios.sh.Breaking Changes
rs-platform-wallet,rs-platform-wallet-ffi.HDWallet,HDWalletModels,IdentityModel,ContractModel,DocumentModel,TokenModel. Consumers must migrateto
Persistent*SwiftData rows.PersistentIdentity.walletIddenormalization dropped in favor of thePersistentWalletrelationship.org.dashfoundation.wallet;legacy seed/PIN/mnemonic entries removed.
Checklist: