Repository navigation
[DeFi][FIN-12] Checked tick pricing, fixed-point arithmetic and exact swap-step maths #62
Description
Umbrella: #43 · Proposed application capability · FIN work-item FIN-12. No milestone, implementer, reviewer or release approval is implied.
What problem does this solve? — In plain English
Range-based swaps need exact price-to-tick calculations and carefully rounded maths. A tiny rounding error can mint value or charge the wrong amount.
Visual explanation
flowchart LR
A["Amount / price / liquidity"] --> B["Bounded wide arithmetic"]
B --> C["Tick and sqrt-price conversions"]
C --> D["One swap step + explicit rounding"]
D --> E["Reference/model/CKB-VM parity"]
Primary implementation layer: Protocol maths + conditional general arithmetic stdlib.
Dependencies / start conditions: #53 arithmetic semantics and independent model; FIN-11 for chosen numerical boundaries.
Detailed design and security review
Numerical contract before implementation
Define named application-library domains for signed Tick, nonnegative SqrtPrice, Liquidity, Amount and signed BalanceDelta, with frozen fixed-point scale, tick base/spacing, lower/upper endpoints, width and conversion rules. These are normal value types and library functions, not compiler keywords. For inverse price→tick, state the exact floor rule at every representational discontinuity.
Existing checked u128 operations do not automatically support a mathematically representable quotient whose product needs a wider intermediate. Either supply an independently checked wide mul-div, or reject a precisely documented bounded input domain. Rounding must favour the party required by the economic invariant: distinguish amounts owed to the pool from amounts paid out by the pool, including negative deltas.
Implementation sequence
- Freeze a specification independent of production arithmetic: integer/rational equations, type units, error precedence and fee application.
- Implement tick↔sqrt-price conversion with exact boundary vectors, monotonicity and spacing checks.
- Implement amount delta / liquidity conversion for below-range, in-range and above-range price regions.
- Implement a one-step swap for each asset direction and each specified-amount mode, returning consumed amount, output, fee, next sqrt price and whether a boundary was reached.
- Compare safe on-chain calculations against independent big-integer model, generated SDK quote and exact CKB-VM transaction fixtures; preserve counterexamples.
Test matrix
| Input class | Required behaviour |
|---|---|
| Tick min/max, zero, +/-1, spacing boundaries | Correct conversion and monotonicity |
| Just below/at/above sqrt-price boundary | Exact inverse tick and deterministic rounding |
| Tiny amount with fee greater than usable input | Defined zero-output or rejection |
| Large operands with overflowing narrow product | Correct wide result or explicit admitted-domain rejection |
| Opposite swap direction / exact-output inverse | Model-consistent deltas and safe user limits |
| Negative signed delta and extreme narrowing | No wraparound or sign confusion |
Integration and compatibility
Keep fee-policy equations in the protocol package; reusable arithmetic helpers may go to a general stdlib only with a non-financial use case. Do not silently change existing example fee rounding. Record differentiated vectors if intentionally non-equivalent. Publish proof of intermediate widths, per-case cycles/ELF/stack and exact error codes. #64 owns liquidity state; #65 owns repeated swap steps.
Security flow
flowchart LR
T["Typed tick/price/liquidity"] --> W["Checked wide intermediates"]
W --> S["One exact rounded step"]
S --> M["Independent mathematical oracle"]
S --> V["Compiled CKB verifier"]
M --> Q{"Same admitted result?"}
V --> Q
Source-contract and release discipline
- Reuse the existing CellScript transaction-view, resource-lifecycle, exact Script-handle, ProtocolBundle and generated-builder contracts. Do not invent a finance-specific parser/IR/codegen branch, implicit cross-Script call or a second transaction serializer.
- Freeze the semantic support matrix, named implementation owner, explicit reviewer/waiver disposition, transaction and byte budgets before acceptance. An arbitrary unchecked witness is not execution evidence.
- Full-transaction CKB-VM adversarial negatives must fail at the intended enforcing Script with otherwise-valid signatures and correctly constructed participating groups. Maintain source/ELF/CellDep/transaction/node identities, independent reference vectors, full gates and disclosed unknown outcomes.
- These issues do not assert public deployment or a new compiler release.
Implementation scope
- Implement signed tick↔sqrt-price, fixed-point operations, liquidity/amount deltas and single-step exact-input/exact-output swaps as reusable protocol library functions.
- Freeze widths, signed arithmetic, units, tick and price endpoints, overflow/underflow, floor/ceil direction and exact representable result rules.
- Use general safe multiplication/division/conversions from [DeFi][FIN-03][M1] Freeze checked financial arithmetic, rounding and reference model #53 where possible; only separately propose business-neutral compiler/stdlib enhancements after a failing example.
Acceptance checklist
- Reference vectors cover positive/negative tick extremes, both asset directions, both amount modes, zero liquidity, zero/maximum amounts, overflow and one-unit rounding.
- Independent arbitrary-precision reference model, generated builder and actual CKB-VM return identical admitted outputs or declared intentional rejections.
- Unsafe narrowing, out-of-domain prices, wrong signedness or altered rounding reject, with measured cycle/stack/ELF budgets.
- No tick-named compiler opcode or finance-specific parser/codegen branch is introduced.
Explicit boundary: This issue delivers mathematical primitives, not the pool's tick-state store or fee ownership.
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: #53 and #61. Downstream: #64 liquidity positions and #65 executed swaps.
These are planning links, not executed acceptance or formal GitHub blocking relationships. Parent: #43.
Verified dependencies and implementation sequencing
Hard prerequisites: #53 financial arithmetic profile and selected numerical assumptions from #61.
Unblocks: #64 positions, #65 swap steps.
Status: These are explanatory GitHub cross-links and do not set native GitHub blocking relationships, authorise a compiler change, or certify dependent implementation.
Activity