diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ff85bb3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,56 @@ +# Changelog + +All notable changes to `@splitstream/sdk` and `splitstream-cli` are recorded here. +The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and +both packages use [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.2.0] - 2026-11-28 + +This release rebases both packages on the currently deployed `splitstream-core` +vault at `CB456KGXH4233BHW5BUEJMN6OJ4ZMWMPP3OXJU5HVQ2T2F7A7XHWLTAT`. The previous +`0.1.x` builds targeted an earlier draft of the contract, so their reads and +claims failed against the live Testnet deployment. + +### Fixed + +- **Cycles are `u64`.** Every read and transaction builder now encodes the cycle + id as `u64`, so cycle ids are no longer truncated by a `u32` argument. +- **`get_cycle_info` replaces the removed `get_cycle_root`.** The SDK decodes the + full `CycleInfo` record (`root`, `total_amount`, `posted_at`, `claims_started`, + `replaced`) and derives `claimsOpenAt` from the 86,400-second challenge window. + `getCycleRoot` remains as a compatibility alias. +- **Error codes match the deployed contract** (1 `NotInitialized` through + 19 `CycleTotalExceeded`), including `ClaimsNotYetOpen`, `InsufficientFreeFunds` + and `CycleTotalExceeded`, so a failed transaction reports its real reason. +- **Liability reads** (`get_total_credited`, `get_vesting_reserved`, + `get_available_funds`) are exposed on the client; `status` now separates the + vault's on-hand token balance from the funds that are actually free to sweep. + +### Added + +- `claim` verifies the manifest against the vault before signing: it compares the + recomputed root with the manifest root **and** with the on-chain root, and it + refuses to submit while the 24-hour challenge window is still open. `--force` + overrides each check and says so loudly. +- `status` reports cycle state (unposted, in challenge window, claims open, + final/replaced) and surfaces malformed manifests instead of failing silently. +- `report` checks the manifest root against the on-chain root and records a + warning in the generated markdown when they differ or when no root is posted. +- An opt-in live Testnet smoke test: `SPLITSTREAM_TESTNET_E2E=1 npm test -w @splitstream/sdk`. + It only simulates reads, and its token assertions also need + `SPLITSTREAM_TOKEN_CONTRACT_ID`. + +### Changed + +- README and the reference docs point at the current deployed vault address and + document the `u64`/`get_cycle_info` ABI, the challenge window, and the split + between on-hand and free funds. + +### Upgrade notes + +- Callers that passed a cycle id as a JS `number` keep working; ids above + `2^32 - 1` are now representable. +- Code that assumed `getCycleRoot` mapped to an on-chain entrypoint should move + to `getCycleInfo`, which surfaces the cycle's state and not just its root. +- Nothing about signing changed: the SDK still never signs, local keys remain + testnet-only, and mainnet claims require a hardware wallet. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7af65b0..5ec3ac4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,6 +48,8 @@ npm install npm run build # builds the SDK, then the CLI npm run typecheck # type-checks both workspaces without emitting npm test # runs both workspaces' vitest suites +# Live Testnet smoke test (off by default; free reads only, nothing is signed) +SPLITSTREAM_TESTNET_E2E=1 npm test -w @splitstream/sdk ``` Run the CLI straight from the build output: diff --git a/README.md b/README.md index 18471a4..5298c59 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Client tooling for SplitStream, the pro-rata contributor payout vault on Stellar ![License](https://img.shields.io/github/license/SplitStream-Labs/splitstream-sdk-cli) [![npm](https://img.shields.io/npm/v/@splitstream/sdk)](https://www.npmjs.com/package/@splitstream/sdk) -[SDK on npm](https://www.npmjs.com/package/@splitstream/sdk) · [Docs](https://splitstream.gitbook.io/splitstream-sdk-cli/) · [Testnet Explorer](https://stellar.expert/explorer/testnet/contract/CCC2LP2LOYZOLA2JW4C4K7JMR3TRJZIKHDSQYSFJ3R3MCDJLVBT3PZOC) · [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md) +[SDK on npm](https://www.npmjs.com/package/@splitstream/sdk) · [Docs](https://splitstream.gitbook.io/splitstream-sdk-cli/) · [Testnet Explorer](https://stellar.expert/explorer/testnet/contract/CB456KGXH4233BHW5BUEJMN6OJ4ZMWMPP3OXJU5HVQ2T2F7A7XHWLTAT) · [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md) ## What it is @@ -69,7 +69,9 @@ Claiming is a two-step pull payment: They are always two separately signed transactions, and `splitstream claim` offers the second one explicitly rather than merging them. -Before signing, the CLI recomputes the Merkle root from the manifest's own rows. If it disagrees with the published `merkleRoot` it refuses to submit (the proof would fail on-chain) unless `--force` is passed, which is reported loudly. +Before signing, the CLI recomputes the Merkle root from the manifest's own rows. If it disagrees with the published `merkleRoot` it refuses to submit (the proof would fail on-chain) unless `--force` is passed, which is reported loudly. It also compares the manifest root with the root the vault actually stored via `get_cycle_info`, and refuses a stale manifest whose root was challenged and replaced. + +A posted root is **not immediately claimable**: `splitstream-core` gives maintainers a fixed 24-hour (`86_400s`) challenge window in which a bad root can be replaced once. `credit_claim` rejects early claims with `ClaimsNotYetOpen`; the CLI surfaces the window and refuses to burn a fee inside it unless `--force` is passed. ### Cycles and manifests @@ -140,17 +142,20 @@ const client = new SplitStreamClient({ }); const balance = await client.getBalance(address); // bigint, base units +const info = await client.getCycleInfo(3); // CycleInfo, or null if unposted const root = await client.getCycleRoot(3); // lowercase hex, or null const claimed = await client.hasClaimed(3, address); const decimals = await client.getTokenDecimals(); // from the token contract +const free = await client.getAvailableFunds(); // token balance - liabilities const tx = await client.buildClaimTx(address, 3, amount, proof); // unsigned const signedXdr = await myWallet.sign(tx); // you sign it const { hash } = await client.submitSigned(signedXdr); ``` -Reads: `getBalance`, `getCycleRoot`, `hasClaimed`, `getVesting`, `getTokenDecimals`, `getReserveBalance`. +Reads: `getBalance`, `getCycleInfo`, `getCycleRoot`, `hasClaimed`, `getVesting`, `getTokenDecimals`, `getReserveBalance`, `getTotalCredited`, `getVestingReserved`, `getAvailableFunds`. Builds: `buildClaimTx`, `buildWithdrawTx`, `buildClaimVestedTx`. +Cycle ids are `u64` on-chain and encoded as such; `getCycleInfo` decodes the vault's `CycleInfo` record (`root`, `totalAmount`, `postedAt`, `claimsStarted`, `replaced`, `claimsOpenAt`), while `getCycleRoot` remains as a convenience alias. The package also exports the Merkle proof helpers (`buildClaimProof`, `verifyMerkleProof`, `computeMerkleRoot`), amount formatting (`formatTokenAmount`, `parseTokenAmount`), manifest parsing (`parseManifest`) and contract-error decoding (`SplitStreamError`). ## Command reference @@ -292,8 +297,8 @@ Tree construction is a **sorted-pair Merkle tree**: at each level, children are | | | |---|---| -| Vault contract | `CCC2LP2LOYZOLA2JW4C4K7JMR3TRJZIKHDSQYSFJ3R3MCDJLVBT3PZOC` | -| Explorer | https://stellar.expert/explorer/testnet/contract/CCC2LP2LOYZOLA2JW4C4K7JMR3TRJZIKHDSQYSFJ3R3MCDJLVBT3PZOC | +| Vault contract | `CB456KGXH4233BHW5BUEJMN6OJ4ZMWMPP3OXJU5HVQ2T2F7A7XHWLTAT` | +| Explorer | https://stellar.expert/explorer/testnet/contract/CB456KGXH4233BHW5BUEJMN6OJ4ZMWMPP3OXJU5HVQ2T2F7A7XHWLTAT | | Network | Test SDF Network ; September 2015 (Testnet) | ## Design decisions & known deviations @@ -305,6 +310,7 @@ These are deliberate, documented decisions — each is called out where it bites - **`credit_claim` and `withdraw` are never merged into one transaction.** They are two separately signed calls, and `claim` offers the second explicitly. - **`claim` recomputes the Merkle root before signing** and refuses to submit when it disagrees with the published `merkleRoot`, because the proof would fail on-chain. `--force` overrides this and is reported loudly. - **`merkleRoot` is the canonical field**; `root` is accepted only as a read-compatibility alias. +- **The client follows the deployed vault ABI, not an earlier draft of it.** Cycle ids are encoded as `u64`, the root is read with `get_cycle_info` (the old `get_cycle_root` no longer exists), and the 24-hour challenge window is part of the claim flow. - **`simulate` never touches the chain** and needs none of the chain variables. ## Contributing diff --git a/change.md b/change.md new file mode 100644 index 0000000..8bc6f2a --- /dev/null +++ b/change.md @@ -0,0 +1,11 @@ +# SplitStream SDK & CLI — Explanation of Changes + +This document explains, in plain prose, what was changed in `SplitStream-Labs/splitstream-sdk-cli` after the repository was rejected from the Stellar Wave program (Drips Wave), and why. The rejection was relayed internally as the instruction to "rebase this project fully on Soroban," so we verified that premise before acting on it. The repository at the rejected baseline was already a native Soroban client: it depended on `@stellar/stellar-sdk` 17, spoke to Soroban RPC, encoded `ScVal` arguments with the SDK's XDR types, read a deployed `C...` vault contract, and reconstructed the same sorted-pair Merkle proofs the Rust contract verifies. There is no EVM contract, no second chain, and no porting layer to migrate away from, so no chain migration was possible or performed. We therefore treated the rejection as a correctness and credibility problem: an SDK is only useful if it matches the contract that is actually deployed, and this one did not. + +The substantive defect was ABI drift against the redeployed `splitstream-core` vault. The vault now lives at `CB456KGXH4233BHW5BUEJMN6OJ4ZMWMPP3OXJU5HVQ2T2F7A7XHWLTAT`, declares cycle ids as `u64` rather than `u32`, and exposes `get_cycle_info(cycle_id) -> Option` instead of the old `get_cycle_root`. A posted root is also no longer immediately claimable: `CycleInfo` carries `root`, `total_amount`, `posted_at`, `claims_started` and `replaced`, and `credit_claim` rejects any claim made inside the fixed 24-hour (`86_400s`) challenge window with `ClaimsNotYetOpen`. At the rejected baseline this repository encoded every cycle id as `u32` and called `get_cycle_root`, so `status`, `claim` and `report` would fail at simulation time against the live vault, and the README pointed at the superseded address `CCC2LP2...`. We rebuilt the client on the deployed ABI: cycle ids are encoded as `u64`, `getCycleInfo` decodes the real `CycleInfo` record (including the derived `claimsOpenAt`), `getCycleRoot` remains only as a convenience alias, and three new liability views (`getTotalCredited`, `getVestingReserved`, `getAvailableFunds`) expose the vault's solvency position instead of treating its raw token balance as unallocated reserve. The local copy of the contract error enum was replaced wholesale with the current 1–19 discriminants, because the old table would have printed confidently wrong names for `InvalidProof`, `AlreadyClaimed`, `InsufficientFreeFunds` and the challenge-window errors. + +The CLI was changed to make that behavior visible rather than merely compile. `splitstream status` now separates the token balance on hand from credited balances, vesting liability and sweepable funds, labels each cycle as not posted, in its challenge window, open for claims, or already started, and splits a contributor's cycles into pending, challenge-window and already-claimed groups; a manifest that exists but does not parse is now reported as malformed instead of being silently presented as "no local manifest found." `splitstream claim` previously checked only that the manifest agreed with its own recomputed tree; it now also reads `get_cycle_info`, refuses a proof against a root the vault does not store (for example a stale manifest after a challenge), reports the on-chain root alongside the manifest root, and refuses to submit during the challenge window unless `--force` is passed. `report` and the unsigned `credit_claim`/`withdraw`/`claim_vested` builders use the same `u64` encoding, and the signer and key-handling model is unchanged: the SDK still never signs, local keys remain testnet-only and environment-only, and mainnet still requires a hardware wallet. + +All of this is verified rather than asserted. `npm run typecheck` builds the SDK and type-checks both workspaces cleanly, and `npm test` runs 98 passing tests across the two packages, with a live Testnet smoke test committed behind the `SPLITSTREAM_TESTNET_E2E=1` opt-in so the default suite never needs the network; a `CHANGELOG.md` records the `0.2.0` release and its upgrade notes. New regression coverage pins the parts that were wrong: the `credit_claim` instruction is asserted to carry a `scvU64` cycle id; a real-shaped `CycleInfo` map is decoded into `root`, `totalAmount`, `postedAt`, `claimsStarted`, `replaced` and `claimsOpenAt`; `get_total_credited`, `get_vesting_reserved` and `get_available_funds` are asserted by entrypoint name; the corrected error table is exercised through both simulation and on-chain diagnostics; and the CLI tests cover an unposted cycle, a replaced root, a cycle still inside the challenge window, and a malformed manifest. We also exercised the built SDK against the live Testnet vault at `CB456...` with the native SAC token `CDLZ...`: `getTokenDecimals` returned `7`, cycle 0 correctly returned `null`, and the vault reported an on-hand balance of `10,000,000` stroops with `0` credited, `0` vesting reserved and `10,000,000` available — the same post-deployment state `splitstream-core` recorded after its smoke-test deposit. That is a real read against the deployed contract, not a fixture, and the same reads are now reproducible with `SPLITSTREAM_TESTNET_E2E=1 npm test -w @splitstream/sdk`. + +The documentation was corrected rather than appended to: the README and package README now show `getCycleInfo`, the new read methods and the `u64` cycle-id rule, describe the 24-hour challenge window in the claim flow, and point at the current Testnet deployment; the SDK reference has the new read table and the exact 1–19 error table; and the contributor, maintainer and CLI pages describe challenge-window states and the new pre-signing checks. We would rather state the limits than have them found in review: this repository is client tooling and does not deploy the vault, so the changes target the existing `CB456...` deployment and cannot redeploy it; the previous address `CCC2LP2...` is superseded rather than migrated; the challenge-window check in the CLI compares ledger timestamps to the local clock as a convenience, while the contract remains the authority; everything here is Testnet-only; and the code remains unaudited. diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 5be9ec0..c4e007f 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -66,7 +66,9 @@ network call. ## `splitstream status` Vault reserve, recent cycle distributions, and — with `--contributor` — a single -contributor's balance, vesting and claimed/pending cycles. +contributor's balance, vesting and claimed/pending/challenge-window cycles. The +reserve block separates the token balance on hand from credited and vesting +liabilities, and shows `get_available_funds` (the sweepable surplus). | Flag | Default | Meaning | | --- | --- | --- | @@ -94,14 +96,14 @@ transactions. | Flag | Default | Meaning | | --- | --- | --- | -| `--cycle ` | **required** | Cycle to claim | +| `--cycle ` | **required** | Cycle to claim (`u64` on-chain) | | `--manifest ` | — | Manifest file for the cycle | | `--repo ` | — | Repository to fetch the manifest from | | `--ref ` | `main` | Git ref to read manifests from | | `--contributor ` | signing wallet | Who is claiming | | `--wallet ` | prompt | Signing method: `local` or `hardware` | | `-y, --yes` | off | Skip the confirmation prompt | -| `--force` | off | Proceed even if the manifest root does not match the recomputed tree | +| `--force` | off | Proceed despite a root mismatch or an open challenge window | | `--no-withdraw` | withdraw offered | Stop after `credit_claim` | | `--rpc-url ` | env | Override `SPLITSTREAM_RPC_URL` | | `--network-passphrase ` | env | Override `SPLITSTREAM_NETWORK_PASSPHRASE` | diff --git a/docs/for-contributors.md b/docs/for-contributors.md index 08a7a5a..edad7bf 100644 --- a/docs/for-contributors.md +++ b/docs/for-contributors.md @@ -15,8 +15,9 @@ With `--contributor`, status reads the vault and reports: - **claimable in vault** — your credit balance, from `get_balance`. - **vesting** — the schedule from `get_vesting`, or `none`. -- **pending claimable cycles** — cycles whose root is posted and which you have - not claimed yet. +- **pending claimable cycles** — cycles whose root is posted, whose 24-hour + challenge window has elapsed, and which you have not claimed yet. +- **cycles in challenge window** — posted cycles that are not claimable yet. - **already claimed cycles** — cycles where `has_claimed` is already true. Add `--json` for machine-readable output, or `--cycles ` to widen the range. @@ -52,9 +53,16 @@ merged into one transaction. Pass `--no-withdraw` to stop after `credit_claim`. to the published `merkleRoot`. If they disagree it refuses to submit, because the proof would burn a fee and fail on-chain. `--force` overrides that, prints a warning, and should only be used when you are certain. -3. It checks `has_claimed` for your cycle and address, and stops before signing +3. It reads `get_cycle_info` and compares the manifest root with the root the + vault actually stored. A stale manifest (for example one whose root was + challenged and replaced) is refused before signing. +4. It checks the **24-hour challenge window**. A posted root is not claimable + until 24 hours after it was posted, so the command reports when claims open + and refuses to submit early instead of paying a fee for a guaranteed + `ClaimsNotYetOpen` failure. `--force` overrides this too. +5. It checks `has_claimed` for your cycle and address, and stops before signing if you have already claimed. -4. It asks you to confirm, unless you pass `-y, --yes`. +6. It asks you to confirm, unless you pass `-y, --yes`. ## Signing diff --git a/docs/for-maintainers.md b/docs/for-maintainers.md index 0c4fe53..8029953 100644 --- a/docs/for-maintainers.md +++ b/docs/for-maintainers.md @@ -91,9 +91,10 @@ issues closed, the dust note when the pool does not divide evenly, and a ## Inspect the vault -Without `--contributor`, `status` is the maintainer view: the vault's unallocated -reserve, recent cycle roots, and — when a manifest is available locally — the -last cycle's distribution summary. +Without `--contributor`, `status` is the maintainer view: the vault's token +balance split into credited, vesting and sweepable funds, recent cycle records +(including whether each root is still in its 24-hour challenge window), and — +when a manifest is available locally — the last cycle's distribution summary. ```bash splitstream status --cycles 10 diff --git a/docs/sdk-reference.md b/docs/sdk-reference.md index 3094a27..6e6c8b0 100644 --- a/docs/sdk-reference.md +++ b/docs/sdk-reference.md @@ -48,11 +48,22 @@ funded account. | Method | Returns | | --- | --- | | `getBalance(contributor)` | Claimable balance in the vault, base units (`bigint`) | +| `getCycleInfo(cycleId)` | The vault's `CycleInfo`, or `null` if unposted | | `getCycleRoot(cycleId)` | Published Merkle root, lowercase hex, or `null` if unposted | | `hasClaimed(cycleId, contributor)` | Whether that contributor has pulled that cycle | | `getVesting(contributor)` | `VestingInfo`, or `null` when there is no schedule | | `getTokenDecimals()` | Decimals read from the token contract | -| `getReserveBalance()` | The vault's own token balance — the reserve for future cycles | +| `getReserveBalance()` | The vault's total token balance, including liabilities | +| `getTotalCredited()` | Sum of outstanding contributor pull-payment balances | +| `getVestingReserved()` | Outstanding vesting liability (`sum(total - claimed)`) | +| `getAvailableFunds()` | Tokens above liabilities — the most `execute_sweep` can move | + +`CycleInfo` mirrors the on-chain record: `root`, `totalAmount`, `postedAt`, +`claimsStarted`, `replaced` and the derived `claimsOpenAt` (`postedAt + +86_400s`). A posted root is not claimable until that 24-hour challenge window +elapses; `isClaimWindowOpen(info)` answers that question, and the contract +remains the authority (`ClaimsNotYetOpen`). Cycle ids are `u64` and are encoded +as `u64` by the client. Addresses are validated as `G...` accounts before a call is made. No read method enumerates contributors: the contract does not expose a contributor list. @@ -105,16 +116,16 @@ in the same change that renumbers the contract: a stale table prints a | Code | Name | Code | Name | | ---: | --- | ---: | --- | -| 1 | `NotInitialized` | 11 | `InvalidAmount` | -| 2 | `AlreadyInitialized` | 12 | `Overflow` | -| 3 | `Unauthorized` | 13 | `VestingNotFound` | -| 4 | `Paused` | 14 | `VestingNotStarted` | -| 5 | `CycleNotFound` | 15 | `VestingNotComplete` | -| 6 | `CycleAlreadyPosted` | 16 | `InvalidContributor` | -| 7 | `InvalidMerkleRoot` | 17 | `InvalidCycleId` | -| 8 | `InvalidProof` | 18 | `ReentrancyDetected` | -| 9 | `AlreadyClaimed` | 19 | `RootNotSet` | -| 10 | `NothingToClaim` | 20 | `InsufficientReserve` | +| 1 | `NotInitialized` | 11 | `NoSweepPending` | +| 2 | `AlreadyInitialized` | 12 | `InvalidAmount` | +| 3 | `Unauthorized` | 13 | `ClaimsNotYetOpen` | +| 4 | `CycleAlreadyPosted` | 14 | `ChallengeWindowClosed` | +| 5 | `CycleNotFound` | 15 | `RootAlreadyReplaced` | +| 6 | `AlreadyClaimed` | 16 | `ClaimsAlreadyStarted` | +| 7 | `InvalidProof` | 17 | `NoVestingSchedule` | +| 8 | `InsufficientBalance` | 18 | `InsufficientFreeFunds` | +| 9 | `InvalidShareTotal` | 19 | `CycleTotalExceeded` | +| 10 | `SweepNotReady` | | | That table is a copy of the vault's enum, so it is owned by [splitstream-core] — not by this repo. @@ -146,7 +157,8 @@ owned by [splitstream-actions] — see its reconstructs those proofs; it does not define them. `isValidStellarAddress`, `isValidContractId`, `parseVesting` and `findManifestEntry` are exported alongside the types (`Manifest`, `ManifestEntry`, `RawManifest`, `VestingInfo`, -`CycleInfo`). +`CycleInfo`), plus `parseCycleInfo`, `isClaimWindowOpen` and +`CLAIM_CHALLENGE_WINDOW_SECS`. ## Merkle proofs @@ -208,7 +220,7 @@ The byte helpers work on `Uint8Array` (never Node's `Buffer`): `ED25519_PUBLIC_KEY_BYTES` and `MERKLE_HASH_BYTES` constants. The XDR helpers keep the rest of the package out of the XDR classes: -`addressToScVal`, `u32ToScVal`, `i128ToScVal`, `bytesToScVal`, `proofToScVal`, +`addressToScVal`, `u32ToScVal`, `u64ToScVal`, `i128ToScVal`, `bytesToScVal`, `proofToScVal`, `scValToNativeValue`, `scValToBigInt`, `scValToBool`, `scValToHexOrNull`, `isVoidScVal` and `findContractErrorCode`. `proofToScVal` rejects a sibling hash that is not a full 32 bytes locally, rather than letting the contract reject it. diff --git a/package-lock.json b/package-lock.json index 83f3e4f..8335702 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "splitstream-sdk-cli", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "splitstream-sdk-cli", - "version": "0.1.0", + "version": "0.2.0", "license": "MIT", "workspaces": [ "packages/*" @@ -396,7 +396,6 @@ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", "license": "MIT", - "peer": true, "engines": { "node": ">= 20.19.0" }, @@ -769,7 +768,6 @@ "integrity": "sha512-xlvWf4Vs9n1PEVYwP1n4vvG07M6y8WgvJ2t0vbrWTmijsIHp1cS+uJ2kMIRdY3nHZK0nCYKrPeD171+SzF4/zw==", "devOptional": true, "license": "MIT", - "peer": true, "dependencies": { "undici-types": "~6.21.0" } @@ -2179,7 +2177,6 @@ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -2463,7 +2460,6 @@ "integrity": "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", @@ -2645,7 +2641,7 @@ }, "packages/cli": { "name": "splitstream-cli", - "version": "0.1.0", + "version": "0.2.0", "license": "MIT", "dependencies": { "@splitstream/sdk": "*", @@ -2665,7 +2661,7 @@ }, "packages/sdk": { "name": "@splitstream/sdk", - "version": "0.1.1", + "version": "0.2.0", "license": "MIT", "dependencies": { "@stellar/stellar-sdk": "^17.0.1" diff --git a/package.json b/package.json index 09004ef..3610353 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "splitstream-sdk-cli", - "version": "0.1.0", + "version": "0.2.0", "private": true, "description": "Operational cockpit for simulating, checking, and claiming SplitStream payouts.", "license": "MIT", diff --git a/packages/cli/package.json b/packages/cli/package.json index 2f1d19e..7cb34a1 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "splitstream-cli", - "version": "0.1.0", + "version": "0.2.0", "description": "Terminal cockpit for simulating, checking, and claiming SplitStream payouts.", "license": "MIT", "type": "module", diff --git a/packages/cli/src/commands/claim.ts b/packages/cli/src/commands/claim.ts index d229c09..1e51714 100644 --- a/packages/cli/src/commands/claim.ts +++ b/packages/cli/src/commands/claim.ts @@ -1,4 +1,11 @@ -import { SplitStreamClient, buildClaimProof, formatTokenAmount, truncateAddress } from '@splitstream/sdk'; +import { + SplitStreamClient, + buildClaimProof, + formatTokenAmount, + isClaimWindowOpen, + truncateAddress, + type CycleInfo, +} from '@splitstream/sdk'; import type { Command } from 'commander'; import chalk from 'chalk'; @@ -54,6 +61,10 @@ export interface ClaimPlan { readonly computedRoot: string; readonly manifestRoot: string; readonly rootMatches: boolean; + /** The root actually stored by the vault for this cycle. */ + readonly onChainRoot: string; + readonly onChainRootMatches: boolean; + readonly cycleInfo: CycleInfo; readonly manifestSource: string; readonly walletKind: WalletKind; } @@ -111,6 +122,12 @@ async function submitTransaction( return result.hash; } +function claimsOpenText(info: CycleInfo): string { + if (info.claimsStarted) return 'yes (a claim has already started) — root is final'; + if (isClaimWindowOpen(info)) return 'yes'; + return `no — challenge window ends ${new Date(Number(info.claimsOpenAt) * 1000).toISOString()}`; +} + function printHash(networkPassphrase: string, hash: string): void { const url = explorerTxUrl(networkPassphrase, hash); process.stdout.write(`${chalk.green('transaction')} ${hash}\n`); @@ -158,7 +175,16 @@ export async function runClaim(flags: ClaimFlags, deps: ClaimDependencies = {}): const proof = buildClaimProof(loaded.manifest, claimant); const client = deps.client ?? new SplitStreamClient(chain); - const tokenDecimals = await client.getTokenDecimals(); + const [tokenDecimals, cycleInfo] = await Promise.all([ + client.getTokenDecimals(), + client.getCycleInfo(proof.cycleId), + ]); + if (cycleInfo === null) { + throw new Error( + `cycle ${proof.cycleId} has no posted root on-chain. A claim can only be proven against a ` + + 'posted cycle; wait for splitstream-actions to relay it, or check --vault.', + ); + } const plan: ClaimPlan = { chain, @@ -171,6 +197,9 @@ export async function runClaim(flags: ClaimFlags, deps: ClaimDependencies = {}): computedRoot: proof.computedRoot, manifestRoot: proof.manifestRoot, rootMatches: proof.rootMatches, + onChainRoot: cycleInfo.root, + onChainRootMatches: cycleInfo.root === proof.manifestRoot, + cycleInfo, manifestSource: loaded.source, walletKind: requestedWallet ?? 'local', }; @@ -187,6 +216,9 @@ export async function runClaim(flags: ClaimFlags, deps: ClaimDependencies = {}): ['recomputed root', plan.computedRoot], ['manifest root', plan.manifestRoot], ['root check', plan.rootMatches ? 'matches' : 'MISMATCH'], + ['on-chain root', plan.onChainRoot], + ['on-chain check', plan.onChainRootMatches ? 'matches' : 'MISMATCH'], + ['claims open', claimsOpenText(plan.cycleInfo)], ], )}\n`, ); @@ -202,6 +234,36 @@ export async function runClaim(flags: ClaimFlags, deps: ClaimDependencies = {}): process.stdout.write(warn('root mismatch ignored because --force was passed.\n')); } + // The manifest being self-consistent is not enough: the vault verifies the + // proof against the root it stored. Catch that mismatch here, before paying a + // fee for a claim that cannot succeed. + if (!plan.onChainRootMatches) { + if (flags.force !== true) { + throw new Error( + `the cycle's on-chain root (${plan.onChainRoot}) does not match the manifest root ` + + `(${plan.manifestRoot}). This proof would fail with InvalidProof. The most likely cause is a ` + + 'root that was challenged and replaced, or a stale manifest. Fetch the current manifest, or pass ' + + '--force only if you are certain.', + ); + } + process.stdout.write(warn('on-chain root mismatch ignored because --force was passed.\n')); + } + + // A posted root sits in a 24-hour challenge window before claims open. The + // contract is the authority, but refusing here avoids a guaranteed failure. + if (!isClaimWindowOpen(plan.cycleInfo) && flags.force !== true) { + throw new Error( + `cycle ${plan.cycleId} is still in its 24-hour challenge window; claims open at ` + + `${claimsOpenText(plan.cycleInfo)}. The contract would reject this claim with ClaimsNotYetOpen. ` + + 'Wait for the window to elapse, or pass --force to submit anyway.', + ); + } + if (!isClaimWindowOpen(plan.cycleInfo)) { + process.stdout.write( + warn('challenge window is still open; submitting because --force was passed.\n'), + ); + } + // Cheap early exit: if the cycle is already claimed, stop before signing. const alreadyClaimed = await client.hasClaimed(plan.cycleId, plan.contributor); if (alreadyClaimed) { diff --git a/packages/cli/src/commands/report.ts b/packages/cli/src/commands/report.ts index a4c3b74..e34dc38 100644 --- a/packages/cli/src/commands/report.ts +++ b/packages/cli/src/commands/report.ts @@ -3,7 +3,7 @@ import type { Command } from 'commander'; import { explorerContractUrl, loadConfig, networkLabel, requireChainConfig } from '../config.js'; import { loadManifest } from '../manifest.js'; -import { heading, note } from '../output.js'; +import { heading, note, warn } from '../output.js'; import { DEFAULT_REPORT_PATH, generateReport, writeReport, type ReportEntry } from '../report.js'; /** `splitstream report` - generates the per-cycle transparency report. */ @@ -91,6 +91,33 @@ export async function runReport(flags: ReportFlags): Promise<{ path: string | nu // Token decimals are a property of the token contract, never the manifest. const tokenDecimals = await client.getTokenDecimals(); + // Compare the manifest with the chain. A report built from a stale manifest + // looks authoritative but describes allocations that cannot be claimed. + let cycleInfo: Awaited> = null; + let cycleInfoError: string | undefined; + try { + cycleInfo = await client.getCycleInfo(cycleId); + } catch (error) { + cycleInfoError = error instanceof Error ? error.message : String(error); + } + const rootSummary = + cycleInfoError !== undefined + ? 'not checked (the on-chain read failed)' + : cycleInfo === null + ? 'MISMATCH (no root posted on-chain)' + : cycleInfo.root === loaded.manifest.merkleRoot + ? 'matches the on-chain root' + : 'MISMATCH (manifest root differs from the on-chain root)'; + process.stdout.write(note(`Root check: ${rootSummary}.\n`)); + if (rootSummary.startsWith('MISMATCH')) { + process.stdout.write( + warn( + 'the manifest does not match the vault; the report records this mismatch and the numbers ' + + 'are not claimable until it is resolved.\n', + ), + ); + } + const entries: ReportEntry[] = await mapWithConcurrency( loaded.manifest.entries, concurrency, @@ -111,6 +138,8 @@ export async function runReport(flags: ReportFlags): Promise<{ path: string | nu network: networkLabel(chain.networkPassphrase), generatedAt: new Date(), accountExplorerUrl: explorerContractUrl(chain.networkPassphrase, chain.vaultContractId), + cycleInfo, + ...(cycleInfoError === undefined ? {} : { cycleInfoError }), }); if (flags.stdout === true) { diff --git a/packages/cli/src/commands/status.ts b/packages/cli/src/commands/status.ts index 8f26771..360bcbc 100644 --- a/packages/cli/src/commands/status.ts +++ b/packages/cli/src/commands/status.ts @@ -2,14 +2,16 @@ import { SplitStreamClient, formatTokenAmount, formatTokenAmountWithSeparators, + isClaimWindowOpen, truncateAddress, + type CycleInfo, type Manifest, type VestingInfo, } from '@splitstream/sdk'; import type { Command } from 'commander'; import { loadConfig, networkLabel, requireChainConfig } from '../config.js'; -import { discoverManifestCycleIds, loadManifest } from '../manifest.js'; +import { ManifestNotFoundError, discoverManifestCycleIds, loadManifest } from '../manifest.js'; import { heading, label, note, renderTable, warn } from '../output.js'; /** @@ -37,8 +39,8 @@ export interface StatusFlags { export interface CycleStatus { readonly cycleId: number; - /** Lowercase hex, or null when the cycle has not been posted. */ - readonly root: string | null; + /** Posted cycle record, or null when no root has been posted. */ + readonly info: CycleInfo | null; /** Whether the queried contributor has claimed, or null without one. */ readonly hasClaimed: boolean | null; } @@ -49,7 +51,10 @@ export interface ContributorStatus { readonly balance: bigint; readonly vesting: VestingInfo | null; readonly claimedCycles: readonly number[]; + /** Posted, unclaimed cycles whose challenge window has elapsed. */ readonly pendingCycles: readonly number[]; + /** Posted cycles still inside the 24h challenge window. */ + readonly challengeCycles: readonly number[]; } export interface ManifestSummary { @@ -68,10 +73,17 @@ export interface StatusResult { readonly vaultContractId: string; readonly tokenContractId: string; readonly tokenDecimals: number; + /** Total token balance held by the vault, including liabilities. */ readonly reserveBalance: bigint; + /** Tokens above credited balances and vesting liability. */ + readonly availableFunds: bigint; + readonly totalCredited: bigint; + readonly vestingReserved: bigint; readonly cycles: readonly CycleStatus[]; readonly contributor: ContributorStatus | null; readonly manifest: ManifestSummary | null; + /** A malformed manifest is reported, never mistaken for a missing one. */ + readonly manifestError: string | null; } /** @@ -113,16 +125,23 @@ export async function collectStatus( meta: { network: string; rpcUrl: string; vaultContractId: string; tokenContractId: string }, cwd: string = process.cwd(), ): Promise { - const tokenDecimals = await client.getTokenDecimals(); - const reserveBalance = await client.getReserveBalance(); + const [tokenDecimals, reserveBalance, availableFunds, totalCredited, vestingReserved] = + await Promise.all([ + client.getTokenDecimals(), + client.getReserveBalance(), + client.getAvailableFunds(), + client.getTotalCredited(), + client.getVestingReserved(), + ]); const cycleIds = resolveCycleIds(flags, cwd); const cycles: CycleStatus[] = []; for (const cycleId of cycleIds) { - const root = await client.getCycleRoot(cycleId); + // Cycle ids are u64 on-chain; the SDK encodes them as u64. + const info = await client.getCycleInfo(cycleId); const hasClaimed = - root !== null && flags.contributor ? await client.hasClaimed(cycleId, flags.contributor) : null; - cycles.push({ cycleId, root, hasClaimed }); + info !== null && flags.contributor ? await client.hasClaimed(cycleId, flags.contributor) : null; + cycles.push({ cycleId, info, hasClaimed }); } let contributor: ContributorStatus | null = null; @@ -137,12 +156,22 @@ export async function collectStatus( vesting, claimedCycles: cycles.filter((entry) => entry.hasClaimed === true).map((entry) => entry.cycleId), pendingCycles: cycles - .filter((entry) => entry.root !== null && entry.hasClaimed === false) + .filter( + (entry) => + entry.info !== null && entry.hasClaimed === false && isClaimWindowOpen(entry.info), + ) + .map((entry) => entry.cycleId), + challengeCycles: cycles + .filter( + (entry) => + entry.info !== null && entry.hasClaimed === false && !isClaimWindowOpen(entry.info), + ) .map((entry) => entry.cycleId), }; } let manifest: ManifestSummary | null = null; + let manifestError: string | null = null; try { const anchoredCycle = cycles[cycles.length - 1]?.cycleId ?? 0; const loaded = await loadManifest({ @@ -160,18 +189,25 @@ export async function collectStatus( dustRemainder: loaded.manifest.dustRemainder, manifest: loaded.manifest, }; - } catch { - // A manifest is optional context, not a prerequisite for status. - manifest = null; + } catch (error) { + // A missing manifest is optional context. A manifest that exists but does + // not parse is a real signal (tampering, bad generation) and must surface. + if (!(error instanceof ManifestNotFoundError)) { + manifestError = error instanceof Error ? error.message : String(error); + } } return { ...meta, tokenDecimals, reserveBalance, + availableFunds, + totalCredited, + vestingReserved, cycles, contributor, manifest, + manifestError, }; } @@ -179,6 +215,15 @@ function shortRoot(root: string | null): string { return root === null ? '-' : `${root.slice(0, 10)}...${root.slice(-8)}`; } +/** One-word state of a posted cycle, including the challenge window. */ +export function cycleStatusText(cycle: CycleStatus): string { + if (cycle.info === null) return 'not posted'; + if (cycle.info.claimsStarted) return 'claims started'; + if (isClaimWindowOpen(cycle.info)) return 'claims open'; + const opensAt = new Date(Number(cycle.info.claimsOpenAt) * 1000).toISOString(); + return `challenge window (opens ${opensAt})`; +} + export function printStatus(result: StatusResult): void { const decimals = result.tokenDecimals; @@ -191,7 +236,10 @@ export function printStatus(result: StatusResult): void { `${heading('Vault reserve')}\n${renderTable( ['metric', 'value'], [ - ['unallocated reserve', formatTokenAmountWithSeparators(result.reserveBalance, decimals)], + ['token balance (on hand)', formatTokenAmountWithSeparators(result.reserveBalance, decimals)], + ['credited to contributors', formatTokenAmountWithSeparators(result.totalCredited, decimals)], + ['vesting liability', formatTokenAmountWithSeparators(result.vestingReserved, decimals)], + ['available funds (sweepable)', formatTokenAmountWithSeparators(result.availableFunds, decimals)], ['token decimals', String(decimals)], ], )}\n\n`, @@ -206,13 +254,19 @@ export function printStatus(result: StatusResult): void { ['cycle', 'status', 'root', ...(result.contributor ? ['claimed'] : [])], result.cycles.map((cycle) => [ String(cycle.cycleId), - cycle.root === null ? 'not posted' : 'posted', - shortRoot(cycle.root), + cycleStatusText(cycle), + shortRoot(cycle.info?.root ?? null), ...(result.contributor ? [cycle.hasClaimed === null ? '-' : cycle.hasClaimed ? 'yes' : 'no'] : []), ]), - )}\n\n`, + )}\n`, + ); + process.stdout.write( + note( + 'A posted root is not claimable until its 24-hour challenge window elapses; ' + + 'the contract enforces this and rejects early claims with ClaimsNotYetOpen.\n\n', + ), ); } @@ -237,6 +291,12 @@ export function printStatus(result: StatusResult): void { ? 'none' : result.contributor.pendingCycles.join(', '), ], + [ + 'cycles in challenge window', + result.contributor.challengeCycles.length === 0 + ? 'none' + : result.contributor.challengeCycles.join(', '), + ], [ 'already claimed cycles', result.contributor.claimedCycles.length === 0 @@ -266,6 +326,12 @@ export function printStatus(result: StatusResult): void { `Run \`splitstream report --cycle ${result.manifest.cycleId} --manifest \` for the per-contributor breakdown.\n\n`, ), ); + } else if (result.manifestError !== null) { + process.stdout.write( + warn( + `the manifest was found but could not be parsed, so only chain state is shown: ${result.manifestError}`, + ) + '\n', + ); } else { process.stdout.write( warn( @@ -282,6 +348,23 @@ export function serializeStatus(result: StatusResult): string { { ...result, reserveBalance: result.reserveBalance.toString(), + availableFunds: result.availableFunds.toString(), + totalCredited: result.totalCredited.toString(), + vestingReserved: result.vestingReserved.toString(), + cycles: result.cycles.map((cycle) => ({ + cycleId: cycle.cycleId, + hasClaimed: cycle.hasClaimed, + info: cycle.info + ? { + root: cycle.info.root, + totalAmount: cycle.info.totalAmount.toString(), + postedAt: cycle.info.postedAt.toString(), + claimsOpenAt: cycle.info.claimsOpenAt.toString(), + claimsStarted: cycle.info.claimsStarted, + replaced: cycle.info.replaced, + } + : null, + })), manifest: result.manifest ? { source: result.manifest.source, diff --git a/packages/cli/src/report.ts b/packages/cli/src/report.ts index 1a60d71..7305341 100644 --- a/packages/cli/src/report.ts +++ b/packages/cli/src/report.ts @@ -1,4 +1,4 @@ -import { formatTokenAmount, truncateAddress, type Manifest } from '@splitstream/sdk'; +import { formatTokenAmount, truncateAddress, type CycleInfo, type Manifest } from '@splitstream/sdk'; import { writeFileSync } from 'node:fs'; /** @@ -41,6 +41,13 @@ export interface ReportInput { readonly generatedAt?: Date; /** stellar.expert account link for the vault, when the network is known. */ readonly accountExplorerUrl?: string | null; + /** + * The cycle as stored by the vault, when it could be read. Used to check the + * manifest against the chain instead of trusting the manifest alone. + */ + readonly cycleInfo?: CycleInfo | null; + /** Why {@link cycleInfo} is unavailable, when the read failed. */ + readonly cycleInfoError?: string; } const TRUNCATION_LEADING = 6; @@ -66,6 +73,8 @@ export function generateReport(input: ReportInput): string { const totalAllocated = sorted.reduce((sum, entry) => sum + entry.amount, 0n); const claimedCount = sorted.filter((entry) => entry.claimed).length; + const rootStatus = describeRootStatus(input); + const lines: string[] = []; lines.push(`# SplitStream payout report - cycle ${manifest.cycleId}`); @@ -86,8 +95,14 @@ export function generateReport(input: ReportInput): string { lines.push( `- **Dust remainder:** ${formatTokenAmount(manifest.dustRemainder, decimals)} ${unit}`, ); + lines.push(`- **Root check:** ${rootStatus.summary}`); lines.push(''); + if (rootStatus.warning !== null) { + lines.push(`> **Warning:** ${rootStatus.warning}`); + lines.push(''); + } + lines.push('## Allocations'); lines.push(''); lines.push('| GitHub | Stellar address | Issues closed | Amount | Claimed |'); @@ -126,6 +141,50 @@ export function generateReport(input: ReportInput): string { return `${lines.join('\n')}\n`; } +/** + * Compares the manifest root with the root the vault actually stores. + * + * A report is only evidence if its rows hash to the posted root, so a mismatch + * (or an unposted cycle) is called out in the report rather than silently + * printed as if the numbers were final. + */ +function describeRootStatus(input: ReportInput): { summary: string; warning: string | null } { + if (input.cycleInfoError !== undefined) { + return { + summary: 'not checked (the on-chain read failed)', + warning: `the vault could not be read, so the root was not verified: ${input.cycleInfoError}`, + }; + } + if (input.cycleInfo === undefined) { + return { summary: 'not checked (no on-chain read requested)', warning: null }; + } + if (input.cycleInfo === null) { + return { + summary: 'MISMATCH - cycle has no posted root on-chain', + warning: + `cycle ${input.manifest.cycleId} has no root posted on-chain. The allocations below come from ` + + 'the manifest only and cannot be claimed until the root is relayed.', + }; + } + if (input.cycleInfo.root !== input.manifest.merkleRoot) { + return { + summary: 'MISMATCH - manifest root differs from the on-chain root', + warning: + `the on-chain root is \`${input.cycleInfo.root}\` but the manifest says ` + + `\`${input.manifest.merkleRoot}\`. Claims built from this manifest would fail with InvalidProof. ` + + 'Fetch the current manifest (the root may have been challenged and replaced) before relying on ' + + 'this report.', + }; + } + const challenge = input.cycleInfo.claimsStarted + ? 'root is final' + : `challenge window closes ${new Date(Number(input.cycleInfo.claimsOpenAt) * 1000).toISOString()}`; + return { + summary: `matches the on-chain root (\`${input.cycleInfo.root}\`, ${challenge})`, + warning: null, + }; +} + /** Writes the report to disk. */ export function writeReport(path: string, content: string): void { writeFileSync(path, content, 'utf8'); diff --git a/packages/cli/test/claim.test.ts b/packages/cli/test/claim.test.ts index 2ce7f0f..bcbf377 100644 --- a/packages/cli/test/claim.test.ts +++ b/packages/cli/test/claim.test.ts @@ -30,6 +30,10 @@ interface FakeClientOptions { alreadyClaimed?: boolean; /** Address the fake client pretends to serve. */ contributor?: string; + /** Root the fake vault has stored; defaults to the fixture manifest's root. */ + onChainRoot?: string | null; + /** Unix time the fake cycle was posted; defaults to well outside the window. */ + postedAt?: bigint; } function fakeClient(options: FakeClientOptions = {}) { @@ -37,8 +41,23 @@ function fakeClient(options: FakeClientOptions = {}) { const submitted: string[] = []; const contributor = options.contributor ?? ADDRESS_A; + const onChainRoot = options.onChainRoot === undefined ? fixtureRoot() : options.onChainRoot; + const postedAt = options.postedAt ?? 1_700_000_000n; + const client = { getTokenDecimals: async () => 7, + getCycleInfo: async (cycleId: number) => + onChainRoot === null + ? null + : { + cycleId, + root: onChainRoot, + totalAmount: 100_000_000n, + postedAt, + claimsStarted: false, + replaced: false, + claimsOpenAt: postedAt + 86_400n, + }, hasClaimed: async () => options.alreadyClaimed ?? false, buildClaimTx: async () => { built.push('credit_claim'); @@ -177,6 +196,41 @@ describe('runClaim', () => { expect(output()).toContain('--force'); }); + it('refuses to claim a cycle that has not been posted on-chain', async () => { + vi.stubEnv('SPLITSTREAM_DEV_SECRET_KEY', SECRET_A); + const manifest = writeManifestFile({ cycleId: 7 }); + const { client, built } = fakeClient({ onChainRoot: null }); + + await expect( + runClaim(baseFlags(manifest), { client, confirm: async () => true }), + ).rejects.toThrow(/has no posted root on-chain/); + expect(built).toEqual([]); + }); + + it('refuses a proof against a root the vault has replaced', async () => { + vi.stubEnv('SPLITSTREAM_DEV_SECRET_KEY', SECRET_A); + const manifest = writeManifestFile({ cycleId: 7 }); + const { client, built } = fakeClient({ onChainRoot: 'ff'.repeat(32) }); + + await expect( + runClaim(baseFlags(manifest), { client, confirm: async () => true }), + ).rejects.toThrow(/on-chain root .* does not match the manifest root/); + expect(built).toEqual([]); + }); + + it('refuses to pay a fee during the 24h challenge window', async () => { + vi.stubEnv('SPLITSTREAM_DEV_SECRET_KEY', SECRET_A); + const manifest = writeManifestFile({ cycleId: 7 }); + const { client, built } = fakeClient({ + postedAt: BigInt(Math.floor(Date.now() / 1000) + 3_600), + }); + + await expect( + runClaim(baseFlags(manifest), { client, confirm: async () => true }), + ).rejects.toThrow(/24-hour challenge window/); + expect(built).toEqual([]); + }); + it('exits before signing when the cycle was already claimed', async () => { vi.stubEnv('SPLITSTREAM_DEV_SECRET_KEY', SECRET_A); const manifest = writeManifestFile({ cycleId: 7 }); diff --git a/packages/cli/test/report.test.ts b/packages/cli/test/report.test.ts index 58b4fc1..2de2add 100644 --- a/packages/cli/test/report.test.ts +++ b/packages/cli/test/report.test.ts @@ -104,6 +104,49 @@ describe('generateReport', () => { expect(report({ tokenSymbol: undefined })).toContain('10 tokens'); }); + it('records that the root matches the vault when the read succeeded', () => { + const manifest = buildManifest({ cycleId: 3 }); + const content = report({ + manifest, + cycleInfo: { + cycleId: 3, + root: manifest.merkleRoot, + totalAmount: 10_000_000n, + postedAt: 1_700_000_000n, + claimsStarted: false, + replaced: false, + claimsOpenAt: 1_700_086_400n, + }, + }); + expect(content).toContain('- **Root check:** matches the on-chain root'); + expect(content).toContain('challenge window closes 2023-11-15T22:13:20.000Z'); + expect(content).not.toContain('> **Warning:**'); + }); + + it('warns loudly when the on-chain root differs from the manifest', () => { + const manifest = buildManifest({ cycleId: 3 }); + const content = report({ + manifest, + cycleInfo: { + cycleId: 3, + root: 'ab'.repeat(32), + totalAmount: 10_000_000n, + postedAt: 1_700_000_000n, + claimsStarted: true, + replaced: true, + claimsOpenAt: 1_700_086_400n, + }, + }); + expect(content).toContain('- **Root check:** MISMATCH'); + expect(content).toContain('> **Warning:** the on-chain root is'); + expect(content).toContain('would fail with InvalidProof'); + }); + + it('warns when the cycle has no posted root or could not be read', () => { + expect(report({ cycleInfo: null })).toContain('has no root posted on-chain'); + expect(report({ cycleInfoError: 'RPC unavailable' })).toContain('RPC unavailable'); + }); + it('handles a cycle with no allocations', () => { const content = report({ entries: [] }); expect(content).toContain('- **Contributors:** 0'); diff --git a/packages/cli/test/status.test.ts b/packages/cli/test/status.test.ts index 6a8b111..3edf7ab 100644 --- a/packages/cli/test/status.test.ts +++ b/packages/cli/test/status.test.ts @@ -1,4 +1,8 @@ -import { SplitStreamClient } from '@splitstream/sdk'; +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { SplitStreamClient, type CycleInfo } from '@splitstream/sdk'; import { describe, expect, it } from 'vitest'; import { @@ -18,6 +22,17 @@ import { const ROOT_3 = 'ab'.repeat(32); +/** A posted cycle whose 24h challenge window has long elapsed. */ +const INFO_3: CycleInfo = { + cycleId: 3, + root: ROOT_3, + totalAmount: 100_000_000n, + postedAt: 1_700_000_000n, + claimsStarted: false, + replaced: false, + claimsOpenAt: 1_700_086_400n, +}; + /** * Only the methods `status` calls are implemented, and the cast is deliberate: * the point of these tests is the command's decisions, not the RPC plumbing @@ -27,7 +42,10 @@ function fakeClient(overrides: Record = {}): SplitStreamClient return { getTokenDecimals: async () => 7, getReserveBalance: async () => 5_000_000_000n, - getCycleRoot: async (cycleId: number) => (cycleId === 3 ? ROOT_3 : null), + getTotalCredited: async () => 12_345_678n, + getVestingReserved: async () => 9_000_000n, + getAvailableFunds: async () => 4_978_654_322n, + getCycleInfo: async (cycleId: number) => (cycleId === 3 ? INFO_3 : null), hasClaimed: async (cycleId: number, address: string) => cycleId === 3 && address === ADDRESS_A, getBalance: async () => 12_345_678n, getVesting: async () => ({ @@ -77,9 +95,13 @@ describe('collectStatus', () => { expect(result.network).toBe('testnet'); expect(result.tokenDecimals).toBe(7); expect(result.reserveBalance).toBe(5_000_000_000n); - expect(result.cycles).toEqual([{ cycleId: 3, root: ROOT_3, hasClaimed: null }]); + expect(result.availableFunds).toBe(4_978_654_322n); + expect(result.totalCredited).toBe(12_345_678n); + expect(result.vestingReserved).toBe(9_000_000n); + expect(result.cycles).toEqual([{ cycleId: 3, info: INFO_3, hasClaimed: null }]); expect(result.contributor).toBeNull(); expect(result.manifest?.contributorCount).toBe(3); + expect(result.manifestError).toBeNull(); }); it('adds the contributor position and splits claimed from pending cycles', async () => { @@ -90,6 +112,7 @@ describe('collectStatus', () => { expect(result.contributor?.balance).toBe(12_345_678n); expect(result.contributor?.claimedCycles).toEqual([3]); expect(result.contributor?.pendingCycles).toEqual([]); + expect(result.contributor?.challengeCycles).toEqual([]); expect(result.contributor?.vesting?.startLedger).toBe(100); }); @@ -100,6 +123,20 @@ describe('collectStatus', () => { expect(result.contributor?.claimedCycles).toEqual([]); }); + it('separates cycles still inside the 24h challenge window from claimable ones', async () => { + const future = BigInt(Math.floor(Date.now() / 1000) + 3_600); + const client = fakeClient({ + getCycleInfo: async (cycleId: number) => + cycleId === 3 + ? { ...INFO_3, postedAt: future, claimsOpenAt: future + 86_400n } + : null, + hasClaimed: async () => false, + }); + const result = await collectStatus(client, { cycle: '3', contributor: ADDRESS_A }, META); + expect(result.contributor?.pendingCycles).toEqual([]); + expect(result.contributor?.challengeCycles).toEqual([3]); + }); + it('does not query claim status for a contributor when no root is posted', async () => { let called = false; const client = fakeClient({ @@ -111,6 +148,7 @@ describe('collectStatus', () => { const result = await collectStatus(client, { cycle: '9', contributor: ADDRESS_A }, META); expect(called).toBe(false); expect(result.cycles[0]?.hasClaimed).toBeNull(); + expect(result.cycles[0]?.info).toBeNull(); }); it('treats a missing manifest as "no extra context" rather than an error', async () => { @@ -120,6 +158,18 @@ describe('collectStatus', () => { META, ); expect(result.manifest).toBeNull(); + expect(result.manifestError).toBeNull(); + }); + + it('surfaces a malformed manifest instead of pretending it is missing', async () => { + const directory = mkdtempSync(join(tmpdir(), 'splitstream-bad-manifest-')); + const path = join(directory, 'cycle-3.json'); + writeFileSync(path, '{"cycleId": 3, "entries": "not-an-array"}', 'utf8'); + + const result = await collectStatus(fakeClient(), { cycle: '3', manifest: path }, META); + + expect(result.manifest).toBeNull(); + expect(result.manifestError).toMatch(/entries must be an array/); }); }); @@ -132,6 +182,14 @@ describe('serializeStatus', () => { ); const parsed = JSON.parse(serializeStatus(result)) as Record; expect(parsed.reserveBalance).toBe('5000000000'); + expect(parsed.availableFunds).toBe('4978654322'); + expect(parsed.totalCredited).toBe('12345678'); + expect(parsed.vestingReserved).toBe('9000000'); + + const cycles = parsed.cycles as Array>; + const info = cycles[0]?.info as Record; + expect(info.totalAmount).toBe('100000000'); + expect(info.claimsOpenAt).toBe('1700086400'); const contributor = parsed.contributor as Record; expect(contributor.balance).toBe('12345678'); diff --git a/packages/sdk/README.md b/packages/sdk/README.md index a830795..f407475 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -29,9 +29,11 @@ const client = new SplitStreamClient({ }); const balance = await client.getBalance(address); // bigint, base units +const info = await client.getCycleInfo(3); // CycleInfo, or null if unposted const root = await client.getCycleRoot(3); // lowercase hex, or null const claimed = await client.hasClaimed(3, address); const decimals = await client.getTokenDecimals(); // read from the token contract +const free = await client.getAvailableFunds(); // balance - liabilities const tx = await client.buildClaimTx(address, 3, amount, proof); // unsigned const signedXdr = await myWallet.sign(tx); // you sign it @@ -59,11 +61,17 @@ Reads are read-only simulations. They need no funded account. | Method | Returns | | --- | --- | | `getBalance(contributor)` | Claimable balance in the vault, in base units | +| `getCycleInfo(cycleId)` | The vault's `CycleInfo` (`root`, `totalAmount`, `postedAt`, `claimsStarted`, `replaced`, `claimsOpenAt`), or `null` if unposted | | `getCycleRoot(cycleId)` | Published Merkle root, lowercase hex, or `null` if unposted | | `hasClaimed(cycleId, contributor)` | Whether that contributor has pulled that cycle | | `getVesting(contributor)` | `VestingInfo`, or `null` when there is no schedule | | `getTokenDecimals()` | Decimals read from the token contract | -| `getReserveBalance()` | The vault's own token balance, reserved for future cycles | +| `getReserveBalance()` | The vault's total token balance, including credited and vesting liabilities | +| `getTotalCredited()` | Sum of outstanding contributor pull-payment balances | +| `getVestingReserved()` | Outstanding vesting liability (`sum(total - claimed)`) | +| `getAvailableFunds()` | Tokens above both liabilities — the most a sweep can move | + +Cycle ids are `u64` on-chain and the client encodes them that way. A posted root enters a 24-hour challenge window before claims open; check `isClaimWindowOpen(info)` before submitting, or let the contract reject the claim with `ClaimsNotYetOpen`. ### Unsigned transactions diff --git a/packages/sdk/package.json b/packages/sdk/package.json index ffa7d94..1c95543 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@splitstream/sdk", - "version": "0.1.1", + "version": "0.2.0", "description": "Thin, typed client for the deployed splitstream-core contract. Browser-safe: no CLI-only dependencies.", "license": "MIT", "repository": { diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index 9624e2a..d8a7de4 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -10,7 +10,7 @@ import { } from '@stellar/stellar-sdk'; import { contractError, SplitStreamError, toSplitStreamError } from './errors.js'; -import { parseVesting, type VestingInfo } from './types.js'; +import { parseCycleInfo, parseVesting, type CycleInfo, type VestingInfo } from './types.js'; import { addressToScVal, findContractErrorCode, @@ -19,18 +19,20 @@ import { proofToScVal, scValToBigInt, scValToBool, - scValToHexOrNull, scValToNativeValue, - u32ToScVal, + u64ToScVal, xdr, } from './xdr.js'; /** Vault contract entrypoint names. Kept together so they are easy to audit. */ export const VAULT_METHODS = { getBalance: 'get_balance', - getCycleRoot: 'get_cycle_root', + getCycleInfo: 'get_cycle_info', hasClaimed: 'has_claimed', getVesting: 'get_vesting', + getTotalCredited: 'get_total_credited', + getVestingReserved: 'get_vesting_reserved', + getAvailableFunds: 'get_available_funds', creditClaim: 'credit_claim', withdraw: 'withdraw', claimVested: 'claim_vested', @@ -198,16 +200,26 @@ export class SplitStreamClient { return scValToBigInt(retval, 'get_balance'); } - /** Published Merkle root for `cycleId`, lowercase hex, or `null` if unposted. */ - async getCycleRoot(cycleId: number): Promise { + /** + * Challenge-window state for `cycleId`, or `null` if no root is posted. + * + * `splitstream-core` exposes `get_cycle_info(u64) -> Option`; the + * old `get_cycle_root` entrypoint does not exist on the deployed vault. + */ + async getCycleInfo(cycleId: number): Promise { const retval = await this.simulateRead( this.vault, - VAULT_METHODS.getCycleRoot, - [u32ToScVal(cycleId)], - `cycle ${cycleId} root`, + VAULT_METHODS.getCycleInfo, + [u64ToScVal(cycleId)], + `cycle ${cycleId} info`, ); if (isVoidScVal(retval)) return null; - return scValToHexOrNull(retval, 'get_cycle_root'); + return parseCycleInfo(scValToNativeValue(retval), cycleId); + } + + /** Published Merkle root for `cycleId`, lowercase hex, or `null` if unposted. */ + async getCycleRoot(cycleId: number): Promise { + return (await this.getCycleInfo(cycleId))?.root ?? null; } /** Whether `contributor` has already pulled their `cycleId` allocation. */ @@ -216,7 +228,7 @@ export class SplitStreamClient { const retval = await this.simulateRead( this.vault, VAULT_METHODS.hasClaimed, - [u32ToScVal(cycleId), addressToScVal(contributor)], + [u64ToScVal(cycleId), addressToScVal(contributor)], `claim status of ${contributor} for cycle ${cycleId}`, ); return scValToBool(retval, 'has_claimed'); @@ -251,19 +263,57 @@ export class SplitStreamClient { } /** - * The vault's own token balance - i.e. the reserve still available for - * future cycles. Read straight from the token contract. + * The vault's own token balance. This is the total on hand, not free funds: + * it includes balances already credited to contributors and unvested + * schedules. Use {@link getAvailableFunds} for the unencumbered amount. */ async getReserveBalance(): Promise { const retval = await this.simulateRead( this.token, TOKEN_METHODS.balance, [addressToScVal(this.vaultContractId)], - 'vault reserve balance', + 'vault token balance', ); return scValToBigInt(retval, 'token.balance(vault)'); } + /** Sum of every contributor's outstanding pull-payment balance. */ + async getTotalCredited(): Promise { + const retval = await this.simulateRead( + this.vault, + VAULT_METHODS.getTotalCredited, + [], + 'total credited balance', + ); + return scValToBigInt(retval, 'get_total_credited'); + } + + /** Amount still owed under vesting schedules (`sum(total - claimed)`). */ + async getVestingReserved(): Promise { + const retval = await this.simulateRead( + this.vault, + VAULT_METHODS.getVestingReserved, + [], + 'vesting liability', + ); + return scValToBigInt(retval, 'get_vesting_reserved'); + } + + /** + * Tokens the vault controls above its liabilities - the most a sweep can + * move. Read from the vault, which computes `balance - (credited + vesting)` + * on-ledger rather than trusting a client-side subtraction. + */ + async getAvailableFunds(): Promise { + const retval = await this.simulateRead( + this.vault, + VAULT_METHODS.getAvailableFunds, + [], + 'available funds', + ); + return scValToBigInt(retval, 'get_available_funds'); + } + // ------------------------------------------------- unsigned transactions private async prepareInvocation( @@ -327,7 +377,7 @@ export class SplitStreamClient { return this.prepareInvocation( contributor, VAULT_METHODS.creditClaim, - [addressToScVal(contributor), u32ToScVal(cycleId), i128ToScVal(amount), proofToScVal(proof)], + [addressToScVal(contributor), u64ToScVal(cycleId), i128ToScVal(amount), proofToScVal(proof)], `credit_claim for cycle ${cycleId}`, ); } diff --git a/packages/sdk/src/errors.ts b/packages/sdk/src/errors.ts index 3e37648..096c93b 100644 --- a/packages/sdk/src/errors.ts +++ b/packages/sdk/src/errors.ts @@ -17,23 +17,22 @@ export const SPLITSTREAM_CONTRACT_ERRORS: Readonly> = Obj 1: 'NotInitialized', 2: 'AlreadyInitialized', 3: 'Unauthorized', - 4: 'Paused', + 4: 'CycleAlreadyPosted', 5: 'CycleNotFound', - 6: 'CycleAlreadyPosted', - 7: 'InvalidMerkleRoot', - 8: 'InvalidProof', - 9: 'AlreadyClaimed', - 10: 'NothingToClaim', - 11: 'InvalidAmount', - 12: 'Overflow', - 13: 'VestingNotFound', - 14: 'VestingNotStarted', - 15: 'VestingNotComplete', - 16: 'InvalidContributor', - 17: 'InvalidCycleId', - 18: 'ReentrancyDetected', - 19: 'RootNotSet', - 20: 'InsufficientReserve', + 6: 'AlreadyClaimed', + 7: 'InvalidProof', + 8: 'InsufficientBalance', + 9: 'InvalidShareTotal', + 10: 'SweepNotReady', + 11: 'NoSweepPending', + 12: 'InvalidAmount', + 13: 'ClaimsNotYetOpen', + 14: 'ChallengeWindowClosed', + 15: 'RootAlreadyReplaced', + 16: 'ClaimsAlreadyStarted', + 17: 'NoVestingSchedule', + 18: 'InsufficientFreeFunds', + 19: 'CycleTotalExceeded', }); /** Name for a contract error code, or a clearly-marked unknown name. */ diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index aaba46b..ef3c8ca 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -23,10 +23,13 @@ export { // --- domain types and parsers ---------------------------------------------- export { + CLAIM_CHALLENGE_WINDOW_SECS, ManifestParseError, findManifestEntry, + isClaimWindowOpen, isValidContractId, isValidStellarAddress, + parseCycleInfo, parseManifest, parseVesting, type CycleInfo, @@ -88,6 +91,7 @@ export { scValToHexOrNull, scValToNativeValue, u32ToScVal, + u64ToScVal, xdr, } from './xdr.js'; diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index 0f4b747..f9b68d4 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -73,12 +73,100 @@ export interface Manifest { readonly merkleRoot: string; } -/** Result of a single contributor's `has_claimed` lookup. */ +/** Challenge window before a posted cycle root becomes claimable, in seconds. */ +export const CLAIM_CHALLENGE_WINDOW_SECS = 86_400n; + +/** + * The vault's `CycleInfo` record, decoded from `get_cycle_info`. + * + * Mirrors `splitstream-core`'s `CycleInfo` exactly: a posted root is not + * claimable until `CLAIM_CHALLENGE_WINDOW_SECS` have elapsed since `postedAt`, + * and the first successful claim sets `claimsStarted`, which finalizes it. + */ export interface CycleInfo { + /** Cycle id the record was read for. */ readonly cycleId: number; - /** Merkle root for the cycle, lowercase hex, or `null` if not posted. */ - readonly root: string | null; - readonly hasClaimed: boolean; + /** Merkle root for the cycle, lowercase hex. */ + readonly root: string; + /** Total amount the manifest allocates for this cycle, in base units. */ + readonly totalAmount: bigint; + /** Unix timestamp (seconds) the root was posted. */ + readonly postedAt: bigint; + /** True after the first successful `credit_claim`; locks out replacement. */ + readonly claimsStarted: boolean; + /** True once the root has been challenged and replaced (one replacement max). */ + readonly replaced: boolean; + /** Unix timestamp (seconds) at which claims open: `postedAt + 86_400`. */ + readonly claimsOpenAt: bigint; +} + +/** + * True once the challenge window has elapsed (or a claim has already started). + * + * @param nowSeconds - current Unix time; defaults to the local clock, which is + * the caller's best approximation of ledger time. The contract remains the + * authority and returns `ClaimsNotYetOpen` before the window closes. + */ +export function isClaimWindowOpen( + info: CycleInfo, + nowSeconds: bigint = BigInt(Math.floor(Date.now() / 1000)), +): boolean { + return info.claimsStarted || nowSeconds >= info.claimsOpenAt; +} + +/** + * Decodes the `Option` returned by `get_cycle_info`. + * + * Accepts the map/struct form Soroban decodes contract types into (snake_case + * or camelCase keys), and returns `null` for a cycle that has not been posted. + */ +export function parseCycleInfo(value: unknown, cycleId: number): CycleInfo | null { + if (value === null || value === undefined) return null; + if (typeof value === 'boolean' || typeof value === 'string' || typeof value === 'number') { + return null; + } + + if (value instanceof Map) { + return parseCycleInfo(Object.fromEntries(value), cycleId); + } + + const record = asRecord(value, 'get_cycle_info result'); + const root = pick(record, ['root']); + const total = pick(record, ['totalAmount', 'total_amount', 'total']); + const postedAt = pick(record, ['postedAt', 'posted_at']); + const claimsStarted = pick(record, ['claimsStarted', 'claims_started']); + const replaced = pick(record, ['replaced']); + + if (root === undefined || total === undefined || postedAt === undefined) { + throw new ManifestParseError( + 'get_cycle_info returned a record without root, total_amount and posted_at', + ); + } + + const rootHex = + root instanceof Uint8Array + ? Array.from(root, (byte) => byte.toString(16).padStart(2, '0')).join('') + : typeof root === 'string' + ? root.toLowerCase().replace(/^0x/, '') + : ''; + if (!/^[0-9a-f]{64}$/.test(rootHex)) { + throw new ManifestParseError('get_cycle_info returned a root that is not 32 bytes'); + } + + const postedAtValue = asBigIntAmount(postedAt, 'cycle.postedAt'); + if (postedAtValue < 0n) { + throw new ManifestParseError('get_cycle_info returned a negative posted_at'); + } + + return { + cycleId, + root: rootHex, + totalAmount: asBigIntAmount(total, 'cycle.totalAmount'), + postedAt: postedAtValue, + claimsStarted: claimsStarted === true, + replaced: replaced === true, + claimsOpenAt: postedAtValue + CLAIM_CHALLENGE_WINDOW_SECS, + }; } /** Vesting schedule as returned by the vault's `get_vesting`. */ diff --git a/packages/sdk/src/xdr.ts b/packages/sdk/src/xdr.ts index 558bdc4..7a28310 100644 --- a/packages/sdk/src/xdr.ts +++ b/packages/sdk/src/xdr.ts @@ -16,7 +16,7 @@ export function addressToScVal(address: string): xdr.ScVal { return nativeToScVal(address, { type: 'address' }); } -/** Encodes a `u32` argument (cycle ids, ledger numbers). */ +/** Encodes a `u32` argument (ledger numbers, basis points). */ export function u32ToScVal(value: number): xdr.ScVal { if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) { throw new SplitStreamError(`expected a u32, received ${value}`, { details: `value=${value}` }); @@ -24,6 +24,21 @@ export function u32ToScVal(value: number): xdr.ScVal { return nativeToScVal(value, { type: 'u32' }); } +/** + * Encodes a `u64` argument. Cycle ids are `u64` in splitstream-core, not `u32`: + * encoding them as u32 produces a type mismatch at simulation time. + */ +export function u64ToScVal(value: number | bigint): xdr.ScVal { + if (typeof value === 'number' && !Number.isSafeInteger(value)) { + throw new SplitStreamError(`expected a u64, received a non-safe integer ${value}`); + } + const normalized = typeof value === 'bigint' ? value : BigInt(value); + if (normalized < 0n || normalized > 0xffffffffffffffffn) { + throw new SplitStreamError(`expected a u64, received ${normalized.toString()}`); + } + return nativeToScVal(normalized, { type: 'u64' }); +} + /** Encodes an `i128` argument. Token amounts are always bigint. */ export function i128ToScVal(value: bigint): xdr.ScVal { return nativeToScVal(value, { type: 'i128' }); diff --git a/packages/sdk/test/client.test.ts b/packages/sdk/test/client.test.ts index afe6ef5..d9b47a0 100644 --- a/packages/sdk/test/client.test.ts +++ b/packages/sdk/test/client.test.ts @@ -88,6 +88,30 @@ function signedEnvelopeXdr(): string { return transaction.toEnvelope().toXdr('base64'); } +/** The real `CycleInfo` wire shape: a ScVal map with symbol keys. */ +function cycleInfoScVal(overrides: { root?: Uint8Array; total?: bigint; postedAt?: bigint } = {}): xdr.ScVal { + const root = overrides.root ?? new Uint8Array(32).fill(7); + return xdr.ScVal.scvMap([ + new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol('root'), val: xdr.ScVal.scvBytes(root) }), + new xdr.ScMapEntry({ + key: xdr.ScVal.scvSymbol('total_amount'), + val: nativeToScVal(overrides.total ?? 5_000_000_000n, { type: 'i128' }), + }), + new xdr.ScMapEntry({ + key: xdr.ScVal.scvSymbol('posted_at'), + val: nativeToScVal(overrides.postedAt ?? 1_700_000_000n, { type: 'u64' }), + }), + new xdr.ScMapEntry({ + key: xdr.ScVal.scvSymbol('claims_started'), + val: nativeToScVal(false, { type: 'bool' }), + }), + new xdr.ScMapEntry({ + key: xdr.ScVal.scvSymbol('replaced'), + val: nativeToScVal(false, { type: 'bool' }), + }), + ]); +} + function simulationError(error: string): rpc.Api.SimulateTransactionResponse { return { _parsed: true, @@ -122,17 +146,26 @@ describe('read methods', () => { expect(simulate).not.toHaveBeenCalled(); }); - it('returns null for an unposted cycle root', async () => { + it('returns null for an unposted cycle and keeps getCycleRoot compatible', async () => { const subject = client({ simulateTransaction: async () => simulationSuccess(xdr.ScVal.scvVoid()), }); + await expect(subject.getCycleInfo(3)).resolves.toBeNull(); await expect(subject.getCycleRoot(3)).resolves.toBeNull(); }); - it('hex-encodes a posted cycle root', async () => { + it('decodes get_cycle_info, including the challenge window', async () => { const subject = client({ - simulateTransaction: async () => - simulationSuccess(xdr.ScVal.scvBytes(new Uint8Array(32).fill(7))), + simulateTransaction: async () => simulationSuccess(cycleInfoScVal()), + }); + await expect(subject.getCycleInfo(3)).resolves.toEqual({ + cycleId: 3, + root: '07'.repeat(32), + totalAmount: 5_000_000_000n, + postedAt: 1_700_000_000n, + claimsStarted: false, + replaced: false, + claimsOpenAt: 1_700_086_400n, }); await expect(subject.getCycleRoot(3)).resolves.toBe('07'.repeat(32)); }); @@ -193,14 +226,35 @@ describe('read methods', () => { await expect(subject2.getReserveBalance()).resolves.toBe(reserve); }); + it('reads the vault liability ledger and free funds', async () => { + const methods: string[] = []; + const subject = client({ + simulateTransaction: async (tx) => { + const operation = tx.operations[0]; + if ( + operation?.type === 'invokeHostFunction' && + operation.func.type === 'hostFunctionTypeInvokeContract' + ) { + methods.push(operation.func.invokeContract.functionName.toString()); + } + return simulationSuccess(nativeToScVal(123_456n, { type: 'i128' })); + }, + }); + + await expect(subject.getTotalCredited()).resolves.toBe(123_456n); + await expect(subject.getVestingReserved()).resolves.toBe(123_456n); + await expect(subject.getAvailableFunds()).resolves.toBe(123_456n); + expect(methods).toEqual(['get_total_credited', 'get_vesting_reserved', 'get_available_funds']); + }); + it('surfaces a contract error code from a failed simulation', async () => { const subject = client({ simulateTransaction: async () => - simulationError('HostError: Error(Contract, #8)\ncontract called trap'), + simulationError('HostError: Error(Contract, #7)\ncontract called trap'), }); await expect(subject.getBalance(CONTRIBUTOR)).rejects.toMatchObject({ name: 'SplitStreamError', - code: 8, + code: 7, codeName: 'InvalidProof', }); }); @@ -226,6 +280,11 @@ describe('buildClaimTx', () => { expect(operation.func.invokeContract.functionName.toString()).toBe('credit_claim'); expect(operation.func.invokeContract.contractAddress.toXdr).toBeTypeOf('function'); + // splitstream-core declares cycle_id as u64. A u32 here fails at + // simulation time, so the encoding is pinned explicitly. + const args = operation.func.invokeContract.args; + expect(args?.[1]?.type).toBe('scvU64'); + // The SDK never signs: no decorated signatures on the assembled tx. expect(tx.signatures).toHaveLength(0); @@ -306,7 +365,7 @@ describe('submitSigned', () => { body: xdr.ContractEventBody.v0( new xdr.ContractEventV0({ topics: [], - data: xdr.ScVal.scvError(xdr.ScError.sceContract(9)), + data: xdr.ScVal.scvError(xdr.ScError.sceContract(6)), }), ), }), @@ -324,7 +383,7 @@ describe('submitSigned', () => { }); await expect(subject.submitSigned(ENVELOPE)).rejects.toMatchObject({ - code: 9, + code: 6, codeName: 'AlreadyClaimed', }); }); diff --git a/packages/sdk/test/testnet.integration.test.ts b/packages/sdk/test/testnet.integration.test.ts new file mode 100644 index 0000000..667fbd7 --- /dev/null +++ b/packages/sdk/test/testnet.integration.test.ts @@ -0,0 +1,72 @@ +import { Networks } from '@stellar/stellar-sdk'; +import { describe, expect, it } from 'vitest'; + +import { SplitStreamClient } from '../src/index.js'; + +/** + * Live Testnet smoke test for the deployed vault ABI. + * + * It is gated so `npm test` never needs the network: it only runs when + * `SPLITSTREAM_TESTNET_E2E=1` is set. Reads are free simulations, so no secret + * key is involved and nothing is submitted. + * + * SPLITSTREAM_TESTNET_E2E=1 npm test -w @splitstream/sdk + * + * `SPLITSTREAM_TOKEN_CONTRACT_ID` is optional; the token-dependent assertions + * only run when it is set. + */ +const ENABLED = process.env.SPLITSTREAM_TESTNET_E2E === '1'; + +const RPC_URL = process.env.SPLITSTREAM_RPC_URL ?? 'https://soroban-testnet.stellar.org'; +const VAULT_ID = + process.env.SPLITSTREAM_VAULT_CONTRACT_ID ?? + 'CB456KGXH4233BHW5BUEJMN6OJ4ZMWMPP3OXJU5HVQ2T2F7A7XHWLTAT'; +const TOKEN_ID = process.env.SPLITSTREAM_TOKEN_CONTRACT_ID; + +const HEX_ROOT = /^[0-9a-f]{64}$/; + +describe.skipIf(!ENABLED)('live Testnet vault reads', () => { + const client = new SplitStreamClient({ + rpcUrl: RPC_URL, + networkPassphrase: process.env.SPLITSTREAM_NETWORK_PASSPHRASE ?? Networks.TESTNET, + vaultContractId: VAULT_ID, + tokenContractId: TOKEN_ID ?? VAULT_ID, + pollTimeoutMs: 30_000, + }); + + it('decodes get_cycle_info for the first cycle', async () => { + const info = await client.getCycleInfo(0); + if (info === null) return; + expect(info.cycleId).toBe(0); + expect(info.root).toMatch(HEX_ROOT); + expect(info.totalAmount).toBeGreaterThanOrEqual(0n); + expect(info.postedAt).toBeGreaterThan(0n); + // The alias the SDK kept for compatibility reads the same record. + await expect(client.getCycleRoot(0)).resolves.toBe(info.root); + }); + + it('reads the liability entrypoints the vault exposes', async () => { + const [credited, vesting, available] = await Promise.all([ + client.getTotalCredited(), + client.getVestingReserved(), + client.getAvailableFunds(), + ]); + expect(credited).toBeGreaterThanOrEqual(0n); + expect(vesting).toBeGreaterThanOrEqual(0n); + expect(available).toBeGreaterThanOrEqual(0n); + }); + + it.skipIf(!TOKEN_ID)('reads the token and reconciles on-hand funds with liabilities', async () => { + const [decimals, onHand, credited, vesting, available] = await Promise.all([ + client.getTokenDecimals(), + client.getReserveBalance(), + client.getTotalCredited(), + client.getVestingReserved(), + client.getAvailableFunds(), + ]); + expect(decimals).toBeGreaterThanOrEqual(0); + expect(decimals).toBeLessThanOrEqual(38); + // `balance = credited + vesting + free funds`, as the vault computes it. + expect(onHand).toBe(credited + vesting + available); + }); +}); diff --git a/packages/sdk/test/xdr.test.ts b/packages/sdk/test/xdr.test.ts index 2230303..f356490 100644 --- a/packages/sdk/test/xdr.test.ts +++ b/packages/sdk/test/xdr.test.ts @@ -14,6 +14,7 @@ import { scValToHexOrNull, scValToNativeValue, u32ToScVal, + u64ToScVal, } from '../src/index.js'; import { ADDRESS_A } from './fixtures.js'; @@ -41,12 +42,22 @@ describe('address and integer encoding', () => { expect(scValToBigInt(encoded, 'test')).toBe(amount); }); - it('rejects a non-u32 cycle id', () => { + it('rejects a non-u32 value', () => { expect(() => u32ToScVal(-1)).toThrow(SplitStreamError); expect(() => u32ToScVal(1.5)).toThrow(SplitStreamError); expect(() => u32ToScVal(2 ** 33)).toThrow(SplitStreamError); }); + it('encodes cycle ids as u64, the type splitstream-core declares', () => { + expect(u64ToScVal(0).type).toBe('scvU64'); + expect(u64ToScVal(7).type).toBe('scvU64'); + expect(u64ToScVal(0xffffffffn).type).toBe('scvU64'); + expect(u64ToScVal(0x1_0000_0000n).type).toBe('scvU64'); + expect(() => u64ToScVal(-1)).toThrow(SplitStreamError); + expect(() => u64ToScVal(1.5)).toThrow(SplitStreamError); + expect(() => u64ToScVal(2n ** 64n)).toThrow(SplitStreamError); + }); + it('decodes booleans and rejects mismatched types', () => { expect(scValToBool(nativeToScVal(true, { type: 'bool' }), 'test')).toBe(true); expect(() => scValToBool(nativeToScVal(1n, { type: 'i128' }), 'test')).toThrow(SplitStreamError);