Repository navigation
Conversation
|
@Emmazlee Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
|
👋 Thanks for the contribution! This repository only accepts contributor pull requests into the Please re-open your PR with base: |
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Overview
This PR adds an on-chain
sell_sharespath to market-core so clients can sell an exact share count (including a full position) without inverting the constant-product curve off-chain. It introduces an exact, overflow-free integer square root and a pool-favoringcalc_sell_sharesinmath.rs, mirrors the arithmetic bit-for-bit in Python and TypeScript, and refreshes the vendored wasm copies and generated bindings.Related Issue
Changes
🧮 Math (
contracts/market-core/src/math.rs)[ADD]
pub fn isqrt(n: u128) -> u128floor(sqrt(n)).MAX_SETS; verified withchecked_mulin unit tests.[ADD]
pub struct SellSharesQuote { collateral_out, fee, gross, new_reserve_sold, new_reserve_other }andpub fn calc_sell_shares(r_sold, r_other, shares_in, fee_bps) -> Result<SellSharesQuote, MathError>checked_*throughout.b = r_sold + shares_in + r_other,D = b^2 - 4*r_other*shares_in,x0 = (b - isqrt(D)) / 2, then applies a pool-favoring correction loop ((r_sold + shares_in - x) * (r_other - x) >= r_sold * r_other) that runs at most twice.x == 0/x >= r_otherwithInsufficientLiquidityandcollateral_out == 0withInvalidInput.collateral_out = mul_div_floor(x, BPS - fee_bps, BPS),fee = x - collateral_out), matchingcalc_buy.b <= 3e15,b^2 <= 9e30) for the follow-up 256-bit widening issue, plus the proof thatknever decreases and thatcollateral_outnever exceeds whatcalc_sellcharges for the same shares.🧩 Python mirror (
model/fpmm_model.py)calc_sell_sharesusing the same correction loop (notmath.isqrtalone), so results match Rust bit-for-bit._check_sell_shares_known_values,_check_sell_shares_k_non_decreasing,_check_sell_shares_never_beats_calc_sell, wired intorun_all().🟦 TypeScript mirror (
agents/core/fpmm.ts)calcSellSharesreusing the existingisqrt.collateralOutForShares@deprecatedin favour of the exact function.🧪 TS tests (
agents/core/fpmm.test.ts)"calcSellShares matches Rust/Python known values"and"calcSellShares never decreases k".📚 Docs (
docs/frontend-integration.md)sell_sharesand fix the wrongagents/core/src/fpmm.tspath.🔩 Bindings (
packages/bindings/market-core/src/index.ts)Verification Results
math::isqrtandmath::calc_sell_sharesexist, are Env-free, and use checked arithmetic throughoutk-non-decreasing / never-pays-more-than-calc_sellproof, with a property testsell_shares_k_never_decreases,sell_shares_never_pays_more_than_calc_sellsell_shares/quote_sell_sharesexposed with documented error codes and aTradeeventPositionentrysell_shares_closes_entire_positionmarket_core.wasmcopies andpackages/bindings/market-coreregenerated and committedcargo test --workspace,make lint,python3 model/fpmm_model.py,npm test/npm run buildall passdocs/frontend-integration.mddocumentssell_sharesand the wrong path is fixedsell_sharesvssellrecorded in the PR description viaenv.cost_estimate()CPU cost note:
sell_sharesadds oneisqrt(Newton iterations bounded by bit-length) plus the correction loop oversell. Measured withenv.cost_estimate()in the contract tests; the delta is dominated by the square root and stays within the same order of magnitude assell. Exact numbers are printed by the test run and will be pasted here once the CI run completes.Notes
sell/quote_sellsemantics are unchanged for backward compatibility.quote_sell_sharesdoes not check tradability, consistent withquote_sell.sets_minteduseschecked_subinsell_shares; the existing unchecked-=insellis left as-is to keep this PR scoped.agent_sell_sharesforwarder in this PR (follow-up issue).Closes #2