-
Notifications
You must be signed in to change notification settings - Fork 2
Tokens #695
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tcsenpai
wants to merge
130
commits into
stabilisation
Choose a base branch
from
tokens
base: stabilisation
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Tokens #695
Changes from all commits
Commits
Show all changes
130 commits
Select commit
Hold shift + click to select a range
67d37a2
docs: map existing codebase
tcsenpai a454f37
docs: add repository semantic map
tcsenpai a3d0626
chore: refresh semantic map for baseline ref
tcsenpai fcc8d5e
chore: add embeddings generator for semantic map
tcsenpai 1bf0da0
chore: add local embeddings for semantic index
tcsenpai 5173ed1
docs: point agents to repository semantic map
tcsenpai f1ade44
chore: add canonical check command
tcsenpai 38609ff
fix(devnet): set genesis from_ed25519_address
tcsenpai b8909f4
fix(devnet): avoid bootstrap race in getGenesisDataHash
tcsenpai ee8ae14
Revert "fix(devnet): avoid bootstrap race in getGenesisDataHash"
tcsenpai 02eba32
fix(devnet): make getGenesisDataHash startup-safe
tcsenpai 81b7018
perf(loadgen): add transfer ramp, quiet mode, and hygiene
tcsenpai 16d41c6
perf(loadgen): write run artifacts and per-second timeseries
tcsenpai 473e9f5
perf(loadgen): persist run artifacts (gitignored)
tcsenpai 69e9ace
memories
tcsenpai abd9111
cleanup
tcsenpai f173f9d
cleanup 2
tcsenpai 44dcc5d
fix: prevent token balance divergence under load
tcsenpai ac0ab02
fix: make token holder pointers and sync tx fetching reliable
tcsenpai af34af1
fix: serialize token mint/burn updates
tcsenpai 2dd36c4
chore: ignore local beads runtime dirs
tcsenpai 754575a
test(loadgen): add token ACL smoke scenario
tcsenpai 0a8c249
fix: IM WS loadgen + signaling server tx signing
tcsenpai c12e8c9
test: token consensus consistency scenario
tcsenpai fd29c88
test: token read/query coverage scenario
tcsenpai 9323fae
test(tokens): add token ACL matrix scenario
tcsenpai 7abb7fa
test(tokens): add token edge-cases scenario
tcsenpai 0db1aeb
chore(better_testing): add runner scripts and perf baseline
tcsenpai e667241
test(tokens): add canBurn ACL matrix scenario
tcsenpai 452dad2
test(tokens): add pause/unpause ACL matrix scenario
tcsenpai 22e94c3
test(tokens): add transferOwnership ACL matrix scenario
tcsenpai ec868dc
feat(better_testing): add token ACL multi-perm + updateACL compat sce…
tcsenpai b1d25c2
feat(token): enable scripted callView + add script smoke scenario
tcsenpai 2061f55
feat(better_testing): add token script hook correctness scenario
tcsenpai 674b71e
feat(better_testing): add token script rejects/invariants scenario
tcsenpai a26c793
feat(better_testing): scripted token transfer ramp
tcsenpai 52d702e
docs(better_testing): record SCRIPT_SET_STORAGE ramp findings
tcsenpai 057d3aa
fix(tokens): prevent self-transfer mint and apply token edits at fina…
tcsenpai 43760bd
fix(better_testing): harden token suite scenarios
tcsenpai 2e43981
docs(better_testing): add runbook for scenarios
tcsenpai 482c84a
feat(better_testing): add scripted mint/burn loadgen
tcsenpai 87d26d1
fix(better_testing): harden loadgen accounting + settle checks
tcsenpai 8d2a55a
feat(better_testing): add token_observe probe scenario
tcsenpai 70ad9dd
fix(better_testing): require mempool drain for settle check
tcsenpai dd1f5b5
fix: committed token reads during sync/consensus
tcsenpai 2568ab0
feat: add beadspace dashboard
tcsenpai 76cf927
fix: stabilize chaos scripted transfer restart
tcsenpai 2660ba2
(fix) prevent token state divergence under load
tcsenpai b98c46d
(test) token invariants (known holders)
tcsenpai 3353581
(fix) prevent committed reads stuck in STATE_IN_FLUX
tcsenpai 561bd65
(test) token pause/unpause under load
tcsenpai 64faf1f
(test) export token holders for global invariants
tcsenpai fd73aea
bd: backup 2026-03-03 09:48
tcsenpai 21e38e3
chore(br): restore issues.jsonl
tcsenpai d5f7181
test(better_testing): deterministic scripted rejects
tcsenpai 3e7a83a
fix(br): ensure unique external_ref
tcsenpai e4f57c2
test(better_testing): upgrade script mid-load
tcsenpai ac6e21c
chore(br): expand token testing task matrix
tcsenpai 229ac11
chore(br): close already-covered token scenario tasks
tcsenpai 2d85683
test(tokens): run token_script_mint_ramp
tcsenpai 9ede6cb
chore(br): close bd-2vy.2.3.6
tcsenpai 30c493b
test(tokens): run token_script_burn
tcsenpai 056d936
test(tokens): run token_script_burn_ramp
tcsenpai 4d09248
chore(tokens): add epic for complex scripted tokens
tcsenpai 6f68107
test(better_testing): complex token-script scenarios
tcsenpai 23108ab
docs(tokens): document token system and diagrams
tcsenpai af9cda6
chore(br): update issues
tcsenpai 2a0177c
docs(tokens): add better_testing run results
tcsenpai 5636ad3
chore(br): update issues
tcsenpai 43a40d8
added old branches refs (ipfs)
tcsenpai bdcd94a
ignores
tcsenpai 1ffee4c
fix(tokens): make custom script methods executable
tcsenpai 5a9c09b
fix(tokens): time-bound script hooks and views
tcsenpai 9451cd7
fix(tokens): prevent negative balances from script mutations
tcsenpai c66f62a
fix(tokens): update holder pointers for script mutations
tcsenpai ed9c402
fix(sync): avoid persisting mempool txs in batch sync
tcsenpai 53fd1a6
fix(scripting): harden token script VM
tcsenpai 5300856
fix(tokens): make hook contexts deterministic
tcsenpai edab550
fix(consensus): keep simulate rollbacks non-persisting
tcsenpai 714aee5
fix(consensus): atomically finalize blocks with token edits
tcsenpai 2971107
fix(security): restore nonce checks and add rate limiting
tcsenpai d34dda8
chore(beads): store backup state as jsonl
tcsenpai b740e96
fix(tokens): prevent caller spoofing in token edits
tcsenpai d24ded1
fix(rpc): init TypeORM for token nodeCalls
tcsenpai 68ce2be
chore(docs): remove in-repo phase checklist
tcsenpai 6206573
fix(sync): apply token edits before inserting block
tcsenpai 9cde2f5
chore(br): update issues
tcsenpai 14b403d
Promote token core test suite
tcsenpai e991dd3
gh files
tcsenpai 6dfe92f
wf files
tcsenpai d4fee61
ignored files
tcsenpai aa85292
Merge stabilisation into tokens
tcsenpai 08216e1
Remove legacy better_testing and beads artifacts
tcsenpai 8d85421
Align tracker guidance with mycelium
tcsenpai 87fbfcb
Fix review autofixes for config, docs, and tracking
tcsenpai 79f5b48
Sync hook architecture docs with runtime
tcsenpai 4d44c84
Triage new PR 695 review comments
tcsenpai 98bebc9
Fix semantic map validation and IPFS swarm key docs
tcsenpai 43e6040
Fix network validation and committed read handling
tcsenpai eb3033a
Fix token holder references and consensus tx validation
tcsenpai 123a295
Track new chainBlocks shared-state review task
tcsenpai 00ab201
ignores
tcsenpai e45a4a9
Fix transactional block state sync and fail closed rollback
tcsenpai f19b80b
Remove dead auth_ok signing path
tcsenpai 44888f8
Restore token rollback owner and script state
tcsenpai 68d86de
Stop caching token script VM contexts
tcsenpai e2e6720
Clone hook inputs before token script execution
tcsenpai 4afc6a9
Prepare token script sandbox boundary design
tcsenpai b640785
Fail closed on missing deterministic block height
tcsenpai 1f97b74
Update Mycelium guidance in agent instructions
tcsenpai 74a00eb
Refactor token scripting sandbox worker
tcsenpai 9968588
mycelium setup
tcsenpai 1b92a6b
Merge stabilisation hotfixes into tokens (batch GCR processing)
tcsenpai a748178
Add stabilisation hotfix report and Mycelium epic for tokens adaptation
tcsenpai 8e60488
Fix type errors from stabilisation merge
tcsenpai 5ed318b
Close completed mycelium tasks #265, #267, #270, #271
tcsenpai 2fb4415
Fix token rollback safety and hook execution guards
tcsenpai 87fa56d
Close mycelium task #268
tcsenpai ddcc36c
Add token_gcr_batch_exclusion devnet scenario (myc #266)
tcsenpai abfe728
Fix token_gcr_batch_exclusion scenario for single-wallet mode
tcsenpai 2bbde95
Close mycelium task #266 — devnet scenario passed
tcsenpai 6d7efc4
Stabilisation hotfix merge into tokens — summary
tcsenpai 8402ea0
updated myc
tcsenpai 410a1f5
Merge tokens-stabilisation-merge into tokens
tcsenpai bece554
Fix greptile review issues: onApprove double-fire, custom method writ…
tcsenpai 75fe074
Merge stabilisation reorganization into tokens
tcsenpai 879a0bc
better documentation
tcsenpai dbe81bf
ignores
tcsenpai fd14b0c
testing
tcsenpai d9c9b69
Merge branch 'tokens' of https://github.com/kynesyslabs/node into tokens
tcsenpai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
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
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
This file was deleted.
Oops, something went wrong.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| # Hook System Architecture | ||
|
|
||
| ## Summary | ||
| The hook system allows token scripts to extend native operations (transfer, mint, burn, approve) with custom logic. Hooks can validate, modify, or reject operations and add additional mutations. | ||
|
|
||
| ## Hook Types | ||
| All 8 hook types are supported: | ||
| - `beforeTransfer` / `afterTransfer` | ||
| - `beforeMint` / `afterMint` | ||
| - `beforeBurn` / `afterBurn` | ||
| - `beforeApprove` / `afterApprove` | ||
|
|
||
| ## Key Components | ||
|
|
||
| ### HookExecutor (`HookExecutor.ts`) | ||
| High-level orchestrator for hook execution during native operations. | ||
|
|
||
| **Main Method**: `executeWithHooks(request: ExecuteWithHooksRequest): Promise<HookExecutionResult>` | ||
|
|
||
| **Execution Flow**: | ||
| ```text | ||
| ExecuteWithHooksRequest | ||
| │ | ||
| ▼ | ||
| 1. Execute beforeHook | ||
| ├── If hook throws or returns `reject` → Return `rejection` | ||
| └── If hook returns mutations/setStorage → Update working state | ||
| │ | ||
| ▼ | ||
| 2. Apply native operation mutations | ||
| │ | ||
| ▼ | ||
| 3. Execute afterHook | ||
| ├── If hook throws or returns `reject` → Return `rejection` | ||
| └── If hook returns mutations/setStorage → Update working state | ||
| │ | ||
| ▼ | ||
| 4. Return HookExecutionResult | ||
| ├── finalState: GCRTokenData | ||
| ├── mutations: TokenMutation[] | ||
| ├── rejection: { hookType: string; reason: string } | null | ||
| └── metadata: HookExecutionMetadata | ||
| ``` | ||
|
|
||
| ### Hook Result Structure | ||
| ```typescript | ||
| interface HookResult { | ||
| reject?: string | boolean | ||
| mutations?: TokenMutation[] | ||
| setStorage?: Record<string, unknown> | ||
| } | ||
| ``` | ||
|
|
||
| ### Hook Rejection | ||
| ```typescript | ||
| interface HookRejection { | ||
| hookType: string | ||
| reason: string | ||
| } | ||
| ``` | ||
|
|
||
| ## Utility Functions | ||
|
|
||
| ### Native Operation Mutations | ||
| - `createTransferMutations(from, to, amount)` → [subBalance, addBalance] | ||
| - `createMintMutations(to, amount)` → [addBalance] | ||
| - `createBurnMutations(from, amount)` → [subBalance] | ||
| - `createApproveMutations(owner, spender, amount)` → [setAllowance] | ||
|
|
||
| ### Validation Helpers | ||
| - `validateSufficientBalance(tokenData, address, amount)` | ||
| - `validateSufficientAllowance(tokenData, owner, spender, amount)` | ||
|
|
||
| ### Merging | ||
| - `mergeHookResults(results: HookResult[])` → Single HookResult | ||
|
|
||
| ## Usage Example | ||
| ```typescript | ||
| const executor = new HookExecutor(scriptExecutor) | ||
|
|
||
| const result = await executor.executeWithHooks({ | ||
| operation: "transfer", | ||
| operationData: { from: "0x1", to: "0x2", amount: 100n }, | ||
| tokenAddress: "0xToken", | ||
| tokenData: currentState, | ||
| scriptCode: tokenScript, | ||
| txContext: { caller, txHash, timestamp, blockHeight, prevBlockHash }, | ||
| nativeOperationMutations: createTransferMutations("0x1", "0x2", 100n), | ||
| }) | ||
|
|
||
| if (!result.rejection) { | ||
| // Apply result.finalState to storage | ||
| } else { | ||
| // Handle rejection: result.rejection.reason | ||
| } | ||
| ``` | ||
|
|
||
| ## Integration with ScriptExecutor | ||
| HookExecutor uses the current `scriptExecutor` implementation in `src/libs/scripting/index.ts`, which executes exported hook functions inside a Node `vm` context with timeouts. This is a determinism-oriented execution model, not a security boundary. | ||
|
|
||
| ## Error Handling | ||
| - Hook errors cancel the operation. | ||
| - The current branch does not re-run hook logic during rollback; rollback support is limited to the native reverse paths implemented in `GCRTokenRoutines`. | ||
| - Custom-method rollback remains explicitly unsupported and should not be documented as fully restorative. | ||
|
|
||
| ## Consensus Integration (Phase 5.1) | ||
|
|
||
| ### GCRTokenRoutines Integration | ||
| The hook system is now integrated into the consensus flow through `GCRTokenRoutines`: | ||
|
|
||
| **Files Modified**: | ||
| - `src/libs/blockchain/gcr/handleGCR.ts` - Passes Transaction to GCRTokenRoutines.apply | ||
| - `src/libs/blockchain/gcr/gcr_routines/GCRTokenRoutines.ts` - Contains hook integration | ||
|
|
||
| **Key Changes**: | ||
|
|
||
| 1. **GCRTokenRoutines.apply signature updated**: | ||
| ```typescript | ||
| static async apply( | ||
| editOperation: GCREditToken, | ||
| gcrTokenRepository: Repository<GCRToken>, | ||
| simulate: boolean, | ||
| tx?: Transaction, // New: Transaction context for hook execution | ||
| ): Promise<GCRResult> | ||
| ``` | ||
|
|
||
| 2. **Helper Methods Added**: | ||
| - `getHookExecutor()` - Singleton HookExecutor instance | ||
| - `tokenToGCRTokenData(token)` - Converts GCRToken entity to GCRTokenData interface | ||
| - `applyGCRTokenDataToEntity(token, data)` - Applies mutations back to entity | ||
|
|
||
| 3. **Handler Integration Pattern**: | ||
| Each handler (transfer, mint, burn) now checks for scripts: | ||
| ```typescript | ||
| if (token.hasScript && token.script?.code && tx && !edit.isRollback) { | ||
| // Use HookExecutor.executeWithHooks() | ||
| // Handle rejection via result.rejection | ||
| // Apply finalState via applyGCRTokenDataToEntity() | ||
| } else { | ||
| // Native operation without hooks | ||
| } | ||
| ``` | ||
|
|
||
| ### Consensus Flow | ||
|
|
||
| ```text | ||
| Transaction submitted | ||
| │ | ||
| ▼ | ||
| PoRBFTv2 Consensus | ||
| │ | ||
| ▼ | ||
| applyGCREditsFromMergedMempool | ||
| │ | ||
| ▼ | ||
| HandleGCR.apply(edit, tx) ← Now passes tx | ||
| │ | ||
| ▼ | ||
| GCRTokenRoutines.apply(edit, repo, simulate, tx) | ||
| │ | ||
| ▼ | ||
| handleTransferToken / handleMintToken / handleBurnToken | ||
| │ | ||
| ├── Token has script? ──Yes──▶ HookExecutor.executeWithHooks() | ||
| │ │ | ||
| │ ┌─────┴─────┐ | ||
| │ │ │ | ||
| │ Proceed Rejection | ||
| │ │ │ | ||
| │ Apply finalState │ | ||
| │ │ │ | ||
| │ ▼ ▼ | ||
| │ Save entity Return failure | ||
| │ | ||
| └── No script ───────▶ Native operation | ||
| │ | ||
| ▼ | ||
| Save entity | ||
| ``` | ||
|
|
||
| ### Determinism Notes | ||
| - Consensus-critical hook execution currently uses the Node `vm`-based runtime in `src/libs/scripting/index.ts`, not SES. | ||
| - `prevBlockHash` is currently a placeholder value in some paths and is intended to be injected by consensus later. | ||
| - `blockHeight` comes from `tx.blockNumber` and may be absent during mempool-side processing. | ||
| - `timestamp` is taken from transaction content when available; any `Date.now()` fallback should be treated as non-consensus or pre-consensus behavior, not as a deterministic guarantee. | ||
|
|
||
| ### Rollback Handling | ||
| Script hooks are not executed during rollback. Rollback paths currently reverse only the supported native token effects; script-upgrade payload restoration and opaque custom-method state reversal are tracked separately and are not complete guarantees today. | ||
|
|
||
| ## Last Updated | ||
| 2026-02-23 - Phase 5.1 consensus integration complete | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| # Scripting Module Architecture | ||
|
|
||
| ## Summary | ||
| The `src/libs/scripting/` module provides secure, deterministic script execution for token operations using SES (Secure EcmaScript) sandbox technology. | ||
|
|
||
| ## Key Components | ||
|
|
||
| ### TokenSandbox (`TokenSandbox.ts`) | ||
| Low-level SES compartment management: | ||
| - `initialize()` - Locks down JS primordials via SES | ||
| - `execute(code, context, config)` - Runs script in isolated compartment | ||
| - `executeHook(hookCode, hookType, context, config)` - Runs hooks for native operations | ||
| - `validateMutations()` - Structural validation of mutations | ||
| - Deterministic PRNG via `createSeededRandom()` using prevBlockHash + txHash | ||
|
|
||
| ### ScriptExecutor (`ScriptExecutor.ts`) | ||
| High-level orchestration service: | ||
| - `executeMethod(request)` - Main entry point for consensus layer | ||
| - `executeHook(request)` - Hook execution for native operations | ||
| - `validateMutationsAgainstToken()` - Business rule validation | ||
| - Builds ScriptContext from ExecuteMethodRequest | ||
| - Merges config with defaults | ||
|
|
||
| Key types: | ||
| - `BlockContext` - height, prevBlockHash, timestamp | ||
| - `ExecuteMethodRequest` - tokenAddress, method, args, caller, blockContext, txHash, tokenData | ||
| - `ExecuteHookRequest` - hookCode, hookType, hookContext, tokenData | ||
|
|
||
| ### MutationApplier (`MutationApplier.ts`) | ||
| Pure functions for applying mutations: | ||
| - `applyMutations(tokenData, mutations)` - Main apply function | ||
| - Returns `MutationApplicationResult` with newState, events, mutationsApplied | ||
| - Immutable - creates deep copy before modifications | ||
| - Utility functions: `isEmitMutation()`, `getStateMutations()`, `getEventMutations()` | ||
|
|
||
| ### TokenStateAccessorBuilder (`TokenStateAccessorBuilder.ts`) | ||
| Builds read-only state accessors: | ||
| - `buildTokenStateAccessor(data)` - Full accessor for scripts | ||
| - `buildMinimalAccessor()` - Minimal accessor for testing | ||
|
|
||
| ### Types (`types.ts`) | ||
| Core type definitions: | ||
| - `ScriptContext` - caller, method, args, timestamp, blockHeight, prevBlockHash, txHash, token | ||
| - `StateMutation` - Union of SetBalance, AddBalance, SubBalance, SetAllowance, SetStorage, Emit | ||
| - `ScriptResult` - ScriptSuccess | ScriptError | ||
| - `HookContext`, `HookResult` - Hook-specific types | ||
|
|
||
| ## Execution Flow | ||
|
|
||
| ``` | ||
| ExecuteMethodRequest | ||
| │ | ||
| ▼ | ||
| ScriptExecutor.executeMethod() | ||
| │ | ||
| ├─▶ buildTokenStateAccessor(tokenData) | ||
| │ | ||
| ├─▶ Build ScriptContext | ||
| │ | ||
| ├─▶ tokenSandbox.execute(code, context, config) | ||
| │ │ | ||
| │ └─▶ SES Compartment execution | ||
| │ Returns StateMutation[] | ||
| │ | ||
| ├─▶ validateMutationsAgainstToken() | ||
| │ (Business rule validation) | ||
| │ | ||
| └─▶ Return ScriptResult | ||
| │ | ||
| ▼ | ||
| applyMutations(tokenData, result.mutations) | ||
| │ | ||
| └─▶ MutationApplicationResult | ||
| (newState, events, mutationsApplied) | ||
| ``` | ||
|
|
||
| ### HookExecutor (`HookExecutor.ts`) | ||
| Native operation hook orchestrator: | ||
| - `executeWithHooks(request)` - Main entry for consensus layer | ||
| - Execution flow: beforeHook → native mutations → afterHook | ||
| - Rejection handling with rollback on afterHook failure | ||
| - Utility functions: `createTransferMutations()`, `createMintMutations()`, etc. | ||
|
|
||
| See `arch_hook_system` memory for detailed hook architecture. | ||
|
|
||
| ## Last Updated | ||
| 2026-02-22 - Phase 2.4 completion (added HookExecutor) |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.