Skip to content

[DeFi][Application/Protocol] EVM-class finance on CKB with CellScript #43

Open

Description

@a19q3

Architectural boundary: protocol/application first, not a DeFi language extension

Normative scope rule. This programme proves that substantial CKB-native DeFi can be built as ordinary CellScript application/protocol packages. FIN-02–FIN-10 are not a backlog of nine new compiler features, language keywords, VM opcodes, or finance-specific runtime intrinsics.

  • Pool, Order, LPReceipt, swap, fill_order, cancel_order, AMM fees, pricing curves, LP issuance, order matching, settlement-allocation rules and financial risk policies are application-defined types, actions and protocol predicates. Neither the parser nor codegen may recognise finance-specific names and attach implicit rules.
  • General CellScript language/runtime owns only business-neutral mechanisms: typed resource ownership/lifecycles, bounded Cell selection and output correspondence, transaction/source/Script identity, executable effects, checked numerical operations, canonical ABI, independent checker and fail-closed resource limits.
  • Reusable standard library may expose business-neutral safe-wide multiplication/division with specified rounding, checked conversions, fixed-point or container helpers only when justified by concrete failing examples and independent non-financial uses. A formula such as constant-product pricing remains in an application package, not the stdlib or compiler.
  • Protocol packages/on-chain Scripts own asset custody, pool identity, LP supply, order escrow, cumulative payment/rounding, obligation allocation, and the actual transaction-level security invariants. All essential financial predicates must be enforced by the actual executing Lock/Type Scripts, not only by an SDK quote, test fixture, receipt label or ProtocolBundle structural check.
  • Generated builders/CKB adapter own live Cell discovery, quoting, transaction assembly, payer/change attribution, signing integration, routing within admitted bounds, submission/recovery and UX. They can assist, but cannot grant on-chain authority or waive a Script-level check. Evidence tooling independently tests source/VM/node/economic outcomes without being an authority layer.
  • Compiler-change admission: first attempt ordinary existing CellScript constructs and packages; then provide a minimal reproducing application, demonstrate exactly why existing general capabilities cannot express it correctly, specify a business-neutral contract with a second non-DeFi use, choose the smallest owning layer, record compatibility/checker/SDK impacts, open a separate general-purpose issue, and require adversarial/budget/gate evidence before accepting the change. No language change is authorised merely by creating or completing a FIN issue.
  • Release separation: [DeFi][Application/Protocol] EVM-class finance on CKB with CellScript #43/[DeFi][FIN-02][M1] Enforce authentic pool custody, asset identity and LP supply #52–[DeFi][FIN-10][M6] Independent DeFi package reproduction and final acceptance #60 are application/protocol programme acceptance, not automatic blockers for a CellScript core compiler release (including any future v0.36). [0.33][Runtime] Add bounded allocation-backed value collections and deterministic Map/Set #47–[0.33][Runtime] Extend bounded Cell selection and correspondence for heterogeneous and dynamic data #49 and [0.32][Language/ABI] Stabilize generic compatible-open Script and verifier handles #28/[0.32][ProtocolBundle] Stabilize runtime-selected open cross-Script roles #29 remain their own general-language workstreams; they become genuine FIN dependencies only when a specified executable DeFi shape demonstrably needs one and its scope is explicitly revised.
FIN item Primary implementation owner What is delivered rather than a language feature
FIN-02 / #52 Protocol: on-chain Lock/Type Scripts Authentic custody, pool/LP identity and supply enforcement
FIN-03 / #53 Protocol mathematics + conditional general stdlib Checked financial arithmetic, rounding and independent mathematical oracle
FIN-04 / #54 Pool protocol + generated SDK Constant-product AMM/LP lifecycle and real transaction construction
FIN-05 / #55 Developer tooling / integration Outside-developer second-pool reproducibility
FIN-06 / #56 Order/escrow protocol + SDK Author-defined Order Cell, partial fills, cumulative payout and cancel
FIN-07 / #57 Settlement protocol + ProtocolBundle Order/pool asset-flow validation across executing Script groups
FIN-08 / #58 Settlement protocol + builder No-double-credit allocations and bounded multihop routing
FIN-09 / #59 Off-chain builder/operations + evidence Intent-preserving retries, stale-state recovery and full-operation costs
FIN-10 / #60 Integration / independent evidence Clean external replay, adversarial scenarios and scoped acceptance

Acceptance interpretation: closing a FIN issue is evidence that the relevant application/protocol, builder or integration contract worked within documented limits. It does not demonstrate that the CellScript language has acquired a new builtin, nor does it grant a security audit, production deployment or new public release.


Expanded financial protocol capability tracker — October 2026

Scope and ownership. The original FIN-02–FIN-10 programme proves a bounded constant-product pool, escrowed orders and finite settlement. The additional FIN-11–FIN-29 issues below extend the application/protocol and SDK programme with independently admitted range liquidity, composable asset accounting, extensibility and developer tooling. They do not change the earlier FIN acceptance claims, create an implied single release milestone or require core-language grammar for any financial noun. A closed foundation issue remains a bounded accepted capability, not proof that its applications are already implemented.

New implementation issue index

Capability stream Functional issues Hard-dependency principle
Pool state and range execution #61 FIN-11 pool identity; #62 FIN-12 tick maths; #63 FIN-13 authenticated sparse ticks; #64 FIN-14 positions/fees; #65 FIN-15 cross-tick trades Authentic #52 custody and #53 maths → pool/tick/position → swaps. No ticker-named compiler semantics.
Net settlement and assets #66 FIN-16 ordered operations; #67 FIN-17 backed claims; #68 FIN-18 native CKB CKB's one real input/final output transition is preserved; logical intermediate steps and per-owner liabilities are checked.
Extensible pool behaviour #69 FIN-19 actual authenticated hook execution; #70 FIN-20 fee authority; #71 FIN-21 returned deltas/alternative curves Hook identity alone is insufficient: prove mandatory execution, permissioned effects, signed amount/owner scope and solvency.
Time and observations #72 FIN-22 temporal/freshness feasibility; #73 FIN-23 authenticated historic prices Chain-enforced expiry is claimed only when a real consensus-visible proof exists; otherwise explicitly mark trusted or client-only assumptions.
Developer-facing composition #74 FIN-24 positions/subscriptions; #75 FIN-25 command router/migration; #76 FIN-26 signed intents; #77 FIN-27 indexing/quoting Use documented packages and generated adapters; user intent and genuine state ownership are independently enforceable.
Independent integration and assurance #78 FIN-28 third-party extensions/adversarial corpus; #79 FIN-29 differential state/solvency model Begin #79 model/counterexample work early. #59 owns operational budgets; #60 owns final external reproduction for its admitted scope.

Dependency and acceptance sketch

flowchart TD
    A["#52 / #53: custody + numerical foundations"] --> P["#61–#65: pool, ticks, positions, swaps"]
    P --> N["#66–#68: operations, claims, native currency"]
    P --> H["#69–#71: hooks and accounting"]
    N --> H
    T["#72: truthful time claims"] --> O["#73: optional authenticated observations"]
    H --> O
    P --> D["#74–#77: position / router / SDK"]
    N --> D
    H --> D
    D --> E["#78: independent extensions"]
    O --> E
    P --> V["#79: differential solvency evidence"]
    N --> V
    H --> V
    E --> V
Loading

Important split in #58: pure multi-pool AMM routing is independent of #56/#57 order acceptance and can use accepted #54 or #65 pool execution; shared-payment order allocation still requires #57. See the updated #58. This avoids accidental order-book gating of the pool router.

Evidence and reviewer separation: issue creation and diagrams only define required work. Every FIN issue must separately freeze its exact protocol, resource bounds and owner/review disposition; pass genuine all-group CKB-VM and adversarial financial evidence; archive reproducible identities; and distinguish local, node, external reproduction, audited and deployment tiers. Core compiler releases and these protocol-package acceptance streams remain separate. The earlier deferred-capability paragraphs further below describe the original baseline scope and are preserved as historical intent, not an assertion that these newly owned streams have been implemented.


Implementation issue tracker — 2026-10-11

Tracking update (not implementation acceptance): FIN-01/M0 remains the initial baseline, owner/reviewer, decision-freeze and evidence-inventory gate inside this umbrella. The FIN-02–FIN-10 work items in §11 now have dedicated, separately accepted GitHub implementation issues. These FIN identifiers are work-item names, not GitHub issue numbers.

Stage Work item and tracked issue Dependency / opening condition
M0 FIN-01 — this umbrella (#43) Revalidate baseline, name owners/reviewers and freeze first slice
M1 FIN-02 — #52 Authentic custody and LP supply FIN-01; develop alongside FIN-03
M1 FIN-03 — #53 Checked financial arithmetic FIN-01 + FIN-02 domain inputs; develop alongside FIN-02
M2 FIN-04 — #54 Complete AMM/LP and builders Accepted FIN-02 + FIN-03
M2 FIN-05 — #55 External second-pool integration FIN-04 first runnable SDK path; can start before its final acceptance
M3 FIN-06 — #56 Escrowed partial-fill orders Accepted FIN-02 + FIN-03; freeze D09a–D09d and order D10 before implementation; parallel to FIN-04
M3 FIN-07 — #57 Order/pool settlement Accepted FIN-04 + FIN-06
M4 FIN-08 — #58 Shared-payment allocation and bounded multihop Accepted FIN-07; freeze D11/D12 and route limits
M5 FIN-09 — #59 Recovery and contention budgets Early prototype from runnable FIN-04; final acceptance after FIN-08
M6 FIN-10 — #60 Independent reproduction/closure FIN-05 + FIN-08 + FIN-09 (and their upstream dependencies)
flowchart TD
    A["#43 FIN-01: M0"] --> B["#52 FIN-02: custody"]
    A --> C["#53 FIN-03: arithmetic"]
    B --> D["#54 FIN-04: AMM/LP"]
    C --> D
    B --> F["#56 FIN-06: orders"]
    C --> F
    D --> E["#55 FIN-05: external DX"]
    D --> G["#57 FIN-07: order/pool"]
    F --> G
    G --> H["#58 FIN-08: allocation/routes"]
    D -. "early recovery prototype" .-> I["#59 FIN-09: recovery/budgets"]
    H --> I
    E --> J["#60 FIN-10: independent closure"]
    H --> J
    I --> J
Loading

Ownership boundaries: Existing accepted #7–#11/#24–#26 supply bounded exact-deployment foundations. Open general-language #47/#48/#49 and compatible-open #28/#29 are not automatic release gates for this programme; link a missing general primitive only after an admitted concrete application demonstrates the gap. ZK #42/#44–#46 is also separately scoped. Liquidity, live stablecoins, lending, Oracles and concentrated liquidity remain outside the initial FIN-02–FIN-10 acceptance.

State: all new issues are initially proposed; opening an issue does not claim tested code, an assigned reviewer, an independent security audit, deployment or permission to release. Do not automatically attach these issues to the 0.32/0.36 milestone or change inherited cost budgets. The detailed financial, adversarial and resource contracts below remain normative.


Objective and scope

Deliver a reusable CKB-native trading application with authentic asset custody, checked financial arithmetic, a complete constant-product AMM/LP lifecycle, partial-fill orders and bounded composable settlement through generated builders.

“EVM-class” means comparable financial functionality, not EVM execution compatibility. Financial policy belongs in protocol packages. Only demonstrated, business-neutral capability gaps belong in the compiler or general standard library. Stablecoins are not an engineering prerequisite: test-issued assets with genuine enforcing Scripts suffice; market liquidity and stablecoin integrations are separate product work.

Duplicate and overlap review — 2026-10-04

Reviewed all 37 repository issues, including 8 open issues, their titles/bodies, and relevant implementation/closure discussion. No existing issue owns this complete application scope. This is a new umbrella extending the accepted bounded evidence, not a reopening of completed mechanisms.

Existing work Relationship and ownership boundary
#26 — closed business corpus Closest overlap: bounded order/AMM cases and composition evidence. Reuse those fixtures and their exact evidence ceilings. This issue adds authentic pool custody and LP supply closure, continuous financial lifecycles, cumulative fill economics, mandatory on-chain shared-payment allocation, operational recovery and independent package reuse. Do not rewrite the frozen 0.30 portfolio or claim its closure already proves these outcomes.
#9, #10, #11 — closed ProtocolBundle, closed roles and exact handles Reuse these mechanisms. Do not create another transaction serializer, linker, signer framework or exact-handle format. Bundle structural conflict checks do not replace financial allocation checks on-chain.
#7, #8, #12, #24, #25 — closed runtime, temporal and authority foundations Reuse bounded group selection, output correspondence, typed views and authorization. Open a narrowly scoped follow-up only for an evidenced missing contract; do not duplicate completed work.
#14 — closed capability taxonomy Reuse the separation between executable-surface closure and product-capability completeness in the new inventory.
#28, #29 — open compatible handles / open roles Optional future extension, not a prerequisite for this exact-deployment, bounded design. Keep their generic language/ABI scope there.
#35 — closed cost evidence; #36–#40 — open measurement/backend research Reuse measurement infrastructure and preserve existing baselines. Finance owns its application cases and frozen budgets; any general optimization stays in the existing owning track or an explicit linked follow-up. GitHub states are not a new assessment of local implementation completion.
#42 — open ZK application tooling; #22 — closed exact ZK boundary Adjacent builder/recovery concerns, but ZK proving, statement binding and verifier lifecycle remain there. ZK is not required for this financial profile. Share general adapter improvements where applicable.

Required implementation boundaries

  • Every reserve spend must require the authentic matching pool transition; pool accounting must bind the actual reserve Cells.
  • Ordinary LP transfers/splits/merges preserve supply. Every mint/burn requires a matching pool transition. Standalone LP destruction and destruction/redemption of locked minimum shares reject.
  • Freeze widths, rounding, fee rules, custody and share topology before acceptance. Independent high-precision models must agree with builders and executed transactions.
  • D09a–D09d resolve zero-payment fills, minimum fill/payment, final dust and surplus credit before order implementation. Maker aggregate entitlement and per-taker economics are separate properties.
  • Reject permutations that break role/recipient/allocation bindings; handle equivalent reconstructed permutations according to the declared layout contract.
  • Shared payments require mandatory on-chain aggregate allocation. One payment cannot satisfy competing obligations twice, even when a hostile builder omits off-chain checks.
  • Rebuilds preserve user intent and distinguish stale state, unavailable observations, execution rejection and unknown submission outcomes.

First executable slice

After baseline/decision closure, couple FIN-02 and FIN-03: two genuinely enforced test assets, one unique pool with authenticated custody, authentic LP issuance, one generated swap and valid redemption. Run reserve-only spend, forged LP, omitted pool state, asset substitution and standalone LP burn attempts through the complete transaction verifier. Negative cases must reach the intended enforcement check, not fail only on unrelated malformed signatures.

Milestone acceptance

  • M0: revalidate inventory, assign owners/reviewers and map child issues; reuse existing owners above.
  • M1: freeze custody/identity/numeric contracts and execute the first joint slice.
  • M2: complete genuine AMM/LP lifecycle, both swap directions and generated builders; outside developer instantiates a second pool with different admitted assets/parameters.
  • M3: partial/final fills, cancel and single-order/pool settlement with explicit economic decisions.
  • M4: bounded shared-output and distinct-pool multihop composition, including unrelated Cells and layout cases.
  • M5: competing builders, intent-preserving rebuild, unknown submission recovery and complete-operation budgets.
  • M6: independent developer composes the second pool, reproduces success/failure evidence, and resolves material usability gaps without compiler changes or hand-replacing generated verifiers.
  • Exact source/compiler/checker/artifact/transaction/VM/node identities, frozen budgets, relevant dev/CI/backend gates and scope-specific review disposition recorded.

Owners/reviewers and implementation child issues remain to be assigned. FIN IDs in the plan are local work-item IDs, not existing GitHub issues. No release version is assigned, no existing review waiver transfers, and this issue does not authorize publication or deployment. Lending, oracles, concentrated liquidity and unrestricted routing remain separate follow-ups.

Detailed plan snapshot

The complete reviewed plan is included below so this issue is independently actionable. Its workspace path is docs/CELLSCRIPT_EVM_CLASS_FINANCE_PLAN.md; that new file is not yet committed/published, so no nonexistent remote file link is used. Source references in the snapshot are pinned to the inspected baseline (and its benchmark gitlink), not to an assumed latest implementation. All implementation evidence remains pending.

Workspace plan SHA-256 before issue backlink: bdde1cec96fe979fa8c42c1cce4617083726ba8843f7acb414dae46feb4c61e1. Relative source links below are expanded for GitHub readability.

Full implementation plan — reviewed 2026-10-04

EVM-class finance on CKB: research and implementation plan

Status: proposed implementation plan, written 2026-10-04. No implementation
milestone in this plan is accepted merely by adding this document. This is a
protocol-package and application-tooling initiative with narrowly justified
compiler/library prerequisites, not a finance-specific language redesign.

The 2026-10-04 review revision makes LP supply preservation, layout-sensitive
permutation tests, partial-fill rounding decisions and independent package
reuse explicit acceptance requirements. Section 11.1 defines the first joint
custody/arithmetic implementation exercise; its evidence remains pending.

The initial source inspection used branch 0.32 at
6616384b1b5e3128b41aa8af4b79edd6e1643f3d. Existing reports retain their own
source and artifact identities; they were not re-executed for this inventory.
Revalidate the baseline at implementation start. No release version, new
syntax, ABI, metadata schema, deployment, or review waiver is assigned here.

1. Objective and completion boundary

Enable developers to build substantial CKB-native financial applications with
explicit asset accounting, reproducible arithmetic, composable transaction
constraints, and reliable construction of complete transactions.

"EVM-class" describes comparable financial functionality: trading, liquidity
provision, and settlement, with lending considered later. EVM bytecode,
account-state emulation, and Solidity compatibility are outside scope.

The first program of work contains three separately accepted product slices:

  1. One constant-product pool with genuine asset custody and a complete LP
    lifecycle, through generated builders and real transaction verification.
  2. Partially fillable orders, including cancellation and settlement against
    one admitted pool.
  3. Bounded multiple-order settlement, shared payment outputs, and routes
    across distinct pools, with contention and external-developer evidence.

Completing an earlier slice is useful and reportable without claiming the
later slices. Completing all three establishes only the admitted trading
portfolio. It does not establish unrestricted composability, lending safety,
economic optimality, or production readiness.

2. Architectural constraints: preserve CellScript's generality

2.1 Ownership by layer

Layer Responsibility Examples in this program Must not own
Language and compiler General value semantics, resource use, transaction bindings, lowering and diagnostics Safe numeric domains, explicit bounded Cell selection, output correspondence AMM formulas, fee policy, LP issuance rules, order price policy
General standard library Reusable arithmetic and CKB operations with explicit contracts Wide product/division helpers, Script identity checks, bounded amount decoding A privileged asset or exchange protocol
Protocol package Assets, authority, persistent state, financial transitions and settlement rules Pool custody, LP mint/burn, partial fills, payment allocation Hidden backend behavior selected by protocol names
Builder and adapter Discovery, quoting, selection, construction, signing integration and recovery Live Cell queries, routes, deterministic allocation, stale-state rebuild Authority to relax on-chain checks or user limits
Evidence tooling Independent models, exact execution records and bounded measurements Financial differentials, hostile transactions, contention reports Reclassifying unexecuted or fixture-only cases as production evidence

"Asset/custody closure" is a required property of a protocol, not a proposed
keyword. Authors should express it with ordinary resources, actions, Locks,
identity checks, lifecycle relations and executable predicates wherever the
existing language suffices. Pool, Order, and LPReceipt remain
package-defined types.

Linear resource checking alone does not prove global token conservation,
authentic issuance, unique pool identity, or custody. Those properties also
depend on executed Script identities, authority, and actual transaction Cells.
An identity badge alone does not enforce a financial lifecycle.

2.2 Admission test for a compiler or library extension

Every proposed extension must include:

  1. A minimal failing application case and the exact missing semantic contract.
  2. Why existing source functions, libraries, bindings and adapters cannot
    satisfy it correctly within the accepted bounds.
  3. A business-neutral specification, plus at least one use outside AMMs or
    orders, such as escrow, auctions, payments or general asset accounting.
  4. The smallest owning layer, including an assessment of whether a library
    API suffices without new grammar.
  5. Compatibility impact and parser/type/lowering/metadata/checker/formatter/
    LSP/editor/WASM/builder changes that actually apply.
  6. Positive, adversarial and boundary evidence, resource budgets, and a
    named implementation issue before admission.

No codegen branch may recognize an action name such as swap, mint_lp, or
settle_order to inject business rules. No protocol-specific opcode or syntax
is planned. New runtime semantics must be explicit and fail closed outside
their admitted domain. Changing a helper's arithmetic meaning requires an
explicit compatibility decision; do not silently alter existing examples.

Reuse the existing adapter and package systems. Do not introduce a second
transaction serializer, alternate signer framework, or finance-specific
compiler pipeline. Compatible-open handles and runtime-selected open roles
remain separate work; exact admitted deployments are sufficient for the
initial bounded application unless evidence demonstrates otherwise.

3. Capability baseline and evidence limits

This is an initial inventory, not a completed capability audit. "Present"
means the cited implementation or evidence exists at the inspected baseline;
it does not certify every proposed application shape.

Capability Existing basis Remaining work for this plan Primary owner role
Checked numeric operations u128 emitter, runtime ABI tests, surface matrix Wide intermediate mulDiv, named rounding semantics, domain and conversion closure Arithmetic/compiler
Wide comparisons c256 emission, runtime helpers, iCKB order source Determine which constraints can reuse comparisons and which require new arithmetic; inspect sum carry limits Arithmetic/protocol
AMM actions AMM package source, bootstrap guide Persistent authentic custody, full asset/LP lifecycle and financial-sequence evidence Pool protocol
Narrow AMM execution swap fixture, scenario tests Real asset identities, fee/LP lifecycle, generated-builder execution beyond fixed-position quote checks Protocol/evidence
Order state and composition business corpus, anchor fixtures Cumulative entitlements, unified pool settlement and aggregate payment allocation Settlement protocol
Asset and authorization behavior fungible scenarios, crypto/authority matrix Selected external asset profile and pool-specific authority/issuance closure Asset protocol
Bounded inputs and outputs GroupInput contract, output Plan contract Exact cross-asset/group bindings and proof that declared bounds fit the application Protocol/compiler
Multi-artifact construction ProtocolBundle, CKB adapter Financial allocation semantics, discovery, quote/route selection and rebuild workflow Builder/settlement
Persistent policies and witnesses policy ABI, entry ABI Pool/order dispatch coverage, custody-trigger binding and external witness compatibility Protocol/builder
Time domains temporal contract Decide whether expiry is admitted; prove the chosen clock's enforcement and freshness assumptions Protocol
Independent evidence and costs artifact boundary, cost contract, 0.32 reports Financial model, lifecycle measurements, contention and third-party reproduction Evidence

Specific boundaries to preserve:

  • Checked u128 multiplication rejects an overflowing 128-bit product. A
    subsequent division does not rescue that expression even if the final
    quotient fits. General full-width narrowing from u128 is rejected in the
    inspected type checker.
  • Existing AMM source uses bounded u64 arithmetic and implements one explicit
    swap direction. Its presence does not prove a general external-token pool.
  • The narrow swap fixture checks a quote and reserve transition over selected
    transaction positions. It is not the complete custody/LP protocol.
  • Existing local-node acceptance has real verifier execution but explicitly
    records fixture-only resource identities; see the
    acceptance producer
    and report boundary. Those cases cannot satisfy
    authentic pool custody acceptance without new evidence.
  • Bounded GroupInput traversal selects the current complete Type Script
    group. It is not a generic cross-asset transaction iterator.
  • ProtocolBundle detects structural conflicts and materializes transactions.
    It does not automatically prove every financial obligation is paid once.
  • Existing SDK paths reach signing, submission and observed confirmation.
    Automatic financial state discovery, selection and competing-state rebuild
    remain distinct acceptance work.
  • Historical benchmark or release claims apply only to their pinned universe.
    Do not broaden them to this proposed financial portfolio.

M0 must produce a machine-readable inventory using the existing capability
taxonomy where applicable. Each row records source/test paths, exact evidence
identity, admission state, on-chain/builder/interface status, missing work,
owning layer, dependency, acceptance cases, compatibility and named owner.
Keep this new portfolio separate from frozen historical evidence; any gate
integration or existing ledger change needs an intentional scoped update.

4. Scope decisions required before executable protocol work

The following defaults are proposals for M0/M1 to freeze, not existing
compiler behavior. Every unresolved item gets a decision record with owner,
alternatives, selected bounds, rationale and executable acceptance mapping.

ID Decision Proposed initial direction Must be resolved by
D01 Asset profile Two distinct admitted standard fungible assets with exact Script identities; decide supported xUDT flags/extensions explicitly M1
D02 Custody topology Explicit reserve asset Cells linked to a unique persistent pool state and an enforced custody policy M1
D03 Pool identity Unique creation anchor, immutable asset pair and policy binding; exact uniqueness mechanism specified and executed M1
D04 LP representation and supply One authenticated share representation per pool; transfers/splits/merges preserve amount; every mint/burn requires the authentic matching pool transition; standalone destruction rejected M1
D05 Numeric domain u128 asset amounts with documented reserve/share ceilings and separately bounded intermediates M1
D06 Fees Fixed fee denominator and immutable rate per pool; fee remains in reserves; no admin fee withdrawal M1
D07 Initial and terminal liquidity Positive locked minimum shares with no redemption path; reject below-minimum initialization and pool draining M1
D08 Deposit residuals Proportional used amounts with explicit refunds; reject zero-share deposits M2
D09 Order pricing and fill economics Immutable rational price and cumulative minimum payment; freeze D09a-D09d below, including zero-payment, minimum fill and terminal dust rules Before FIN-06 protocol implementation
D10 Time No expiry in the first admitted profile unless a separate clock contract is completed; builder timeout is not on-chain expiry M1/M3
D11 Settlement allocation Initially distinct outputs per obligation, then explicit checked shared-output allocations M3/M4
D12 Route and batch bounds Fixed numeric limits from measured pilot shapes; distinct pools, each used once per transaction M4
D13 Deployment and upgrades Exact dependencies; no implicit upgrade/admin escape path; any upgrade policy requires separate analysis M1
D14 Capacity ownership Explicit funding, return and fee attribution for pool, reserve, order and LP Cells M1
D15 Unsolicited assets Define recognized custody inventory and surplus treatment; do not infer deposits from reserve-like data M1

D09 is incomplete until each subdecision is recorded with examples and
expected model/builder/verifier outcomes:

  • D09a: whether a fill with zero incremental payment is allowed, and the
    associated taker-visible economics.
  • D09b: the minimum sold-asset fill quantity and any minimum payment per fill;
    specify units, enforcement and effects on cumulative rounding.
  • D09c: final-fill exceptions, unfillable dust, and whether cancellation is
    required when the remaining amount cannot meet the ordinary fill rules.
  • D09d: whether overpayment is a donation or tracked future credit, including
    any effect of added per-fill payment floors on the maker's total receipts.

Resolve these before FIN-06 protocol implementation begins. Exploratory model
experiments may inform the choice, but the implementation must not silently
choose a policy through integer rounding or builder behavior. Cumulative maker
entitlement and fairness between takers are separate acceptance properties.

"Real assets" means genuine enforced token and custody Scripts in execution,
not necessarily assets with market value. Test-issued assets can meet
engineering acceptance and must remain labelled test assets. Arbitrary token
extensions, issuer powers and upgradeable assets are not assumed safe.

Stablecoins are not a prerequisite for the admitted pool, LP, order or routing
milestones. Test-issued assets with genuinely enforcing Scripts suffice for
engineering acceptance. Stablecoin integration, redemption availability and
market liquidity remain separate product dependencies, not compiler gates.

CKB capacity is accounted for separately from token amounts. A native-CKB
trading pair needs an explicit rule separating occupied capacity, tradable
capacity, fees and refundable deposits; it is not automatically included by
supporting two fungible-token assets.

5. Asset identity, custody and authority contract

5.1 Asset and pool identities

Bind each asset to the complete serialized Type Script identity, including
code hash, hash type and args, together with the selected chain/deployment
context and exact code dependencies. Tickers, decimals, schema names and a
code hash alone do not distinguish all assets. Display metadata must not affect
on-chain amount comparisons or authorize minting.

Pool identity must bind its creation anchor, ordered distinct asset pair,
custody policy, LP identity and immutable economic parameters. Specify whether
reverse asset order is normalized. Multiple pools for the same pair may be
allowed, but they must have distinct pool and LP identities.

5.2 Topology and invocation completeness

Before implementation, publish a transaction topology for every action:
input/output roles, complete Lock/Type identities, data layouts, dependencies,
witness owners, capacity owners, permitted counts and correspondence rules.

For each protected asset, identify the exact Script invocation that rejects
an unauthorized spend. Prove both directions of the association:

  • reserve spending requires the authentic matching pool transition;
  • a pool transition binds exactly the required reserve movements.

Matching a Type hash in data, selecting an action in a witness, or attaching a
ProtocolBundle is not sufficient. Raw hostile transactions that omit the
builder, omit the pool state, omit a reserve, or substitute a permissive policy
must fail under the actual transaction verifier.

Cover initialization, every update, destruction and unmatched group shapes.
Use a persistent policy for each state machine, with no alternative entry that
permits a weaker transition. Reserve and LP validation must remain mandatory
under missing, duplicated, substituted and unknown action dispatch records.

5.3 Accounting and authority

For every asset, specify a checked conservation equation over actual Cells:

sum(inputs) + authorized_mint = sum(outputs) + authorized_burn

The protocol may impose stronger conditions than the selected token Script.
For ordinary swaps/deposits/withdrawals, mint and burn of underlying assets
are zero. External asset issuer actions must not become an escape from pool
accounting. Check totals in a domain wide enough for the admitted Cell count.

LP creation must correspond to the prescribed pool supply increase; LP
redemption must consume authentic shares and reduce supply by the same amount.
Neither a user-defined LPReceipt schema nor a pool-id field establishes
issuance authority. The initial LP policy must enforce:

  • ordinary transfers and splits/merges preserve the total share amount for
    that complete LP identity;
  • every mint or burn requires the matching authentic pool transition and
    changes its total_lp by exactly the minted or burned amount;
  • standalone destruction without redemption is rejected, including consuming
    every share input with no LP output and no pool state;
  • the locked minimum cannot be redeemed or destroyed through any admitted
    action or token governance mode.

Thus total_lp denotes all live authentic shares, including the locked
minimum. Establish this invariant at creation and preserve it inductively;
do not require an off-chain inventory scan as proof of global supply. Define
ownership and every admitted transfer/split/merge shape. No holder should need
a maintainer signature for ordinary redemption.

The sUDT transfer rule
allows input amounts to exceed output amounts, enabling burns. The
xUDT documentation
retains sUDT rules with additional configured behavior. A generic token
representation therefore does not by itself establish this stronger LP
invariant. Identify the mandatory LP validation path under every admitted
transfer, issuance and owner mode; a removable holder Lock is insufficient.
Pin and test the selected implementation and configuration. Permitting
unredeemed destruction later requires an explicit redesign of the supply
denominator and remaining entitlement, not an exception in the builder.

Bind payouts to authenticated recipient commitments. Distinguish Lock
authorization, Type lifecycle validation and off-chain intent signatures.
Witness fields are untrusted unless checked; a copied owner value is not proof
of ownership. Capacity refunds and transaction fee funding need explicit
owners and cannot silently subsidize another participant.

For unsolicited transfers, state which Cells belong to the recognized reserve
inventory and why that inventory is complete. A builder/indexer omission must
not redefine authoritative reserves. Decide whether surplus is unrecognized,
rejected, or admitted by an explicit synchronization transition; test its
effect on shares and price. Do not assume scanning one Script group enumerates
all assets controlled by every related Lock.

6. Arithmetic and financial reference model

6.1 Required contracts

Specify reusable operations independently of pool/order policy:

  • checked addition, subtraction, multiplication, division and conversions;
  • mulDivFloor(a,b,d) and mulDivCeil(a,b,d) with declared operand,
    intermediate and result widths;
  • nonnegative integer square root with exact floor semantics;
  • exact product/product-sum comparison where it can avoid unnecessary division;
  • fixed-point representation only when a selected mechanism actually needs it.

API names here are descriptive, not admitted CellScript spellings. For each
operation, specify zero denominators, overflow, underflow, narrowing, zero
inputs and error behavior. Ceiling division must not use an overflowing
n + d - 1 shortcut. Preserve existing operator contracts.

Two u128 factors can require 256 bits; multiplying again by a fee scale or
summing products can require additional bits. Document a width proof for each
formula. "Uses c256" alone is not a proof that every intermediate fits.
If restricted domains are chosen, check them on-chain before arithmetic and
publish rejected ranges in the public API and builder.

For an optional builder-computed quotient verified on-chain, the verifier must
prove the rounding relation, not merely a loose price inequality. For example,
floor division requires q*d <= a*b < (q+1)*d for positive d, with a safe
representation even at the maximum q. Similarly specify square-root
verification without overflowing (q+1)^2. Compare this approach with direct
computation by correctness, witness size and complete-operation cost.

6.2 Independent model and sequence properties

Use a separately implemented arbitrary-precision integer/rational reference
model in the repository's native tooling stack. Do not reuse production
arithmetic helpers or add retired interpreter tooling. Any new dependency
requires an explicit dependency decision and the matching gates.

Record reproducible seeds, generated domains, shrunk counterexamples and
independently calculated expected values. Compare model, builder and actual
CKB-VM results. Required coverage includes:

  • zero/one/maximum amounts, every range boundary and just-outside values;
  • unequal reserves, small deposits, large shares and representable results
    with overflowing narrow intermediate products;
  • fee/rounding boundaries and conversion limits;
  • repeated deposit/swap/withdraw sequences, alternating directions and
    multiple users;
  • split versus single order fills, final dust and cancellation after fills;
  • arbitrary direct payments/donations under the chosen surplus rule.

Measure rounding loss and distinguish intended fees, slippage and donations
from an accounting error. State sequence invariants and their assumptions;
finite differential tests do not constitute a universal proof.

7. Constant-product pool and LP lifecycle

7.1 Proposed financial specification

The following equations are a candidate specification to freeze in M1. They
describe mathematical integers, not code with implicitly sufficient widths.
Use the same specification in source, builder, reference model and docs.

Let x,y > 0 be reserves, L > 0 total shares including locked minimum
shares, F > 0 fee denominator, and 0 <= f < F fee rate numerator.

Operation Candidate rule Mandatory checks
Initialize L = floor_sqrt(a*b); provider receives L - L_min Genuine deposits; L > L_min > 0; unique pool and authentic locked shares
Deposit s = min(floor(a_max*L/x), floor(b_max*L/y)); use a = ceil(s*x/L), b = ceil(s*y/L) s > 0; a <= a_max, b <= b_max; user minimum shares; refund unused amounts; L' = L+s
Withdraw a = floor(s*x/L), b = floor(s*y/L) Authentic user shares; locked minimum not redeemable; both minimum outputs; policy for zero payouts; L' = L-s
A to B swap n = a*(F-f); b = floor(y*n/(x*F+n)) Positive input/output; b < y; user minimum output; x' = x+a, y' = y-b; shares unchanged
B to A swap Symmetric rule with asset roles exchanged Same domain, custody, limit and output checks

The candidate swap rule retains fees in reserves and must satisfy the
fee-adjusted relation (x*F + a*(F-f))*(y-b) >= x*y*F, plus the exact rounding
rule if exact quoted output is required. Prove/check the relevant widths.
The existing example instead computes a rounded fee before its quote; the
new package must explicitly document this difference and must not silently
change historical fixtures to a different fee convention.

Specify the admitted maximum fee and immutable fee encoding separately from
the mathematical range above. No protocol-fee collection, dynamic fee,
rebasing asset or transfer-tax assumption is included in this initial profile.

7.2 Required lifecycle evidence

Execute one continuous state chain with authentic assets and LP authority:
initialize; transfer/split shares if admitted; second-provider deposit;
both swap directions; partial withdrawals; redemption of all circulating
shares subject to the locked minimum. Feed actual prior outputs into later
transactions. Record remaining locked shares, reserve dust and capacity.

Reject forged LPs, unauthorized mint/burn, standalone LP destruction,
cross-pool shares, duplicate pool creation, reserve-only spends, fake reserve
identities, pool state without reserve movement, wrong recipient, surplus
ambiguity, missing/extra group Cells and malformed witnesses. Test unrelated
Cells and multiple groups explicitly, not only fixed transaction indexes.

Reject output permutations that invalidate role bindings, recipient
commitments or allocation references. Test semantically equivalent
permutations according to the admitted layout contract: if arbitrary placement
is allowed, reconstruct every affected reference and authorization and require
acceptance; if canonical order is mandatory, specify that rule and reject
noncanonical layouts even after references are updated. A mutation of an
already signed transaction is a distinct authorization-negative case. Tests
must not accidentally promote the current builder's preferred order into a
protocol requirement.

Use real asset Type Scripts and custody Locks for application acceptance.
Always-success fixtures remain useful unit fixtures but are excluded from
this milestone's custody claim. A full-transaction verifier must execute all
participating Scripts; executing only the pool ELF is insufficient.

8. Partially fillable orders

Freeze the sold/requested asset identities, maximum sold amount, immutable
price, proceeds recipient, remainder recipient, creation authority, cancel
authority and any expiry policy. Creation must escrow the actual sold asset.
Filling need not require the maker online, but every transition must enforce
their committed terms and custody rules.

A candidate rounding policy uses cumulative entitlement. With immutable price
N/D, positive N,D, and cumulative sold amount z, define
Q(z) = ceil(z*N/D). A fill from z0 to z1 owes at least
Q(z1) - Q(z0), with 0 <= z0 < z1 <= original_amount. Bind the cumulative
state to the authentic order successor; it cannot be reset on a partial fill.

Decide explicitly whether surplus payment is a donation or future credit.
The proposed baseline treats it as surplus, never as unrecorded credit that
can reduce later obligations. Specify zero incremental-payment fills, minimum
fill size, final-fill exception and dust through D09a-D09d before FIN-06
protocol implementation, not only before final acceptance.

For example, with N/D = 1/3, successive one-unit fills have cumulative
minimum-payment increments 1, 0, 0. This meets the maker's cumulative
minimum but charges different takers differently. It does not establish
per-fill fairness. If a positive per-fill payment floor is added, the three
fills may pay more in total than one three-unit fill; document that changed
economics and whether excess is credited. Require executable cases for the
chosen behavior, rejected alternatives, different takers, fill partitioning,
terminal dust and cancellation. The builder must expose the actual per-fill
payment and residual entitlement from the accepted policy.

Required operations: create, multiple partial fills, final fill, and owner
cancellation after zero or more fills. Final fill/cancellation closes the
order and returns the correct remaining assets and capacity. Cancellation
cannot undo an already committed fill. Competing fill/cancel transactions
must refer to the same live order state, with stale outcomes tested at the
node boundary rather than inferred solely from an in-memory live set.

Expiry is optional for the first profile, but any supported expiry needs an
exact temporal domain and chain-enforced semantics. A chosen HeaderDep or
builder wall clock alone must not be described as authoritative current time.
An upper validity bound cannot be assumed from a lower-bound since check.
If sound expiry cannot be enforced under the selected construction, reject
the feature and document cancellation as the available lifecycle operation.

9. Composable settlement and payment allocation

9.1 On-chain accounting requirements

Begin with one order and one pool, using distinct payment outputs. Introduce
shared outputs only after an explicit allocation contract is admitted.

For output o, asset a and obligation i, let allocation(i,o,a) be the
claimed credited amount. The contract must establish:

  • every referenced output exists and has the required asset, recipient and
    capacity policy;
  • each obligation receives at least its required sum;
  • the sum of allocations charged against an output does not exceed its
    available amount;
  • allocation entries are canonical and cannot be replayed under another
    order, pool, role or transaction binding;
  • all participating assets satisfy the actual input/output conservation and
    custody rules, including fees, change and intermediate flows.

The key counterexample is two obligations of 100 to one recipient with only a
single output of 100. Two successful local "recipient received 100" predicates
must not accept the combined transaction.

Global allocation validation must be mandatory on-chain. Select either a
shared settlement verifier that every participant provably requires, or a
bounded complete allocation view checked by the relevant participants. Record
why an attacker cannot omit the coordinator, hide another obligation, split
an allocation table or substitute an unchecked entry. A builder-only conflict
check is insufficient.

Distinguish compatible checks from duplicated credit. An asset Type Script
checking conservation and an order checking its payment may legitimately
observe the same output. The allocation rule prevents competing economic
obligations from spending the same value; it must not reject necessary
Lock/Type shared observation.

9.2 Supported composition slices

Slice Admitted shape Required rejection cases
C1 One order, one pool, distinct obligation outputs Wrong price, recipient or asset; reserve/order mismatch; omitted participant
C2 Multiple orders with explicit shared-output allocations Duplicated credit, hidden obligation, insufficient aggregate payout, overflow, duplicate IDs
C3 Bounded multihop route across distinct pools Missing intermediate value, substituted pool, broken route amount, same pool repeated, excessive hops
C4 Each preceding shape with unrelated inputs/outputs and layout-contract permutation cases Accidental membership, unrelated-payment capture, stale role/allocation references and witness interference; accept equivalent reconstructed permutations where the layout contract permits

A route is one transaction constraint system. Intermediate value may be
represented through a specified netted flow; do not assume an output Cell can
also be consumed as an input in the same transaction. Bind every pool's reserve
deltas and every intermediate asset balance to the global flow.

Initially allow each pool once per transaction. Repeated-pool routes and
cyclic routes require a separate ordered-transition or netting specification.
No unbounded batch, unrestricted Script selection, or generic router claim
follows from C1-C4. Freeze numeric limits for pools, orders, inputs, outputs,
allocation entries, dependencies, witnesses and bytes before final runs.

10. Builders, observation and contention

Extend existing generated builders and the CKB adapter; keep compiler-owned
encodings and witness ownership authoritative. Generated output must support
the accepted application without hand-replacing the verifier or hand-encoding
its witness payloads.

Provide the lifecycle:

discover -> resolve identities/live Cells -> quote against observed state
  -> select funding and capacity -> allocate -> encode -> preflight
  -> sign -> signed dry-run -> submit -> observe confirmation

Discovery is an off-chain convenience; authoritative validation uses concrete
Cells, scripts and transaction bytes. Record chain/genesis, state OutPoints,
code dependencies, observation time and quote assumptions. Detect incomplete,
unavailable and stale observations without calling them execution rejection.

Expose input/output amounts, rounding, fees, occupied/refundable capacity,
slippage constraints, supported bounds and the transaction identity to the
caller before signing. Preserve WitnessArgs ownership across standard Locks,
CellScript policies and admitted token extensions; test incompatible layouts
as explicit construction failures.

Classify failures separately: discovery unavailable, unsupported construction,
stale input, preflight rejection, signature rejection, VM rejection, pool
admission rejection, submission outcome unknown, and confirmation change.
After a timeout, query the original transaction before creating a replacement;
do not accidentally repeat an already accepted economic operation.

Rebuilding must refresh Cells and dependencies, recompute quotes and capacity,
regenerate outputs/witnesses and obtain a valid signature for the new bytes.
It must preserve the original intent's asset, recipient, maximum spend,
minimum received and permitted time constraints. A retry policy cannot
silently weaken them. Define maximum retries, backoff, cancellation and
terminal errors. Do not persist private keys in evidence artifacts.

Exercise at least two independent builders against the same pool and against
the same order, plus a nonconflicting-pool control. Include fill versus cancel,
state spent between preflight and submission, RPC timeout and changed observed
inclusion. Record successful operations, conflicts, rebuilds, latency and
terminal outcomes. Shared pool state contention must be measured; batching or
partitioning proposals need separate correctness and performance evidence.

11. Milestones, dependencies and acceptance

Owners below are responsibility roles. Actual assignees and reviewers are
unassigned until M0; implementation child issues remain to be assigned. Work
item IDs are local planning IDs, not GitHub issue numbers. Each implementation issue
must name an accountable owner, reviewer, exact inputs/outputs and evidence.

Milestone / work items Owner role Dependencies Deliverable and exit condition
M0 / FIN-01: baseline and work breakdown Program + evidence None Revalidated capability matrix; named owners/reviewers; child issue links; explicit gaps and evidence ceilings; implementation slice selected
M1 / FIN-02: custody and identities Protocol + reviewer M0 D01-D07, D13-D15 frozen; topology for every operation; no-bypass invocation argument; joint exercise in section 11.1, including standalone LP burn rejection
M1 / FIN-03: numeric contract Arithmetic + reviewer M0, topology constraints from FIN-02 Width/rounding specification, independent model, minimal reusable extensions admitted, full-boundary positives/negatives
M2 / FIN-04: pool and generated builders Pool + builder FIN-02, FIN-03 D08/D10 frozen; genuine continuous LP/pool lifecycle; both swap directions; real authorization and capacity checks; frozen costs pass
M2 / FIN-05: early external integration Developer experience First FIN-04 runnable path Outside developer instantiates a second pool with a different admitted asset pair and parameters using documented interfaces; manual gaps logged and material API defects resolved
M3 / FIN-06: orders Order + builder FIN-02, FIN-03; D09a-D09d and order D10 frozen before protocol implementation Create, repeated fill, final fill and cancel; cumulative and per-fill rounding, dust, custody and stale-state tests
M3 / FIN-07: order/pool settlement Settlement + evidence FIN-04, FIN-06 C1 and unrelated-Cell variants; mandatory on-chain flow checks; exact generated construction
M4 / FIN-08: shared outputs and routes Settlement + builder FIN-07 D11/D12 frozen; C2-C4; aggregate allocation and intermediate conservation; published bounds
M5 / FIN-09: operational recovery and budgets Builder + performance Retry prototype begins in M2; final suite after M4 Conflicting builders, unknown submission recovery, preserved intent, complete-operation budgets and retained failures
M6 / FIN-10: independent reproduction and closure External developer + evidence/reviewer M2-M5 Outside integration composes the second pool through documented interfaces, including settlement/failures; exact evidence replay; material gaps closed; matching final gates and limitations recorded

FIN-02 and FIN-03 should inform each other; do not finish a generic math library
before knowing the selected protocol's domains. Generated construction enters
the first M1 exercise; complete builder acceptance starts in M2. The dependency
table permits independent work but does not itself request parallel agents or
assign release dates.

Each milestone has four states: proposed, implementing, evidence-pending,
accepted. Unknown results stay unknown; failed checks stay failed. An owner
records what changed, exact artifact/evidence references, unresolved risks,
review disposition and next eligible milestone. No percentage-complete score
substitutes for acceptance conditions.

11.1 First joint FIN-02/FIN-03 implementation exercise

After M0 and the relevant M1 decisions, implement the smallest continuous
transaction sequence that tests custody and arithmetic together:

  1. Issue two test assets with genuine enforcing Type Scripts and valid
    issuance authority; record their exact identities and selected modes.
  2. Create one uniquely identified pool with authenticated reserve custody,
    authentic LP issuance and the locked minimum defined by D04/D07.
  3. Construct and execute one successful swap through generated encoding and
    the existing adapter, comparing its amounts with the independent model.
  4. Redeem circulating LP shares through a valid withdrawal, recording the
    exact supply/reserve changes and remaining locked shares and capacity.
  5. Execute hostile variants for reserve-only spending, forged LP redemption,
    omitted pool state, substituted asset identity and standalone LP burning.

Run positive and hostile transactions through the complete transaction
verifier with all asset, custody, LP and pool Scripts active. A negative case
must reach and fail the intended enforcement boundary, not merely fail due to
an unrelated invalid signature or malformed transaction. Use valid holder
authorization for the standalone-burn attempt so it tests LP policy.

Retain topology, source/build identities, actual prior-output continuity,
generated-construction artifacts, transaction hashes, expected/actual failure
layers and preliminary resource measurements. State the spike's exact amount,
layout and action bounds. It may exercise only one swap direction; it does
not close M2's complete lifecycle, full numeric domain or final budgets.

Use concrete failed expressions, bindings or construction requirements from
this exercise to propose the smallest missing library/compiler capabilities
under section 2.2. Do not satisfy the exercise by hand-replacing the generated
pool/LP/custody verifier; existing independently admitted asset and standard
authorization Scripts remain explicit dependencies. Shared-output settlement,
multihop routes and additional financial products follow after this boundary.

12. Evidence and resource acceptance

12.1 Required case families

Family Required positive evidence Required adversarial evidence
Arithmetic Independent exact results across admitted ranges Overflow, zero divisor, bad rounding witness, unsafe narrowing, just-outside bounds
Custody and LP Authentic initialization, amount-preserving transfers/splits/merges if admitted, deposit and redemption with matching supply changes Forged shares, standalone destruction including no LP outputs, locked-minimum destruction, missing custody trigger, alternate policy, wrong asset/pool, unauthorized mint/burn
Financial sequences Multi-user deposits/swaps/withdrawals with model agreement Cumulative rounding exploitation, donation ambiguity, dust extraction, zero-share and excessive-withdrawal attempts
Orders Repeated partial fills across different takers, explicit zero-payment/minimum-fill outcomes, terminal fill and cancellation Reset cumulative state, forbidden zero-payment/dust shape under D09, underpayment, wrong recipient, stale order and forged successor
Composition C1-C4 under complete transaction execution, including equivalent reconstructed permutations permitted by the layout contract Duplicate credit, invalidated role/recipient/allocation bindings, noncanonical order where mandated, omitted verifier, missing intermediate, repeated pool, excessive batch, unrelated-Cell substitution
Builder Generated construction, signing, submission and observed confirmation Stale quotes, conflicting spends, unavailable RPC, unknown submission, limit-changing retry
Artifact boundary Compiler-produced bundles accepted by independent checker Deterministic mutations for every changed machine/metadata contract

Use actual transaction syscall context for financial acceptance. The v1
package runner's local Cell bookkeeping is not a substitute for injecting
transaction context into executing Scripts. Prefer the existing full
transaction harness and pinned node acceptance infrastructure.

12.2 Evidence record

Before implementation acceptance, define a bounded versioned report retaining:

  • root/package source commits and digests, clean/dirty state, lockfiles and
    exact submodule revisions;
  • compiler/checker/toolchain versions and identities, flags, source edition,
    target profile, metadata/lowering/source-map identities;
  • every ELF and external Script hash, deployment Script, code dependency and
    witness/builder interface identity;
  • model version, scenario ID, input sequence/seed, expectations and actual
    results, including stable failure and enforcement layer;
  • raw and serialized transaction hashes, resolved input/output context,
    actual VM/node identities, chain/genesis where relevant;
  • simulation, VM, node admission, submission, confirmation, deployment and
    review as separate evidence fields;
  • original and rebuilt transaction identities, retry causes and intent
    constraints for contention cases;
  • metrics, budget revision, unavailable reasons and reproduction instructions.

Independent artifact checking establishes its admitted machine/typed contract,
not universal source equivalence or financial correctness. An external
developer exercise establishes usability, not independent security review.

12.3 Budgets and measurement protocol

Dimension Required measurement
Execution Full-transaction cycles for successes and failures, including expensive late rejection; per-group attribution only where observed
Code Each deployed ELF and total distinct code footprint; sharing/deduplication policy stated
Transaction Canonical serialized bytes, witness bytes, input/output and dependency counts
State Occupied and refundable capacity for state, reserves, orders and LPs
Memory Static bounds and observed stack/memory with their different meanings retained
Construction Discovery, quote, construction, preflight and signing-adapter time under a recorded environment
Contention Offered load, successful throughput, conflicts, retries, terminal failures and latency distribution
Finance Fees, price impact, rounding residuals, share/reserve changes and accumulated loss over sequences

Run labelled exploratory pilots to select practical domains and numeric
ceilings. Freeze per-case/per-metric budgets and worst-case shapes before
final acceptance runs. Numeric ceilings are intentionally not invented in
this planning document; missing frozen ceilings block acceptance. Do not
regenerate budgets from a failing final run. A justified scope/budget change
needs a separately recorded decision and preserves the old result.

Specify host hardware, node configuration, VM identity, RPC placement, cache
state, repetitions and warmup policy for timing. Include minimum, typical and
maximum admitted shapes, not only arithmetic microbenchmarks. Retain missing
observations as unavailable instead of zero. Publish the sustainable result
under the tested contention pattern without claiming network-wide throughput.

13. Compatibility, implementation locations and validation

Reuse the root package infrastructure, formal CKB adapter, independent checker
and cellscript-tools. Place new protocol packages under an agreed repository
location at M0; keep CellScript filenames descriptive and version-neutral.
Do not move existing examples or rewrite historical receipts merely to make
the new inventory appear complete.

For each accepted compiler/library prerequisite, record impacts on source
semantics, public interfaces, package/compiler requirements, runtime errors,
ABI, schemas, builder bindings, checker and artifact cache identities. Version
only the boundaries that actually change. Preserve native-I/O feature gating,
metadata-only browser behavior and the existing WASM size budget.

Changes to admitted grammar require complete parser, formatter, type, IR,
metadata, LSP/editor, example and syntax-combination parity. Backend changes
must preserve assembler closure, explicit register/stack contracts and
independent checker separation. New checker invariants require valid fixtures
and deterministic negative mutations.

Validation uses the existing entry points:

# Before committing implementation or documentation changes
./scripts/cellscript_gate.sh dev

# Before claiming merge readiness
./scripts/cellscript_gate.sh ci

# For IR, backend, ABI, ELF or RISC-V changes
./scripts/cellscript_gate.sh backend

Focused tests supplement these gates and must be existing commands or commands
introduced through the project's normal manifest/gate contract. Plan-only
link/whitespace checks are not a claim that the implementation gates passed.
Record the exact final source tested; rerun affected checks after changes.

Release and production claims follow the full
gate policy and
verification tutorial,
including required tooling and acceptance infrastructure. Do not use
release-quick as external live evidence. Do not run release/deployment work
merely because this plan exists.

14. External developer acceptance

Start with M2 and repeat at M6. A developer outside the implementation team
must independently install the documented toolchain/packages, construct a
meaningful application, run its success/failure paths and reproduce the
relevant evidence. M6 includes order/pool settlement and recovery handling.

Package reuse is mandatory. At M2 the developer must instantiate a second
pool with a different admitted asset pair and different permitted economic
parameters, then exercise its lifecycle through the documented interfaces.
At least one complete asset identity must differ from the implementation
team's reference pair; renaming ticker/display metadata does not count. Choose
parameters within the frozen profile, such as a different supported fee rate
and initial reserves. Expected package configuration and reproducible builds
are allowed; compiler changes, hidden fixture assumptions and maintainer-built
transactions are not.

At M6 the developer must compose the second pool into an admitted settlement
or distinct-pool route through the documented interfaces, and exercise failure
and recovery handling. Use a shared intermediate asset where a route requires
it. Record both pools' exact asset, policy and deployment identities and verify
that cross-pool LP or state substitution fails. This remains within bounded
exact-deployment composition; it does not require generic open routing.

Record every manual step, undocumented assumption, maintainer intervention,
missing interface and direct verifier modification. Providing documented
application parameters is expected; hand-replacing generated verifiers,
hand-encoding compiler-owned witnesses or relying on a maintainer to assemble
transactions fails this milestone. Fix material gaps and repeat affected
flows. A scripted self-test by the implementer does not count as this exercise.

15. Deferred work and external dependencies

  • Concentrated liquidity: tick/position representation, fee growth, traversal
    bounds and per-position accounting after the constant-product baseline.
  • Oracles/TWAP: observation authority, sampling, temporal semantics,
    manipulation and stale-data behavior in a separate security contract.
  • Vaults and isolated lending: share accounting, interest, valuation,
    liquidation execution/incentives, stress scenarios and bad debt handling.
  • Cross-collateral lending, derivatives, flash-loan semantics, repeated-pool
    routes, generic open routing and state partitioning: separate proposals.
  • Stablecoin integration, redemption routes, LP depth and market operations:
    external product dependencies, tracked separately from compiler closure.
  • Public deployment, release publication, governance and emergency/upgrade
    mechanisms: separately scoped decisions and authorization.

No NovaSeal agreement profile is treated as proof of general lending support.
No prior 0.30/0.31 release exception or 0.32 review waiver automatically applies
to this program. Review requirements must be resolved for this exact scope;
an explicit waiver, if granted, is recorded as a waiver rather than a review.

16. Completion checklist

  • Revalidated baseline, named owners/reviewers and accepted child issues.
  • Frozen asset/custody/LP topology, exact supply preservation and standalone-burn rejection.
  • First joint custody/arithmetic exercise passes with full-transaction adversarial evidence.
  • General arithmetic contracts and independent high-precision model.
  • Genuine pool lifecycle with generated builders and authentic assets.
  • D09a-D09d frozen before order implementation; cumulative/per-fill rounding, dust and cancellation executed.
  • On-chain single-order/pool settlement and explicit payment attribution.
  • Bounded shared-output and multihop composition with published limits and explicit permutation behavior.
  • Competing-state rebuild preserves intent and handles unknown submission.
  • Complete-operation measurements pass pre-frozen numeric budgets.
  • Exact artifact, transaction, VM/node and source evidence is reproducible.
  • External developer instantiates and composes a second pool without compiler changes or replacing generated code.
  • Scope-specific review disposition, matching gates and limitations recorded.

17. Normative implementation references

Repository contracts take precedence for CellScript behavior:

For CKB implementation decisions, verify version-sensitive details against
official documentation and the exact pinned upstream source:

This plan records intended work and explicit acceptance boundaries. It is not
an execution report, a release receipt or deployment authorization.

Activity

  1. changed the title [-][Research → Implementation] EVM-class finance on CKB with CellScript[/-] [+][DeFi][Application/Protocol] EVM-class finance on CKB with CellScript[/+] on Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions