-
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
128
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
128 commits
Select commit
Hold shift + click to select a range
67d37a2
docs: map existing codebase
a454f37
docs: add repository semantic map
a3d0626
chore: refresh semantic map for baseline ref
fcc8d5e
chore: add embeddings generator for semantic map
1bf0da0
chore: add local embeddings for semantic index
5173ed1
docs: point agents to repository semantic map
f1ade44
chore: add canonical check command
38609ff
fix(devnet): set genesis from_ed25519_address
b8909f4
fix(devnet): avoid bootstrap race in getGenesisDataHash
ee8ae14
Revert "fix(devnet): avoid bootstrap race in getGenesisDataHash"
02eba32
fix(devnet): make getGenesisDataHash startup-safe
81b7018
perf(loadgen): add transfer ramp, quiet mode, and hygiene
16d41c6
perf(loadgen): write run artifacts and per-second timeseries
473e9f5
perf(loadgen): persist run artifacts (gitignored)
69e9ace
memories
abd9111
cleanup
f173f9d
cleanup 2
44dcc5d
fix: prevent token balance divergence under load
ac0ab02
fix: make token holder pointers and sync tx fetching reliable
af34af1
fix: serialize token mint/burn updates
2dd36c4
chore: ignore local beads runtime dirs
754575a
test(loadgen): add token ACL smoke scenario
0a8c249
fix: IM WS loadgen + signaling server tx signing
c12e8c9
test: token consensus consistency scenario
fd29c88
test: token read/query coverage scenario
9323fae
test(tokens): add token ACL matrix scenario
7abb7fa
test(tokens): add token edge-cases scenario
0db1aeb
chore(better_testing): add runner scripts and perf baseline
e667241
test(tokens): add canBurn ACL matrix scenario
452dad2
test(tokens): add pause/unpause ACL matrix scenario
22e94c3
test(tokens): add transferOwnership ACL matrix scenario
ec868dc
feat(better_testing): add token ACL multi-perm + updateACL compat sce…
b1d25c2
feat(token): enable scripted callView + add script smoke scenario
2061f55
feat(better_testing): add token script hook correctness scenario
674b71e
feat(better_testing): add token script rejects/invariants scenario
a26c793
feat(better_testing): scripted token transfer ramp
52d702e
docs(better_testing): record SCRIPT_SET_STORAGE ramp findings
057d3aa
fix(tokens): prevent self-transfer mint and apply token edits at fina…
43760bd
fix(better_testing): harden token suite scenarios
2e43981
docs(better_testing): add runbook for scenarios
482c84a
feat(better_testing): add scripted mint/burn loadgen
87d26d1
fix(better_testing): harden loadgen accounting + settle checks
8d2a55a
feat(better_testing): add token_observe probe scenario
70ad9dd
fix(better_testing): require mempool drain for settle check
dd1f5b5
fix: committed token reads during sync/consensus
2568ab0
feat: add beadspace dashboard
76cf927
fix: stabilize chaos scripted transfer restart
2660ba2
(fix) prevent token state divergence under load
b98c46d
(test) token invariants (known holders)
3353581
(fix) prevent committed reads stuck in STATE_IN_FLUX
561bd65
(test) token pause/unpause under load
64faf1f
(test) export token holders for global invariants
fd73aea
bd: backup 2026-03-03 09:48
21e38e3
chore(br): restore issues.jsonl
d5f7181
test(better_testing): deterministic scripted rejects
3e7a83a
fix(br): ensure unique external_ref
e4f57c2
test(better_testing): upgrade script mid-load
ac6e21c
chore(br): expand token testing task matrix
229ac11
chore(br): close already-covered token scenario tasks
2d85683
test(tokens): run token_script_mint_ramp
9ede6cb
chore(br): close bd-2vy.2.3.6
30c493b
test(tokens): run token_script_burn
056d936
test(tokens): run token_script_burn_ramp
4d09248
chore(tokens): add epic for complex scripted tokens
6f68107
test(better_testing): complex token-script scenarios
23108ab
docs(tokens): document token system and diagrams
af9cda6
chore(br): update issues
2a0177c
docs(tokens): add better_testing run results
5636ad3
chore(br): update issues
43a40d8
added old branches refs (ipfs)
bdcd94a
ignores
1ffee4c
fix(tokens): make custom script methods executable
5a9c09b
fix(tokens): time-bound script hooks and views
9451cd7
fix(tokens): prevent negative balances from script mutations
c66f62a
fix(tokens): update holder pointers for script mutations
ed9c402
fix(sync): avoid persisting mempool txs in batch sync
53fd1a6
fix(scripting): harden token script VM
5300856
fix(tokens): make hook contexts deterministic
edab550
fix(consensus): keep simulate rollbacks non-persisting
714aee5
fix(consensus): atomically finalize blocks with token edits
2971107
fix(security): restore nonce checks and add rate limiting
d34dda8
chore(beads): store backup state as jsonl
b740e96
fix(tokens): prevent caller spoofing in token edits
d24ded1
fix(rpc): init TypeORM for token nodeCalls
68ce2be
chore(docs): remove in-repo phase checklist
6206573
fix(sync): apply token edits before inserting block
9cde2f5
chore(br): update issues
14b403d
Promote token core test suite
e991dd3
gh files
6dfe92f
wf files
d4fee61
ignored files
aa85292
Merge stabilisation into tokens
08216e1
Remove legacy better_testing and beads artifacts
8d85421
Align tracker guidance with mycelium
87fbfcb
Fix review autofixes for config, docs, and tracking
79f5b48
Sync hook architecture docs with runtime
4d44c84
Triage new PR 695 review comments
98bebc9
Fix semantic map validation and IPFS swarm key docs
43e6040
Fix network validation and committed read handling
eb3033a
Fix token holder references and consensus tx validation
123a295
Track new chainBlocks shared-state review task
00ab201
ignores
e45a4a9
Fix transactional block state sync and fail closed rollback
f19b80b
Remove dead auth_ok signing path
44888f8
Restore token rollback owner and script state
68d86de
Stop caching token script VM contexts
e2e6720
Clone hook inputs before token script execution
4afc6a9
Prepare token script sandbox boundary design
b640785
Fail closed on missing deterministic block height
1f97b74
Update Mycelium guidance in agent instructions
74a00eb
Refactor token scripting sandbox worker
9968588
mycelium setup
1b92a6b
Merge stabilisation hotfixes into tokens (batch GCR processing)
a748178
Add stabilisation hotfix report and Mycelium epic for tokens adaptation
8e60488
Fix type errors from stabilisation merge
5ed318b
Close completed mycelium tasks #265, #267, #270, #271
2fb4415
Fix token rollback safety and hook execution guards
87fa56d
Close mycelium task #268
ddcc36c
Add token_gcr_batch_exclusion devnet scenario (myc #266)
abfe728
Fix token_gcr_batch_exclusion scenario for single-wallet mode
2bbde95
Close mycelium task #266 — devnet scenario passed
6d7efc4
Stabilisation hotfix merge into tokens — summary
8402ea0
updated myc
410a1f5
Merge tokens-stabilisation-merge into tokens
bece554
Fix greptile review issues: onApprove double-fire, custom method writ…
75fe074
Merge stabilisation reorganization into tokens
879a0bc
better documentation
dbe81bf
ignores
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.