Conversation
…IP. Includes description for smart contract invalidation when rev not found.
…into feat/eslint-fixes
…er-computer escrow support
TBC777 (and its programmable variants TBC777M / TBC777P) is a new, fully audited
TBC20 token implementation that can be **safely deposited into any escrow contract**
(even malicious or buggy ones) thanks to the new inner-computer feature.
Key guarantees (enforced entirely inside the token contract):
- No inflation is ever possible
- The token, not the escrow, is responsible for the no-inflation invariant
- Uses on-chain revision history audits (`computer.sync` + `computer.prev`)
to verify that total claimable/withdrawable amounts never exceed actual deposits
New files:
- `src/tbc20.ts` → base TBC20 fungible token (transfer, merge, burn + helper)
- `src/tbc777.ts` → original TBC777 with `deposit`/`claim` + `{claimable, status}`
- `src/tbc777m.ts` → TBC777M (multi-token array edition: `deposits`/`withdraws`)
- `src/tbc777p.ts` → TBC777P (programmable edition: `depositRevs`/`amountByWithdrawId`)
All variants support **arbitrary escrow logic** (e.g. chess games, auctions, lotteries)
while keeping the token side 100% secure.
Includes comprehensive test suites covering:
- happy paths, partial deposits/claims, multi-deposit scenarios
- full revision-history audits and double-finalization protection
- adversarial/malicious escrow tests
- edge cases and error handling
This lays the foundation for the upcoming programmable escrow feature.
The inner-computer sets `_rev` to the pre-broadcast revision (the value passed in `env`). Using `next` + `nextToken.escrowId` check makes atomic deposit flows (escrow.acceptDeposit → token.deposit in the same transaction) natural and reliable. Additional changes: - rename `withdrawRevs` → `withdrawn` (clearer intent) - simplify `computeWithdraw` reduce (single pass) - adapt NaiveEscrow, AtomicEscrow and Chess tests to true atomic deposit + withdrawal patterns - Chess now supports two-sided funding, turn-taking and winner payout in one escrow instance - add `ensureFunds` + `sleep` helpers and fix test setup Tests updated to cover the new atomic flows. No-inflation invariant preserved.
…These amounts are **only credited** when the revision passed to `withdraw()` *is* the last/final revision of the escrow (checked via `computer.last(rev)`). Primary use case: - One-time final payouts (e.g. winner-takes-all in games, auction settlement) - Safe token assignment when the escrow is finalized or **destroyed** (a player can spend the escrow UTXO in a non-BC transaction, making the current revision terminal and triggering `finalWithdraws`). The on-chain audit now enforces `deposits >= withdraws + finalWithdraws` across the entire prev-chain. The `finalWithdraws` audit is conservative (always counted from the supplied revision) while the runtime payout is strict (only if it really is the last revision). Updated: • Escrow interface & full documentation • `computeFinalWithdraw` / `computeFinalWithdraws` • `isValid` invariant check • All tests (NaiveEscrow, AtomicEscrow, chess example) The no-inflation guarantee remains 100 % enforced by the token contract alone.
- Bump `@types/mocha` from `^10.0.6` to `^10.0.10` - Add `chai-as-promised@^8.0.2` (enables fluent async/promise assertions such as `.eventually` in Mocha tests) - Add `"types": ["mocha"]` to `tsconfig.json` (explicitly includes Mocha globals and types for test files
…puter Feat/refactor inner computer
- Introduces full test coverage for the inflation-proof TBC777M token: • Setup/fixtures/deployment with fresh per-test wallets & modules • Core deposit flows (external + atomic patterns, balance deltas, escrowId recording) • Withdraw + on-chain audit (prev-chain walk, isValid, compute* helpers) • No-inflation invariant enforcement across history (deposits vs. withdraws/finalWithdraws) • Malicious escrow resistance (cross-escrow claims, fake deposits, fabricated withdraws) • finalWithdraws logic (last-revision only + conservative audit counting) • Replay protection, multi-root isolation, long-lived escrow history • Integration with inherited TBC20 methods (transfer/merge/burn) - Uses sleep() + isolated Computer instances to reliably handle mempool descendant limits - Marks chess-specific tests for migration to dedicated file - Retains original tbc777m.test.ts (naive/atomic/chess examples) for referenc This gives us exhaustive validation of the strong no-inflation guarantees and arbitrary-escrow compatibility promised in the TBC777M contract docs.
…s it possible to provision payouts that become active if the next owner of the escrow destroys the object.
Non-Error values thrown by libraries, async code or edge cases previously caused crashes or useless logs/responses when code assumed .message existed. This change adds consistent instanceof Error guards plus JSON.stringify (or String) fallbacks everywhere errors are logged or returned to clients—in app startup/shutdown, auth/accesslist/filter-ips middlewares, RPC action, SSE, and sync paths. Strict mode is now enabled in tsconfig.json. Dozens of functions were updated to return T | null, optional fields now prefer undefined over null, and tests received proper type annotations (plus a few strategic @ts-ignore cleanups). Remaining direct rpcClient usage was migrated to the unified RpcService in OutputAction and SyncBlockchainAction. Obsolete commented code was removed and config parsing (ports, intervals, log levels, ZMQ URL) received safe defaults. The net effect is a noticeably more defensive and maintainable node-secret service that fails less often at runtime and catches more problems at compile time.
Previously, every route handler duplicated verbose try/catch blocks that inconsistently logged errors and sent responses, often assuming .message existed on thrown values. Non-Error objects from libraries, async code or edge cases produced useless logs or generic 500s. This change introduces a proper AppError class (with statusCode, code and details) and a shared handleRouteError helper that uniformly handles AppError (respecting its status), Error instances and unknown values (via JSON.stringify) for all routes. parseParams now throws AppError for invalid methods/params so clients receive proper 4xx responses. Mempool cleanup received matching non-Error guards, and a few type/import cleanups were made.
…in-computer/monorepo into feat/TBC20-standardization
This change adds transaction support across the indexer to ensure consistency for critical paths. OutputAction.insertAndUpdateMod now wraps outputs/inputs insertion and mod propagation in a single pg-promise transaction. Reorg handling (orphan registration, block deletion, unconfirmation of inputs/outputs, and worker status reset) and mempool cleanup (stale marking, hard deletes) are similarly atomic. DAO and service layers were updated to accept an optional tx parameter (falling back to the default Db client for single-statement callers). New indexes were added on Output.blockHeight and Output.blockHash. PreparedStatement names were stabilized (removing random suffixes) and extensive transaction strategy comments were added for maintainability. The result prevents partial state (e.g. after crashes or during reorgs), improves reliability of object mod inheritance, and reduces risk in parallel sync workers.
This change strengthens atomic guarantees during reorg recovery and reduces unnecessary transaction nesting in mempool cleanup paths. Orphan block deletion plus input/output unconfirmation now run inside one Db.tx. Worker status reset and orphan processing are combined in a follow-up atomic transaction by extending register function to accept an optional tx (so it can be composed inside the recovery transaction instead of always creating its own). The Db.tx wrappers and tx parameter support were removed from the mempool stale-marking paths because those are now simple self-contained batch updates. The result eliminates windows for partial reorg state after crashes, keeps the DAO interface simple where full multi-table atomicity is not required, and improves sync reliability and maintainability.
This change strengthens atomic guarantees during reorg recovery. Orphan block recording and the full worker/tx status reset happen together as one atomic unit instead of two separate transactions. updateStatus was extended to accept an optional tx parameter so it can participate in a larger transaction without forcing its own Db.tx wrapper. Register of tx status was simplified to remove the conditional reuse-vs-new-transaction branching in favor of a uniform pattern. Error logging in zeromq was also cleaned up to use concise ternary expressions for Error vs. non-Error cases.
This change makes the RPC parameter parser support optional trailing arguments that are common in bitcoind (verbosity on getblock/getrawtransaction/getblockheader, etc.). Previously parseParams treated every entry in callSpec as strictly required and rejected both too few and too many parameters. This prevented legitimate calls from the public /rpc endpoint and forced awkward workarounds. The callSpec format was extended so that optional parameters can be marked with a trailing "?" (e.g. 'str int?'). parseParams now counts only the required parameters for the minimum check, silently accepts extra arguments (delegating final validation to the node), and correctly strips the "?" marker when looking up the coercion function. getBlockHeader was added to the PromisifiedRpcClient interface and to both the fallback and override specs. A new mocha setup hook (test/setup.ts) was introduced that sanitizes Error objects after each test, recursively handling BigInt, Symbol, Function, circular references and non-enumerable properties. .mocharc.json was updated to load it, so failures involving complex blockchain data now produce readable reports instead of serialization crashes. Minor dead-code removal and comment cleanups were performed in rest-client.ts and several lib-secret tests. The result is a more faithful and ergonomic RPC layer that matches real node behavior while preserving clear errors for missing required parameters and improving day-to-day test maintainability.
…into feat/TBC20-standardization
feat(node): Atomic reorg recovery, optional RPC params, and hardened error handling
Removed outdated comments regarding the TBC20 implementation and its compatibility.
Non-Error values thrown by libraries, async code or edge cases previously caused crashes or useless logs/responses when code assumed .message existed. This change adds consistent instanceof Error guards plus JSON.stringify (or String) fallbacks everywhere errors are logged or returned to clients—in app startup/shutdown, auth/accesslist/filter-ips middlewares, RPC action, SSE, and sync paths. Strict mode is now enabled in tsconfig.json. Dozens of functions were updated to return T | null, optional fields now prefer undefined over null, and tests received proper type annotations (plus a few strategic @ts-ignore cleanups). Remaining direct rpcClient usage was migrated to the unified RpcService in OutputAction and SyncBlockchainAction. Obsolete commented code was removed and config parsing (ports, intervals, log levels, ZMQ URL) received safe defaults. The net effect is a noticeably more defensive and maintainable node-secret service that fails less often at runtime and catches more problems at compile time.
Previously, every route handler duplicated verbose try/catch blocks that inconsistently logged errors and sent responses, often assuming .message existed on thrown values. Non-Error objects from libraries, async code or edge cases produced useless logs or generic 500s. This change introduces a proper AppError class (with statusCode, code and details) and a shared handleRouteError helper that uniformly handles AppError (respecting its status), Error instances and unknown values (via JSON.stringify) for all routes. parseParams now throws AppError for invalid methods/params so clients receive proper 4xx responses. Mempool cleanup received matching non-Error guards, and a few type/import cleanups were made.
This change strengthens atomic guarantees during reorg recovery. Orphan block recording and the full worker/tx status reset happen together as one atomic unit instead of two separate transactions. updateStatus was extended to accept an optional tx parameter so it can participate in a larger transaction without forcing its own Db.tx wrapper. Register of tx status was simplified to remove the conditional reuse-vs-new-transaction branching in favor of a uniform pattern. Error logging in zeromq was also cleaned up to use concise ternary expressions for Error vs. non-Error cases.
This change makes the RPC parameter parser support optional trailing arguments that are common in bitcoind (verbosity on getblock/getrawtransaction/getblockheader, etc.). Previously parseParams treated every entry in callSpec as strictly required and rejected both too few and too many parameters. This prevented legitimate calls from the public /rpc endpoint and forced awkward workarounds. The callSpec format was extended so that optional parameters can be marked with a trailing "?" (e.g. 'str int?'). parseParams now counts only the required parameters for the minimum check, silently accepts extra arguments (delegating final validation to the node), and correctly strips the "?" marker when looking up the coercion function. getBlockHeader was added to the PromisifiedRpcClient interface and to both the fallback and override specs. A new mocha setup hook (test/setup.ts) was introduced that sanitizes Error objects after each test, recursively handling BigInt, Symbol, Function, circular references and non-enumerable properties. .mocharc.json was updated to load it, so failures involving complex blockchain data now produce readable reports instead of serialization crashes. Minor dead-code removal and comment cleanups were performed in rest-client.ts and several lib-secret tests. The result is a more faithful and ergonomic RPC layer that matches real node behavior while preserving clear errors for missing required parameters and improving day-to-day test maintainability.
…cutes on the correct tip
feat(TBC20): standardize Token API and align transfer semantics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.