Skip to content

[DeFi][FIN-15] Bounded cross-tick swaps with exact-input and exact-output settlement #65

Open

Description

@a19q3

Umbrella: #43 · Proposed application capability · FIN work-item FIN-15. No milestone, implementer, reviewer or release approval is implied.

What problem does this solve? — In plain English

A large swap may traverse several price ranges. Every crossed tick, liquidity change and fee must be checked before final balances and user limits are accepted.

Visual explanation

flowchart TD
A["Initial pool + price limit"] --> B["Read next authenticated tick"]
B --> C["Apply exact swap step"]
C --> D{"More amount and bounds?"}
D -- Yes --> B
D -- No --> E["Verify final price, fees, assets and state"]
Loading

Primary implementation layer: Pool execution protocol.

Dependencies / start conditions: FIN-12 mathematical steps; FIN-13 complete tick traversal; FIN-14 position/fee accounting.

Detailed design and security review

What a successful swap must prove

A large swap can exhaust the liquidity available before the next tick, cross several authenticated boundaries and finish at a limit price or when the specified amount is consumed. The pool's true final balance and price must follow this entire ordered sequence. The independent tick proof (#63) is authoritative, not a builder-supplied list of convenient boundaries.

Transaction contract

Define a fixed maximum number of executed steps, traversed pages, input/output Cell roles and intermediate state entries. Require the start pool identity/root, admitted price limit, exact input or target output, direction, fee mode, hook mode (initially none), complete successor state and canonical signed amounts. At every step: identify the next authenticated tick, compute rounded in/out/fee using #62, update price, then update active liquidity if a tick was crossed. Tick ties, zero-liquidity ranges, exact-boundary terminations and the first-step/last-step transitions must have explicit rules.

The pool may return partial execution at a price limit only if its specified contract allows it; the user's high-level exact-output order must still be rejected if the requested output is not delivered. The builder must refund unused exact-input amounts and never treat a slippage limit as permission to overspend.

Implementation phases

  1. One swap step against a single active interval, with all inputs/outputs and fees bound to actual CKB Cells.
  2. Multi-step swap within one authenticated page; then across two or more pages.
  3. Both asset directions and both specified-amount modes, with reproducible high-precision model/VM/SDK parity.
  4. Integrate operation-level limits and inspect maximum late rejection costs before admitting a production-shaped profile.

Attack and edge matrix

Input Required result
Omit intermediate initialised tick Reject due to incomplete next-boundary proof
Incorrect liquidity net on crossing Reject actual tick/pool successor
Hit price limit with unsatisfied exact-output intent Reject at intent/adapter contract
Exhaust entire active liquidity Defined partial or reject; never negative reserves
Wrong fee, rounded output or final sqrt-price Reject
Reordered swap steps or repeated state snapshot Reject continuity
More steps/pages than frozen maximum Deterministic bounded rejection

Evidence

Publish at least one authentic multi-pool reference corpus and one independent per-tick arithmetic oracle. Keep total cycles, source identity, exact generated bytes, occupied capacity, final reserves, fee liabilities and each crossed tick observable. Do not present one quote fixture as an entire liquidity lifecycle.

State and execution flow

flowchart TD
    S["Authenticate start state and user intent"] --> T["Prove nearest initialized tick"]
    T --> Q["Calculate exact fee, price and amount step"]
    Q --> C{"Continue within frozen bounds?"}
    C -- Yes --> T
    C -- No --> F["Check final price, reserves, output and limit"]
    F --> V["All required Script groups accept"]
Loading

General implementation, evidence and release policy

  • Preserve business-neutral CellScript semantics: exact Script handles, typed transaction views, resource ownership, bounded execution and independent machine checking. Missing general primitives require separate, narrowly scoped issues and actual failing use cases.
  • Freeze chosen data/ABI/profile, maxima, code deployment and review disposition before implementation admission. Record positive and hostile CKB-VM tests over complete transactions with correct signature setup, exact ELF/CellDep identities, state predecessors/successors and separate costs for VM cycles, witness bytes and occupied capacity.
  • Builder checks and ProtocolBundle dry-runs are helpful but do not replace on-chain authority. No automatic public deployment, external audit claim or core compiler release follows from a completed protocol issue.

Implementation scope

  • Implement bounded step-by-step price movement in both directions and both specified-amount modes; preserve exact tick-crossing and active-liquidity state.
  • Specify partial-execution semantics and the separate periphery guarantee required to satisfy exact-output intent; handle price limits, liquidity gaps and exhausted ranges.
  • Use authenticated intermediate state and actual Cells; supplied step transcripts remain untrusted until independently checked.

Acceptance checklist

  • Representative multi-tick and cross-page transactions match independent calculations and on-chain state transitions for both directions and amount modes.
  • Edge cases: zero/low liquidity, min/max sqrt price, empty intervals, exact boundary, one-unit amount, max traversal and insufficient output.
  • Skipped tick, wrong liquidity net, misordered crossing, changed step amounts, inconsistent final tick/price, stale state and over-limit traversal reject.
  • Full transaction Script groups, cycle/stack/tx-byte bounds and both user-level max-input/min-output checks are observed.

Explicit boundary: Do not equate a pool-level partially fulfilled trade with a successful user-level exact-output swap.

General scope and evidence gate

  • This is application/protocol/SDK work, not a new CellScript grammar feature, VM opcode or finance-name-specific code generation.
  • Before acceptance: freeze semantic contract, threat model, limits, role/authority boundary and accountable implementer/review disposition (unassigned initially).
  • Run independently modelled positives and targeted adversarial cases in actual CKB-VM with all required Script groups, pinned sources/artifact/CellDep/transaction identities and the applicable dev/CI/backend gates. Distinguish node and public deployment evidence.
  • A demonstrably missing business-neutral language capability needs a separate general-purpose issue and independent-checker/ABI/diagnostic acceptance. Opening this issue is not release authorisation.

Verified GitHub dependency links

Core: #62, #63, #64. Downstream: #66 ordered settlement, #71 custom accounting, #73 Oracle, #75 routing.

These are planning links, not executed acceptance or formal GitHub blocking relationships. Parent: #43.

Verified dependencies and implementation sequencing

Hard prerequisites: #62 arithmetic, #63 complete next-tick proof, #64 authentic position/liquidity state.

Unblocks: #66 complete multi-operation integration, #71 custom pricing, #73 observations, #75 router.

Status: These are explanatory GitHub cross-links and do not set native GitHub blocking relationships, authorise a compiler change, or certify dependent implementation.

Activity

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