Skip to content

feat(wasm-sdk): add token-paid document support#3599

Open
PastaPastaPasta wants to merge 1 commit intodashpay:v3.1-devfrom
PastaPastaPasta:codex/token-paid-document-support
Open

feat(wasm-sdk): add token-paid document support#3599
PastaPastaPasta wants to merge 1 commit intodashpay:v3.1-devfrom
PastaPastaPasta:codex/token-paid-document-support

Conversation

@PastaPastaPasta
Copy link
Copy Markdown
Member

@PastaPastaPasta PastaPastaPasta commented May 5, 2026

Issue being fixed or feature implemented

Add Evo SDK support for passing tokenPaymentInfo through document state transitions so document types that define schema-level tokenCost can be created, repriced, transferred, deleted, replaced, and purchased from JS.

What was done?

  • threaded optional tokenPaymentInfo parsing through the wasm document transition bindings instead of always passing None
  • exposed the new option on the public document mutation TypeScript interfaces
  • added unit coverage proving the Evo document facade passes tokenPaymentInfo through unchanged
  • added functional coverage for token-costed document create, set-price, and purchase flows, including negative assertions for missing payment info and too-low maximumTokenCost

How Has This Been Tested?

  • cargo check -p wasm-sdk
  • CC=/opt/homebrew/opt/llvm/bin/clang npm exec -- yarn workspace @dashevo/wasm-sdk build
  • npm exec -- yarn workspace @dashevo/evo-sdk build
  • npm exec -- yarn workspace @dashevo/evo-sdk test:unit --grep "DocumentsFacade"
  • npm exec -- yarn workspace @dashevo/wasm-sdk test:functional --grep "Document State Transitions"
  • manual testnet verification using two existing identities to publish a fresh contract/token, transfer tokens, create a document, set its price, and purchase it successfully

Breaking Changes

None.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed

This pull request was created by Codex.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added token payment support for document operations (create, replace, delete, transfer, purchase, and set price).
    • Documents can now be configured with token payment information including contract ID, minimum and maximum costs, and gas payer policy.
  • Tests

    • Added comprehensive test coverage for token payment flows including balance validation, cost rejection scenarios, and ownership verification.

@github-actions github-actions Bot added this to the v3.1.0 milestone May 5, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 5, 2026

📝 Walkthrough

Walkthrough

This PR adds support for optional token-payment metadata (tokenPaymentInfo) across document state transitions in the Wasm SDK. The changes introduce a TypeScript interface, a parser helper, and wire token payment info through six document operation functions (create, replace, delete, transfer, purchase, set_price). Tests are updated to pass token payment info and validate the behavior.

Changes

Token Payment Info Support for Document Transitions

Layer / File(s) Summary
Type Definitions & Parsing
packages/wasm-sdk/src/state_transitions/document.rs
Introduces DocumentTokenPaymentInfo TypeScript interface and try_from_options_optional_token_payment_info helper that deserializes and validates tokenPaymentInfo (including gasFeesPaidBy field validation) from JS options into dash_sdk's TokenPaymentInfo.
Document Transition Wiring
packages/wasm-sdk/src/state_transitions/document.rs
Adds tokenPaymentInfo?: DocumentTokenPaymentInfo to all six document operation option types (DocumentCreateOptions, DocumentReplaceOptions, DocumentDeleteOptions, DocumentTransferOptions, DocumentPurchaseOptions, DocumentSetPriceOptions) and wires parsed token_payment_info into corresponding state transition calls.
Unit Tests
packages/js-evo-sdk/tests/unit/facades/documents.spec.ts
Defines shared tokenPaymentInfo test fixture and updates all eight document test cases (create, replace, delete instance/identifier, transfer, purchase, setPrice) to pass token payment info in options and assert stub calls include the field.
Functional Tests
packages/wasm-sdk/tests/functional/transitions/documents.spec.ts
Adds test utilities (waitForPlatform, getSingleTokenBalance, buildSimpleTokenConfiguration, makeTokenPaymentInfo), refactors platform indexing delays to use shared helper, and introduces comprehensive tokenPaymentInfo document flow suite validating token-cost contract setup, balance tracking, rejection behavior when token info is missing or costs exceed limits, and end-to-end document lifecycle with token payments.

Sequence Diagram

sequenceDiagram
    actor User
    participant JSClient as JavaScript<br/>Client
    participant WasmSDK as Wasm SDK<br/>document_create()
    participant Parser as Parser:<br/>try_from_options_optional<br/>_token_payment_info()
    participant DashSDK as dash_sdk<br/>TokenPaymentInfo
    participant Platform as Dash Platform

    User->>JSClient: documentCreate(document, {<br/>tokenPaymentInfo: {<br/>contractId, position,<br/>minimumTokenCost,<br/>maximumTokenCost,<br/>gasFeesPaidBy<br/>}})
    JSClient->>WasmSDK: call with options
    WasmSDK->>Parser: extract & parse<br/>tokenPaymentInfo
    Parser->>Parser: validate gasFeesPaidBy
    Parser->>DashSDK: convert to TokenPaymentInfo
    DashSDK-->>WasmSDK: Some(TokenPaymentInfo)
    WasmSDK->>Platform: put_to_platform with<br/>token_payment_info
    Platform-->>WasmSDK: state transition result
    WasmSDK-->>JSClient: document created
    JSClient-->>User: success
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Poem

🐰 Hop along, dear tokens flow,
Through documents they gently go,
Six transitions dance with glee,
Payments parsed with harmony,
Tests now bloom with balance true!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The PR title 'feat(wasm-sdk): add token-paid document support' accurately reflects the main change—adding support for token-paid documents in the wasm-sdk with tokenPaymentInfo threading through document state transitions.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@thepastaclaw
Copy link
Copy Markdown
Collaborator

thepastaclaw commented May 5, 2026

Review Gate

Commit: 0e2f17b3

  • Debounce: 699m ago (need 30m)

  • CI checks: build failure: PR title, PR title

  • CodeRabbit review: comment found

  • Off-peak hours: off-peak (09:21 PM PT Tuesday)

  • Run review now (check to override)

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/wasm-sdk/tests/functional/transitions/documents.spec.ts`:
- Around line 28-32: Replace the fixed sleep-based waitForPlatform helper with a
polling-based wait that repeatedly checks the desired condition until it becomes
true or a timeout is reached; specifically, replace uses of waitForPlatform() in
the purchase/ownership checks with a polling loop that calls
getSingleTokenBalance(identityId, tokenId) (or another deterministic query) at
intervals and resolves when the balance/ownership matches the expected value,
failing after a configurable timeout to avoid flakiness. Locate the helper
waitForPlatform and every test call that assumes immediate platform sync (e.g.,
where ownership is read after broadcast) and swap them to invoke the new polling
helper that uses getSingleTokenBalance to assert the final state. Ensure polling
interval and timeout are configurable and provide a clear error message on
timeout.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b9ee1b67-f584-41ab-a30e-6fd44b7368c8

📥 Commits

Reviewing files that changed from the base of the PR and between 3874e67 and 0e2f17b.

📒 Files selected for processing (3)
  • packages/js-evo-sdk/tests/unit/facades/documents.spec.ts
  • packages/wasm-sdk/src/state_transitions/document.rs
  • packages/wasm-sdk/tests/functional/transitions/documents.spec.ts

Comment on lines +28 to +32
const waitForPlatform = async (ms = 2000) => new Promise((resolve) => { setTimeout(resolve, ms); });
const getSingleTokenBalance = async (identityId: string, tokenId: string) => {
const balances = await client.getIdentityTokenBalances(identityId, [tokenId]);
return balances.get(tokenId);
};
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Replace fixed sleeps with condition polling to avoid flaky functional tests

Using a constant sleep for platform sync is brittle, and the purchase path reads ownership immediately after broadcast. On slower runs, this can intermittently fail despite correct behavior.

Suggested direction
-const waitForPlatform = async (ms = 2000) => new Promise((resolve) => { setTimeout(resolve, ms); });
+const waitForPlatform = async (
+  condition: () => Promise<boolean>,
+  timeoutMs = 20_000,
+  intervalMs = 250,
+) => {
+  const startedAt = Date.now();
+  while (Date.now() - startedAt < timeoutMs) {
+    if (await condition()) return;
+    await new Promise((resolve) => { setTimeout(resolve, intervalMs); });
+  }
+  throw new Error('Timed out waiting for platform state');
+};
-const purchasedDocument = await client.getDocument(
-  tokenPaidContractId,
-  'tokenPaidListing',
-  tokenPaidDocumentId,
-);
+await waitForPlatform(async () => {
+  try {
+    const doc = await client.getDocument(
+      tokenPaidContractId,
+      'tokenPaidListing',
+      tokenPaidDocumentId,
+    );
+    return doc.ownerId.toString() === testData.identityId3;
+  } catch {
+    return false;
+  }
+});
+
+const purchasedDocument = await client.getDocument(
+  tokenPaidContractId,
+  'tokenPaidListing',
+  tokenPaidDocumentId,
+);

Also applies to: 531-535

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/wasm-sdk/tests/functional/transitions/documents.spec.ts` around
lines 28 - 32, Replace the fixed sleep-based waitForPlatform helper with a
polling-based wait that repeatedly checks the desired condition until it becomes
true or a timeout is reached; specifically, replace uses of waitForPlatform() in
the purchase/ownership checks with a polling loop that calls
getSingleTokenBalance(identityId, tokenId) (or another deterministic query) at
intervals and resolves when the balance/ownership matches the expected value,
failing after a configurable timeout to avoid flakiness. Locate the helper
waitForPlatform and every test call that assumes immediate platform sync (e.g.,
where ownership is read after broadcast) and swap them to invoke the new polling
helper that uses getSingleTokenBalance to assert the final state. Ensure polling
interval and timeout are configurable and provide a clear error message on
timeout.

@PastaPastaPasta PastaPastaPasta changed the title feat(evo-sdk): add token-paid document support feat(wasm-sdk): add token-paid document support May 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants