Repository navigation
feat(swift-example-app): update a data contract from its detail screen, with a Rust preview of the changes - #6053
Conversation
Add IdentityWallet::preview_data_contract_update and its FFI binding platform_wallet_preview_data_contract_update. The preview fetches the live contract, checks the owner, merges the supplied sections and builds the updated contract through the same helper the update now uses, then reports the document types, tokens and groups added or changed, whether keywords, description or config change, and the version step. It signs nothing, broadcasts nothing and uses no nonce. It says what changes, not whether Platform accepts the update: the network decides that at broadcast. The FFI writes the preview as JSON, released with platform_wallet_string_free. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Parsing a stored contract a second time inserted a second token, document type, index and property row under each existing unique id, which SwiftData resolves as an upsert with undocumented handling of relationships, so token balances, token history and a type's documents could detach. The parser now copies the parsed definition onto the stored row with the same id and links it again, inserts only new rows, and removes an index or property a type no longer declares. A first parse behaves as before. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Bridge platform_wallet_preview_data_contract_update and decode its JSON into DataContractUpdatePreview. hasChanges is read as Rust writes it. Correct the updateDataContract doc comment: the supplied sections are merged key by key onto the live contract. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Contracts -> contract -> Update Contract, offered when a local identity owns the contract. The screen takes the new sections by paste, file import or editing, reviews them through previewDataContractUpdate, and offers the update only when the review reports a change. It signs with KeychainSigner, broadcasts through updateDataContract, shows Platform's consensus error text and code on a refusal, and refreshes the stored contract afterwards (ContractDownloader.refreshPersistedContract). No contract update rule is checked in Swift. TEST_PLAN DC-04 moves from builder-only to production UI; the parity manifest tracks the preview as contracts.update_preview. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 9 minutes. View limit details
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. |
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
|
⏹️ Not reviewed — PR is closed (merged) (commit 9874294) |
thepastaclaw
left a comment
There was a problem hiding this comment.
Preliminary review — Phase 1 blocker gate
The shared Rust draft builder keeps preview and submit aligned when the contract has not changed, but submit can silently rebuild against a newer version, a failed confirmation can leave the paid action retryable, and refreshing a contract can overwrite a token’s persisted pause status. Kotlin build and tests and the Swift frozen-schema check passed; Rust workspace tests are pending, and the author reports that the Swift tests and device flow have not run.
Validated blockers were found by the Phase-1 review and confirmed by a fresh verifier. Phase 2 is deferred until a fresh same-head revalidation clears the blocker gate.
🔴 3 blocking | 🟡 5 suggestion(s) | 💬 2 nitpick(s)
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🟡 Suggestion: Exercise the public preview against a mock contract fetch
packages/rs-platform-wallet/src/wallet/identity/network/contract.rs:541-586
The new Rust tests cover merge, comparison and JSON output, but none calls preview_data_contract_update or exercises the shared fetch, owner check and version handling. The SDK already demonstrates a contract fixture through sdk.mock().expect_fetch in tests/fetch/mock_fetch.rs. Use that pattern to verify an unchanged draft through the public preview method and to cover the wrong-owner and missing-contract errors.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-gate-verifier, role: verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — The shared Rust update builder, new Swift UI, and in-place refresh of local contract data make this a substantial cross-layer change, but the diff does not change consensus, signing or key handling, or the storage schema. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Fresh verifier:
gpt-6.2-sol— verifier; agentsol-gate-verifier - Phase 2 reviewers: not run (deferred by blocker gate)
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/swift-sdk/Sources/SwiftDashSDK/Core/Utils/DataContractParser.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/Core/Utils/DataContractParser.swift:198-205: Contract refresh resets a token’s live pause status
The refresh copies `parsed.isPaused` onto the stored token, but the parser initializes that value from the contract’s `startAsPaused` flag, not the token’s current status. Drive stores live status separately, and `TokenPauseActionView` persists `isPaused = true` after a successful pause. Updating an unrelated document type on a contract whose token started unpaused therefore saves `false` over that known paused state without resuming the token on-chain. Preserve the stored live status on a definition-only refresh unless it can be replaced with a verified status, and test a reparse where the stored status differs from `startAsPaused`.
In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift:378-398: Bind submit to the contract version the user reviewed
Matching the editor inputs does not bind submit to the reviewed contract. The Swift call sends the reviewed text but not `review.preview.currentVersion`, and the Rust wallet fetches the contract again and builds on whatever version it finds. If another session changes the description after review, submit can overwrite that newer description; if another session already applied the reviewed description, submit can broadcast a version-only update. Pass the reviewed base version into a Rust submit path and compare it with the contract used to build the transition, before fetching a nonce. On mismatch, require a fresh review.
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift:412-427: Clear the review when confirmation fails after broadcast
The no-retry branch catches `.transactionBroadcastUnconfirmed`, but `update_data_contract_with_signer` calls `broadcast` and `DataContract::wait_for_response` separately and returns a wait error unchanged as `PlatformWalletError::Sdk`. For example, if the node acknowledges broadcast but the wait request later fails at the transport layer, the error lacks the SDK’s unconfirmed marker that the FFI checks. Swift takes the generic catch, retains the review, and re-enables Update Contract even though the first update may already have executed. Use the SDK’s submission-phase handling on the Rust update path, preserving the affected-state wait for contract updates, and test that an acknowledged broadcast followed by a failed wait reaches the unconfirmed branch.
- [SUGGESTION] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift:165-183: Tell users that existing tokens and groups cannot be edited here
The footers say tokens and groups are merged the same way as document types, whose footer explicitly says existing entries are replaced. The review then labels replacements as ordinary changes and enables the paid submit action. The preview intentionally describes a draft rather than validating it, but DPP’s `validate_update_tokens` and `validate_update_groups` reject replacements at existing positions. Say that this transition can add tokens and groups but cannot change existing ones, and clarify that the review is not network validation. Keep the validation rule in Rust rather than duplicating it in Swift.
- [NITPICK] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift:529-534: Hide the configuration row on a screen that cannot edit it
The form has no configuration input, and both wallet calls omit `contractConfigJSON`. The Configuration row thus presents a status for an input the user cannot change. Keep the field in the SDK preview, but omit this row from the screen until it supports configuration edits.
In `packages/rs-platform-wallet/src/wallet/identity/network/contract.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/contract.rs:541-586: Exercise the public preview against a mock contract fetch
The new Rust tests cover merge, comparison and JSON output, but none calls `preview_data_contract_update` or exercises the shared fetch, owner check and version handling. The SDK already demonstrates a contract fixture through `sdk.mock().expect_fetch` in `tests/fetch/mock_fetch.rs`. Use that pattern to verify an unchanged draft through the public preview method and to cover the wrong-owner and missing-contract errors.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/contract.rs:768-784: Keep the contract source in serialization diagnostics
The refactor removes `existing` from both diagnostics emitted while converting and serializing the fetched contract, despite the PR’s stated preservation of update error text. It also uses those same generic messages when serializing the rebuilt draft for preview, so the error no longer identifies which side failed. Label the two call sites as `existing` and `updated` to preserve the previous update diagnostics and distinguish preview failures.
In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/RegisterContractSourceView.swift`:
- [SUGGESTION] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/RegisterContractSourceView.swift:600-636: Test the groups input shapes accepted by the update screen
`positionKeyedGroupsJSON` is called by the update screen but not by the existing clipboard classifier tests. Add tests for blank input, a position-keyed map, and an imported array whose numeric or string `id` is removed and used as the map key. Cover reachable malformed inputs such as missing or unsupported IDs, duplicate positions, and an invalid top-level shape. Non-UTF-8 file bytes are rejected before they reach this Swift `String` helper.
In `packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DataContractParserRefreshTests.swift`:
- [SUGGESTION] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DataContractParserRefreshTests.swift:140-168: Cover deletion of a stale index on reparse
The deletion test reparses a document type without its old `body` property, but both versions still declare `byMessage`. That leaves the separate index-deletion branch untested. Extend the parser fixture to omit an index on reparse and assert its stored row is gone; the fixture need not represent a network-valid update.
In `packages/rs-platform-wallet-ffi/src/data_contract.rs`:
- [NITPICK] packages/rs-platform-wallet-ffi/src/data_contract.rs:187-190: Spell out the optional C-string safety requirement
The optional arguments are documented as “null or one.” Name the non-null alternative explicitly so callers can see the same NUL-termination and UTF-8 requirements apply to those arguments.
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
…and report an unconfirmed result update_data_contract_with_signer takes expected_current_version: when set and the live contract is at another version, the update is refused before any nonce is read, so it is never built on a contract the caller did not review. The FFI takes it as a u32, 0 meaning no check (contract versions start at 1); the Kotlin JNI caller passes 0. The update now broadcasts and waits through the SDK's broadcast_and_wait_for_affected_state, so a wait that fails after the transition may have been accepted is StateTransitionResultUnconfirmed (FFI code 20) instead of a plain SDK error. Format conversion errors name the existing or updated contract. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ubmit only the reviewed contract - A contract refresh no longer copies isPaused onto a stored token: the parser seeds it from startAsPaused, the stored value is live status. - updateDataContract takes expectedCurrentVersion; the update screen passes the reviewed version and clears the review on any failed submit. - Footers say an update can add tokens and groups but Platform refuses a change to an existing one, and that the review is not Platform's verdict. The configuration row, which the screen cannot edit, is gone. - Tests: paused status kept and a dropped index removed on re-parse; positionKeyedGroupsJSON input shapes and errors. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The reviewed-update path still breaks the released C ABI, can authorize a second paid submission while the first is unresolved, and can save stale or corrupted contract data locally. The update importer and Swift-to-C boundary can also change what the owner submits. Kotlin emulator CI passed; review gates are pending, no Swift runtime result is available for DC-04, and nine lower-priority findings were left off the inline review.
🔴 8 blocking | 🟡 2 suggestion(s)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); reviewer 8: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 9: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 10: gpt-6.2-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 11: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 12: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — The diff adds a cross-language preview and submission flow and changes how the app refreshes existing records, but it does not change signing rules, consensus, funds movement, or the persisted schema. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Second Phase-2 pass: on this first full review every Phase-2 reviewer also ran a second, independent time, and the verifier weighed both sets
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— security-auditor (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-platform-wallet-ffi/src/data_contract.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/data_contract.rs:105-120: Preserve the released contract-update C ABI
The `v5.0.2` export takes `signer_handle` and `out_contract_id` immediately after `config_json`. This head inserts a `u32` under the same unmangled symbol. A caller built against the released declaration can still link against the replacement library, but Rust then reads the caller's output buffer as the signer and reads an output argument the caller never supplied. The null checks do not make either pointer valid. Keep the original C signature as a forwarding entry point and add a distinct export for reviewed updates. Preserve the original public Rust method as a forwarder too: it now requires an extra argument despite the PR describing the change as additive.
In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Utils/ContractDownloader.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Utils/ContractDownloader.swift:402-438: Do not persist a contract older than the verified update
The affected-state wait verifies the expected contract version and body, but the wallet FFI returns only its ID. The follow-up fetch checks that ID and then overwrites the stored JSON, binary and parsed definitions. `GetDataContract` uses the SDK's default one-block freshness tolerance, so even a client that saw the update at height H can accept a valid proof of the old contract at H−1. The app can mark an old schema as freshly synced or downgrade a newer local row; the trusted context's no-downgrade check does not protect SwiftData. Carry the verified snapshot through the reviewed-update API, or enforce the verified version as a floor on the re-fetch. In either case, reject a snapshot older than the stored version before writing it, including on the unconfirmed path.
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Utils/ContractDownloader.swift:430-447: Keep contract refresh rollback out of the shared SwiftData context
The view passes the app's environment context, which is `modelContainer.mainContext`. If a parser fetch or the save throws, `rollback()` discards every unsaved change in that context, including changes that were already pending before the refresh. It does not just restore the contract. Fetch and update the contract in an isolated context, and cover a refresh failure while an unrelated edit remains pending in the main context.
- [SUGGESTION] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Utils/ContractDownloader.swift:431-439: Refresh the stored metadata and token-presence fields
Replacing `serializedContract` and reparsing updates the version and token rows, but does not update `contractDescription`, `keywordRelations` or `hasTokens`. The storage detail screen reads those projections, and SwiftData's keyword and token filters use them directly. After a metadata change or the addition of the first token, the new version can still display old metadata or be omitted from the relevant filter. Refresh the projections from the same verified payload and cover metadata-only updates and the first token addition.
In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift:417-428: Do not authorize a replacement while the first update is unresolved
The unconfirmed branch clears the review but invites another one, and `canSubmit` has no unresolved-submission guard. If the first broadcast is still pending, both the refresh and a new preview can legitimately show version N. The next submit can then pass the version guard and sign a distinct transition for N+1 with another identity-contract nonce. If the first lands before the second executes, Drive-ABCI can reject the second through the paid version-refusal path. Keep the original attempt separate from the editable review and have the wallet reconcile it before allowing a replacement. A snapshot that still shows N is not evidence of failure.
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift:326-339: Import update input without rewriting or dropping supplied sections
The registration adapter does not round-trip update input. It joins keywords with commas and `WalletArguments` splits them again, so a valid stored keyword `alpha,beta` becomes two keywords; trimming an imported description likewise removes spaces that DPP permits. Pasting an unchanged export can therefore enable a paid update. The same classifier drops a malformed group such as `groups: {"0": null}` when a valid document section is present, yet rejects valid files containing only group or metadata updates. Parse imports as updates: preserve structured values and verbatim descriptions, pass supplied malformed sections through for rejection or show an import error, and accept supported standalone sections. Test that importing an unchanged export leaves submit disabled.
In `packages/swift-sdk/Sources/SwiftDashSDK/Core/Utils/DataContractParser.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/Core/Utils/DataContractParser.swift:676-683: Do not reuse definition rows across document types
`PersistentProperty` encodes its unique ID as contract bytes followed by the type and property names with no boundary. In one contract, `note.title` and `notet.itle` therefore have the same ID. Adding the second type makes the new ID-only lookup reuse the first type's row, overwrite its definition and reparent it without changing its stored names. The new index upsert has the same problem. Give both models unambiguous composite keys, handle existing stored keys, and test that both definitions keep their own parent on reparse. Until collision-safe keys are available, refuse mismatched rows rather than reparenting them.
In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/RegisterContractSourceView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/RegisterContractSourceView.swift:606-629: Resolve duplicate group positions in the Rust update input parser
The Swift array adapter checks string keys, so IDs `0` and `"00"` both survive; the map branch bypasses that check. The wallet merges the string keys, then DPP parses both as the same `GroupContractPosition` and collects them into one entry. One definition can silently disappear before the review, even if the two specify different members or thresholds. Swift can adapt the editor shape, but it should not decide position identity. Normalize and reject duplicate typed positions in the shared Rust wallet input path before merging, regardless of input shape, without changing the consensus deserializer.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:4722-4727: Reject embedded NULs before marshalling contract text
Both Swift wrappers use `withCString`, and the Rust receiver reads only up to the first NUL. A JSON description such as `"Draft\u0000 final"` becomes a Swift string containing U+0000, so preview and submit both send only `Draft`. The review reports that the description changed without showing the value, and an owner can pay to persist the truncated text. Reject embedded NULs in both wrappers at the marshalling boundary, as the JNI bridge does, or use length-delimited UTF-8.
In `packages/rs-platform-wallet/src/wallet/identity/network/contract.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/contract.rs:525-555: Exercise the public preview against a mock contract fetch
The rebuild test calls the merge and diff helpers directly, so it cannot catch the public preview fetching the wrong contract, forwarding the wrong inputs or skipping the ownership check. The wallet already enables SDK mocks for tests, and `document_erase.rs` demonstrates registering a contract with `expect_fetch`. Call `preview_data_contract_update` with a successful draft and an owner mismatch, with only the contract fetch configured so that neither case can silently acquire a nonce or submit a transition.
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Keep the fetch result's contract handle owned until serialization succeeds — The unchanged
dash_sdk_data_contract_fetch_with_serializationexport converts a boxed clone into a raw handle before converting to JSON. If that conversion fails, the error-only result does not carry the handle, so the normal result free cannot reclaim it. The new app flow reuses the export but did not introduce the ownership bug.- Follow-up: Fix the shared SDK FFI export in a separate PR by retaining Rust ownership until the fallible output conversions have succeeded.
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
…ion in a contract update The contract parser reads a tokens or groups key as a u16 position, so "0" and "00" named one entry and one definition was dropped without a word. The update and preview now re-key supplied tokens and groups to canonical positions and refuse a key that is not a position or two keys naming one. Add mock-SDK tests of preview_data_contract_update: a preview of the fetched contract, and an owner mismatch refused with only the contract fetch answered. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… hold after an unconfirmed update - The refresh refuses a fetched contract older than the stored one or the version the confirmed update reached, works in its own ModelContext instead of rolling back the shared one, and refreshes the description, keywords and hasTokens projections. - The parser does not reuse a property or index row found by an id that belongs to another definition (ids have no separator between type and member names); it skips it instead of reparenting it. - previewDataContractUpdate and updateDataContract refuse a string with an embedded NUL instead of sending it truncated. - The update screen imports with its own parser, which keeps every supplied section, keyword and description as given, and accepts keywords as a JSON array. - After an unconfirmed update the screen offers no other update. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Preliminary review — Phase 1 blocker gate
The new refresh path rejects older snapshots and isolates its SwiftData writes from pending edits in the caller’s context. The new importer still rejects the app’s own exports when a contract has no description, and the new submission hold is lost when the user reopens the update screen. The Kotlin SDK build and emulator tests passed; PR Hygiene and the review check were pending, and no Swift runtime validation was reported.
Validated blockers were found by the Phase-1 review and confirmed by a fresh verifier. Phase 2 is deferred until a fresh same-head revalidation clears the blocker gate.
🔴 2 blocking
Still open from earlier rounds (1)
- 🔴 Blocking: Do not authorize a replacement while the first update is unresolved —
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift:439-452(thread)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-gate-verifier, role: verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — The change is substantial and cross-layer, but it adds a version-bound contract preview and submission flow plus local model refresh logic without changing consensus, funds movement, signing or key handling, or the persisted schema. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Fresh verifier:
gpt-6.2-sol— verifier; agentsol-gate-verifier - Phase 2 reviewers: not run (deferred by blocker gate)
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractImport.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractImport.swift:108-113: Import update input without rewriting or dropping supplied sections
The new importer preserves comma-containing keywords and padded descriptions, but it rejects an export of any V1 contract without a description. `DataContractDetailsView.exportContract` writes the exact JSON from `dash_sdk_data_contract_fetch_with_serialization`, which serializes `DataContractInSerializationFormatV1.description: Option<String>` without skipping `None`. That produces `"description": null`, which reaches this branch as `NSNull` and fails the string cast. An owner cannot import that export to review or change its schema. Treat the serialized null as an absent description, keep rejecting other non-string values, and add an export fixture with `"description": null`. The current fixture supplies a non-null description, so it misses this path.
In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/UpdateContractView.swift:439-452: Do not authorize a replacement while the first update is unresolved
(carried; thread: https://github.com/dashpay/platform/pull/6053#discussion_r4658027030)
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Reject embedded NULs in the Swift contract-create wrapper —
createDataContractstill marshals its description through a C string, so a caller supplying an embedded NUL can pay to register a truncated description. That create path predates this PR and is not used by the new update flow.- Follow-up: In a separate PR, reuse the SDK’s NUL guard for the create arguments and add regression coverage.
…iption An export writes "description": null when the contract has none (the serialization format does not skip the empty optional), and the update importer refused it as a non-string. Null now means no description: the field stays empty and the live value is kept. Other non-string values are still refused. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
… schema member order - split_contract_update_source (and the FFI export platform_wallet_split_contract_update_source) splits pasted or imported contract JSON into the update's sections, each as JSON text in source order. Protocol version 15 refuses a reordering of a stored object's members, and a host JSON reader that sorts keys would cause one. The rules are those the Swift importer had. - The preview compares document types as text, member order included: serde_json::Value equality ignores member order, so a reordered schema read as unchanged. - A malformed position key is debug-formatted in its error, so a NUL in it no longer blanks the message across the C boundary. - New test: moderator appointments reported through the public preview against a fetched contract. - platform-wallet declares serde_json's preserve_order itself. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…review when a new one starts - The update screen's import calls DataContractUpdateSource.split (the new FFI export) instead of re-serializing sections with JSONSerialization and sorted keys, so nested schema members keep their order. The Swift parsing helpers and their tests are gone; the rules are tested in Rust. - Starting Review Changes clears the previous review and its acknowledgment, so a failed re-review cannot leave them active. - The moderator rows read "Moderator appointments added/removed", with a caption that the contract owner may always moderate. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Your move: thepastaclaw left review threads unresolved; resolve them. |
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
|
Re the round-10 review at
|
Resolve the parity manifest and its generated summary: keep v5.1-dev's entries and add this branch's contracts.update_preview capability and its two shared symbols, then regenerate PARITY_SUMMARY.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
Regenerate PARITY_SUMMARY.md from the merged parity manifest. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
Resolve the TEST_PLAN "Entry-point reality check" paragraph: keep this branch's wording for data-contract create and update, and v5.1-dev's for the identity key-limits update (ID-17). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
Regenerate PARITY_SUMMARY.md from the merged parity manifest. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
Basic explanation
What this does: The iOS example app gets its own screen for changing a data contract you own. Before, you could only do this from a generic developer form under Settings. Open the contract, tap Update Contract, then paste or import the new schema (or edit it). Review Changes lists exactly what would change, and Update Contract signs and sends it. The review comes from a new Rust wallet call that builds the updated contract the same way the real update does, without sending anything.
Value: Contract owners can now update a contract from the normal app flow. They see what would change before paying, and an update that changes nothing is never offered. Afterwards the app's stored copy of the contract is refreshed. The Swift code checks no contract update rule itself: Platform decides at broadcast, and its refusal text and consensus code are shown as returned.
Risks: Low for the network: no consensus, protocol or state-transition change. The existing update path in
rs-platform-walletwas split into a shared "fetch and build" helper that both the update and the preview call. The update's behaviour is meant to be unchanged, and the module's existing tests pass. Medium for the app: the contract parser now updates stored token, document type, index and property rows in place when a contract is parsed again (it used to insert a second row under each id). That change and its tests compile but have not run: no real iOS library was available on this machine. The new screen has also not been driven on a simulator or device (TEST_PLAN DC-04 is still to run). Two smaller app risks: the refresh writes through its own SwiftData context, and the app records a case where such writes reach the main context's views late (the new test checks the merge but hasn't run). The hold after an unconfirmed update lasts only while the screen is open.Issue being fixed or feature implemented
SwiftExampleApp could only update a data contract through the Settings transition builder (TEST_PLAN row DC-04, marked builder-only). The Kotlin app already has a dedicated
UpdateContractScreen. No open PR or issue covered an iOS screen. Related open PRs that touch the same wallet code: #5961 (which key signs a contract create or update), #4776 (clearing the description through the FFI) and #4730 (delta contract updates, parked for 5.2). This PR doesn't overlap their changes, butcontract.rsmay need a rebase against #5961.What was done?
Rust (
rs-platform-wallet,rs-platform-wallet-ffi)IdentityWallet::preview_data_contract_update(...)takes the same arguments asupdate_data_contract_with_signer, minus the signer. It fetches the live contract and checks that the identity owns it. It then merges the sections and builds the updated contract through a new private helper,draft_data_contract_update, which the update now calls too. Finally it compares the two contracts in their serialization-format JSON. It doesn't sign, doesn't broadcast and uses no nonce.platform_wallet_preview_data_contract_updatereturns the preview as JSON. The caller frees it withplatform_wallet_string_free.split_contract_update_source(FFIplatform_wallet_split_contract_update_source) splits pasted or imported contract JSON into the update's sections, each as JSON text in source order. A host JSON reader that sorts keys would reorder schema members, which protocol version 15 refuses.tokensandgroupsby canonicalu16position, refusing a key that isn't a position and two keys naming one position ("0"and"00").Swift SDK
ManagedPlatformWallet.previewDataContractUpdate(...)and a newDataContractUpdatePreviewtype.hasChangesis read exactly as Rust writes it.DataContractParser: when a contract is parsed again, each stored definition row (token, document type, index, property) gets the new values in place. Only new rows are inserted, and an index or property the type no longer declares is removed. Documents, token balances, token history and a token's paused status stay as stored. A property or index row whose id belongs to another definition (the ids have no separator between type and member name) is skipped, not reparented.Example app
DataContractDetailsViewhas an Update Contract action (contractDetails.updateContract). It is shown only when a local identity owns the contract and the screen isn't a preview.UpdateContractView:config) is sent ascontractConfigJSON. The review names the configuration members and moderators that change, and signing a configuration change needs an explicit acknowledgment.ContractDownloader.refreshPersistedContractre-fetches a stored contract, re-registers it in the SDK trusted context and re-parses it, in its ownModelContext. It refuses a fetched contract older than the stored one or than the version the confirmed update reached, and refreshes the description, keywords andhasTokens. The existing download functions now share one fetch helper.PasteboardContractCandidate.positionKeyedGroupsJSONturns either groups shape into the map the wallet expects.TransitionDetailViewis untouched.Docs
contracts.update_preview: Swift SDKsupported, Swift apppartial(not yet driven), Kotlinunsupported.PARITY_SUMMARY.mdwas regenerated by the script.Example
The live contract has a document type
note. The owner pastes:{ "documents": { "note": { "type": "object", "properties": { "message": { "type": "string", "position": 0, "maxLength": 63 }, "title": { "type": "string", "position": 1, "maxLength": 63 } }, "additionalProperties": false }, "comment": { "type": "object", "properties": { "text": { "type": "string", "position": 0, "maxLength": 63 } }, "additionalProperties": false } } }Before: the only path was Settings -> Platform State Transitions -> Update Contract, which broadcasts straight away and shows nothing about what changes.
After: Contracts -> the contract -> Update Contract -> Paste from Clipboard -> Review Changes shows:
Pasting the live schema back unchanged reviews as "No changes", and Update Contract stays disabled.
Public interface changes
platform-wallet(new, additive; existing callers compile unchanged)update_data_contract_with_signerchanges signature: a newexpected_current_version: Option<u32>sits betweenconfig_jsonandsigner.Callers outside the crate must add the argument;
Nonekeeps today's behaviour. The only in-repo caller is the FFI below. WithSome(v), an update of a contract now at another version is refused (InvalidIdentityData, "is at version X, not the reviewed version v; review the update again") right after the fetch, before any nonce is read. Internally the update builds the contract through the shared helper, with the same checks in the same order (owner before any nonce read). It now broadcasts and waits through the SDK'sbroadcast_and_wait_for_affected_state. A wait that fails after the transition may have been accepted therefore returnsSdk(StateTransitionResultUnconfirmed)(FFI code 20, "may have executed"); before, it returned the plain SDK error. Format conversion errors name theexistingorupdatedcontract.platform-wallet-ffi(two new C symbols, one changed)platform_wallet_update_data_contract_with_signergainsuint32_t expected_current_versionbetweenconfig_jsonandsigner_handle.0means no check (contract versions start atINITIAL_DATA_CONTRACT_VERSION= 1); any other value is the reviewed version. C callers must add the argument. The Kotlin JNI caller (rs-unified-sdk-jni) passes0, so no Kotlin or JNI descriptor change is needed.The preview JSON it writes:
{"currentVersion","newVersion","hasChanges","documentTypes":{"added","changed"},"tokens":{...},"groups":{...},"keywordsChanged","descriptionChanged","configChanged","configChangedFields":[...],"moderatorsAdded":[...],"moderatorsRemoved":[...]}. A reordering of unchanged indexes doesn't count as a change. Token and group keys are decimal position strings. Not bridged to Kotlin/JNI yet.SwiftDashSDK(additive)ManagedPlatformWallet.previewDataContractUpdate(ownerIdentityId:contractId:documentSchemasJSON:tokenSchemasJSON:groupsJSON:keywordsJSON:description:contractConfigJSON:) async throws -> DataContractUpdatePreviewpublic struct DataContractUpdateSource(split(_:),decode(fromJSON:)), the splitter's result.public struct DataContractUpdatePreviewwith nestedSectionChanges,configChangedFields,moderatorsAdded,moderatorsRemoved, andstatic func decode(fromJSON:).previewDataContractUpdateandupdateDataContractthrowinvalidParameterfor an owner or contract id that is not 32 bytes, or a string argument containing NUL.ManagedPlatformWallet.updateDataContract(...)gainsexpectedCurrentVersion: UInt32? = nilaftercontractConfigJSON. It defaults tonil, so existing callers (the transition builder) compile unchanged.DataContractParser.parseDataContractkeeps its signature. Its behaviour changes on a second parse of the same contract: stored rows are updated in place instead of a second row being inserted under each id. A token'sisPausedis not overwritten: it is live status, and the contract only carriesstartAsPaused.How Has This Been Tested?
cargo test -p platform-wallet --lib wallet::identity::network::contract: 14 passed. Four of them are new preview tests, one of which round-trips through the contract parser to check that untouched sections compare equal.cargo test -p platform-wallet-ffi --lib data_contract: 3 passed (2 new: the JSON shape, andhasChangestaken from Rust).cargo clippy -p platform-wallet -p platform-wallet-ffi --all-features --all-targets -- -D warnings: clean.cargo fmt --all -- --check: clean.python3 scripts/check_sdk_parity_manifest.py: OK, summary current.DashSDKFFI.xcframeworkwas available, and a fullbuild_ios.shwas avoided. Instead the fresh cbindgen headers were put into a stub xcframework laid out likebuild_ios.shbuilds it, with an empty static library.xcodebuildof SwiftExampleApp for the simulator compiled every Swift file ofSwiftDashSDKandSwiftExampleApp, and failed only at the final link with undefined symbols, as expected with the stub.build-for-testingofSwiftDashSDKcompiled both new test files and failed only at linking the test bundles.cargo check -p platform-wallet-ffi -p rs-unified-sdk-jniandcargo clippy -p rs-unified-sdk-jni -- -D warnings. The unconfirmed mapping is pinned by the existingshould_preserve_unconfirmed_sdk_submission_through_wallet_ffi. The same stub-framework compile check covered the app, theSwiftDashSDKtests and theSwiftExampleAppTeststarget: every Swift file compiled, and only the links failed.cargo test -p platform-wallet --lib wallet::identity::network::contract: 19 passed, including mock-SDK tests ofpreview_data_contract_update(success, and an owner mismatch with only the contract fetch answered). Clippy is clean. The stub-framework compile check again compiled every Swift file of the app, the app tests and theSwiftDashSDKtests.cargo test -p platform-wallet --lib wallet::identity::network::contract24 passed (stale review refused through the public update, verified by a mutation check; index reordering; configuration and moderator changes),cargo test -p platform-wallet-ffi --lib data_contract4 passed (output cleared on early error), clippy with CI's flags clean. The Swift SDK, app and their tests compile against a stub framework after each round.cargo test -p platform-wallet --lib wallet::identity::network::contract34 passed, including the 8 splitter tests incontract_update_source.rs(source member order kept byte for byte), a member reorder counting as a change, and moderator appointments through the public preview.cargo test -p platform-wallet-ffi --lib data_contract6 passed (the splitter export returns sections in source order and leaves its output null on error). Clippy with CI's flags is clean. The Swift compile check caught and fixed one real error: a bareStringresolving to a C enum constant from the FFI header.ContractRefreshApplyTests,UpdateContractImportTests,DataContractUpdatePreviewDecodingTests,DataContractParserRefreshTests, the newpositionKeyedGroupsJSONtests inPasteboardContractCandidateTests) and the end-to-end flow (TEST_PLAN DC-04) on a simulator or device. Both need a realbuild_ios.shframework.Breaking Changes
No consensus or protocol change, so no
!. Two client interfaces change signature:IdentityWallet::update_data_contract_with_signer(newexpected_current_versionargument) and the C functionplatform_wallet_update_data_contract_with_signer(newexpected_current_version). Both are listed under Public interface changes. Every in-repo caller is updated, and the Swift wrapper defaults the new argument.Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull requestFor repository code-owners and collaborators only
🤖 Generated with Claude Code
PR Hygiene ·
3a6f65f/skip-botsproceeds without the ones not yet reported/self-reviewedsdk-parity— you own itkotlin-sdk(packages/kotlin-sdk/PARITY_SUMMARY.md,packages/rs-unified-sdk-jni/src/identity.rs) — HashEngineeringrs-platform-wallet-ffi(packages/rs-platform-wallet-ffi/src/data_contract.rs) — HashEngineering or ZocoLini or llbartekll or romchornyirs-platform-wallet(packages/rs-platform-wallet/Cargo.toml,packages/rs-platform-wallet/src/wallet/identity/network/contract.rs,packages/rs-platform-wallet/src/wallet/identity/network/contract_update_source.rsand 1 more) — HashEngineering or ZocoLini or llbartekll or romchornyiswift-sdk(packages/swift-sdk/Sources/SwiftDashSDK/Core/Utils/DataContractParser.swift,packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DataContractUpdatePreview.swift,packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DataContractUpdateSource.swiftand 12 more) — llbartekll or romchornyiWhen every merge requirement is met, the
PR Hygienecheck passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.