diff --git a/shield-swap-sdk/AGENTS.md b/shield-swap-sdk/AGENTS.md index 3d43c60e..5bd680cb 100644 --- a/shield-swap-sdk/AGENTS.md +++ b/shield-swap-sdk/AGENTS.md @@ -21,7 +21,7 @@ report = dex.swap_many(pool_key=pools[0].key, token_in_id=pools[0].token0, dex.collect_all() # any session, any time ``` -### `from_profile(home: 'Any' = None, *, network: 'Optional[str]' = None, endpoint: 'Optional[str]' = None) -> "'ShieldSwap'"` +### `from_profile(home=None, *, network=None, endpoint=None)` The client for the local participant profile (created on first use). @@ -41,7 +41,7 @@ Args: to testnet. endpoint: Node API origin for a NEW profile. -### `onboard(self, referral_code: 'Optional[str]' = None) -> 'OnboardReport'` +### `onboard(referral_code=None)` Register this profile end to end — safe to re-run any time. @@ -53,7 +53,7 @@ friend shared to credit them as the referrer (recorded once; later calls ignore it). Requires a profile-bound client (``from_profile()``). -### `status(self) -> 'SessionStatus'` +### `status()` One re-orientation call: identity, access, holdings, pending work. @@ -61,7 +61,7 @@ Run this first in any session — it answers "is this account already registered, what do I hold, what is in flight" from the profile, journal, chain, and API without changing anything. -### `get_positions(self, account: 'Any' = None) -> 'list[PositionView]'` +### `get_positions(account=None)` Every open position — journaled ones plus a record scan. @@ -69,7 +69,7 @@ The scan catches positions the journal never saw (account used from another machine, journal lost); it needs a registered record provider and is skipped silently without one. -### `swap_many(self, *, pool_key: 'str', token_in_id: 'str', amount_in: 'int', count: 'int', slippage_bps: 'int' = 50, expected_out: 'Optional[int]' = None, record_wait_seconds: 'float' = 120.0, account: 'Any' = None) -> 'SwapBatchReport'` +### `swap_many(*, pool_key, token_in_id, amount_in, count, slippage_bps=50, expected_out=None, record_wait_seconds=120.0, account=None)` *count* private swaps of *amount_in* each, with reserved counters. @@ -86,7 +86,7 @@ quotes once and refuses rather than falling back to a spot estimate, which ignores the pool fee and would revert every swap after paying for its proof. -### `collect_all(self, account: 'Any' = None) -> 'CollectReport'` +### `collect_all(account=None)` Claim every finalized swap and collect owed fees on open positions. @@ -212,12 +212,16 @@ them): A swap with nothing left over claims through the no-refund entrypoints automatically; `get_swap_execution` reads the per-hop fill receipt (fees paid, price after) at any later time. -- **Rebalancing is one transaction, testnet only for now** — - `plan_rebalance` quotes the close-and-remint (what comes back, what the - new range needs, funding vs refund per token) and `rebalance_position` - submits it through `shield_swap_rebalance_router.aleo`. Every amount is - asserted at the execution price: a trade in between reverts the whole - transaction (fee paid, no funds moved) — re-plan and resubmit. +- **Rebalancing replaces the complete position in one transaction** — + choose `plan_rebalance_exact_amounts` for exact quotes, + `plan_rebalance_to_liquidity` for exact liquidity with actual recovery, or + `plan_rebalance_from_amounts` for execution-time sizing from token caps. + Review the plan, then pass `plan=` to the matching `rebalance_position_*` + method. Flexible funding/refunds are fixed; surplus stays collectible on + the successor. `estimated_liquidity` is advisory, and token minimums do not + guarantee minimum liquidity. The router is supported on testnet; flexible + calls require an upgraded contract. A rejection rolls back funds movements + but can still cost a fee — refresh state before retrying. - **Concurrency needs partitioned blinded-identity counters AND disjoint input records** — `swap_many` implements the recipe; copy it, don't improvise. @@ -245,7 +249,7 @@ sequence. Current stages: Apps that own their onboarding call the same `dex.api` endpoints the stages use: -### `api.authenticate(self, address: 'str', sign: 'Any') -> 'str'` +### `api.authenticate(address, sign)` Challenge/verify handshake; establishes the session. @@ -263,7 +267,7 @@ returning an Aleo signature literal (``sign1…``) — e.g.:: api.authenticate(str(pk.address), lambda msg: str(pk.sign(msg.encode()))) -### `api.referral_status(self) -> 'models.ReferralStatusResponse'` +### `api.referral_status()` This account's referral picture: ``referred_by`` (the referrer's address once a code was redeemed, else None), ``my_code`` (the code @@ -275,7 +279,7 @@ raises :class:`NotAuthenticatedError` when the session is missing or expired, which makes this the session liveness probe (the dedicated ``/access/status`` route was retired in 2026-09). -### `api.my_referral_code(self) -> 'Optional[str]'` +### `api.my_referral_code()` The referral code this account hands to others. @@ -283,7 +287,7 @@ The API issues the code on the first request, so this normally returns a value; None means issuance is disabled for the account. Network read. -### `api.redeem_code(self, code: 'str') -> 'models.ReferralRedeemResponse'` +### `api.redeem_code(code)` Redeem a referral code (``POST /referral/redeem``) — optional. @@ -297,7 +301,7 @@ Sessions live on the ``/auth/*`` endpoints, so no token comes back (one is still adopted if the API resurrects the legacy body-JWT). -### `api.request_airdrop(self, address: 'str') -> 'models.AirdropStartResult'` +### `api.request_airdrop(address)` Start the test-token airdrop job for *address* (private records). @@ -305,11 +309,11 @@ One claim per address per 15 minutes — raises :class:`AirdropRateLimitedError` on 429. Poll the returned ``job_id`` with :meth:`get_airdrop_job`. -### `api.get_airdrop_job(self, job_id: 'str') -> 'models.AirdropJob'` +### `api.get_airdrop_job(job_id)` Progress of an airdrop job — ``running`` until every transfer lands. -### `api.create_api_token(self, name: 'str', expires_in_days: "'int | None'" = None) -> 'models.ApiTokenCreatedResponse'` +### `api.create_api_token(name, expires_in_days=None)` Mint a long-lived DEX API token (the secret is returned ONCE). @@ -318,7 +322,7 @@ JWTs from :meth:`authenticate` expire in 24h; persist the returned tokens work on data/trading endpoints; ``/access/*`` and token management still require a session JWT. -### `api.get_pools(self) -> 'list[PoolEntry]'` +### `api.get_pools()` Every pool the DEX lists, each with its two tokens' metadata. @@ -328,7 +332,7 @@ An entry exposes the pool's own fields directly — ``entry.key`` is the ``decimals``, but the API does not guarantee them — check for ``None`` before reading. -### `api.get_tokens(self) -> 'list[models.TokenDoc]'` +### `api.get_tokens()` Every token the DEX lists, with its id, symbol, and decimals. @@ -337,27 +341,27 @@ The API returns canonical decimal amounts (``"1.5"``), if using this value to call on-chain methods — ``swap(amount_in=…)``, ``mint``, ``collect`` — conversion to raw base units is necessary. -### `api.get_route(self, *, token_in: 'str', token_out: 'str', amount_in: 'Any' = None, pool_key: 'Optional[str]' = None) -> 'models.RouteResultDoc'` +### `api.get_route(*, token_in, token_out, amount_in=None, pool_key=None)` Best route between two tokens. *amount_in* is a CANONICAL decimal amount (human units, e.g. ``1.5``) — not base units — and the returned ``estimated_amount_out`` is decimal too. *pool_key* pins the quote to one pool instead of the router's best path. -### `api.get_route_topology(self) -> 'models.RouteTopologyDoc'` +### `api.get_route_topology()` The routable token graph: every (token0, token1) edge with an enabled pool and the router's ``max_hops``. Lets a client enumerate reachable pairs without probing ``/route`` per pair. -### `api.get_unclaimed(self) -> 'models.UnclaimedPayloadDoc'` +### `api.get_unclaimed()` Everything the authenticated account can still collect, as the indexer sees it: swaps with finalized-but-unclaimed output and positions with owed balances. A cross-check for a local journal — the chain, not this, gates the claim amounts. -### `api.get_protocol_state(self, *, minimum_revision: 'Optional[int]' = None) -> 'models.ProtocolStateResponse'` +### `api.get_protocol_state(*, minimum_revision=None)` The indexer's view of protocol configuration and its own freshness. @@ -375,7 +379,7 @@ pick them: with a journal they reserve under its lock AND verify each counter on chain; without one they probe the chain. Persist `SwapHandle`s — the blinding factor is the claim secret. -### `blinded_identity_at(aleo: 'Any', account: 'Any', program: 'str', counter: 'int') -> 'BlindedIdentity'` +### `blinded_identity_at(aleo, account, program, counter)` The identity at an exact *counter* — no on-chain probing. @@ -383,7 +387,7 @@ Use with journal-reserved counters for concurrent swaps; :func:`next_blinded_identity` (probe-based) remains the recovery path when no journal exists. -### `next_blinded_identity(aleo: 'Any', account: 'Any', program: 'str' = 'shield_swap.aleo', *, start_counter: 'int' = 0, max_scan: 'int' = 64, gallop: 'bool' = True) -> 'BlindedIdentity'` +### `next_blinded_identity(aleo, account, program='shield_swap.aleo', *, start_counter=0, max_scan=64, gallop=True)` An unused single-use identity for *account*. @@ -401,7 +405,7 @@ exhausting it raises — the fail-fast for a systematically wrong program. ### Chain methods -### `confirm_airdrop(self, *, timeout: 'float' = 600.0, poll_interval: 'float' = 5.0, account: 'Any' = None) -> 'ConfirmAirdropResult'` +### `confirm_airdrop(*, timeout=600.0, poll_interval=5.0, account=None)` Fund the account and wait for its airdrop records to become spendable. @@ -410,7 +414,7 @@ faucet settlement and scanning. Check ``success`` and ``error`` before swapping. A record timeout retains the transfer results; inspect those transactions before requesting another airdrop. Scanner errors propagate. -### `quote(self, *, token_in: 'str', token_out: 'str', amount_in: 'str | Decimal', slippage_bps: 'int' = 50) -> 'SwapQuote'` +### `quote(*, token_in, token_out, amount_in, slippage_bps=50)` Quote a direct or multi-hop swap from two symbols and a token amount. @@ -418,7 +422,7 @@ Returns the API's best route and final slippage floor; pass it to ``swap(quote)``. Requires API authentication. Quoting spends no funds and needs no record scanning or transaction signature. -### `swap(self, quote: 'Optional[SwapQuote]' = None, *, pool_key: 'Optional[str]' = None, token_in_id: 'Optional[str]' = None, amount_in: 'Optional[int | str | Decimal]' = None, slippage_bps: 'Optional[int]' = None, expected_out: 'Optional[int | str | Decimal]' = None, sqrt_price_limit: 'Optional[int]' = None, deadline_offset_blocks: 'int' = 10000, nonce: 'Optional[int]' = None, identity: 'Optional[BlindedIdentity]' = None, token_in_program: 'Optional[str]' = None, token_record: 'Optional[str]' = None, compliance_proofs: 'Optional[SwapProofs]' = None, wrapper_proofs: 'Optional[str]' = None, track: 'bool' = True, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[SwapHandle]'` +### `swap(quote=None, *, pool_key=None, token_in_id=None, amount_in=None, slippage_bps=None, expected_out=None, sqrt_price_limit=None, deadline_offset_blocks=10000, nonce=None, identity=None, token_in_program=None, token_record=None, compliance_proofs=None, wrapper_proofs=None, track=True, imports=None, account=None)` Prepare a direct or multi-hop swap; submit with transact/delegate. @@ -435,7 +439,7 @@ journaling. ``deadline_offset_blocks`` defaults to 10,000 (~8 hours). Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds them, or pass 0–1 bundles (the signer's, for a wrapped input). -### `claim_swap_output(self, handle: 'SwapHandle', *, timeout: 'float' = 0.0, compliance_proofs: 'Optional[ClaimProofs]' = None, wrapper_proofs: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[ClaimResult]'` +### `claim_swap_output(handle, *, timeout=0.0, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` Claim a private swap's output. @@ -454,7 +458,7 @@ After swap confirmation, ``timeout`` sets the maximum wait in seconds Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds them, or pass 1–3 bundles (AMM signer, then each wrapped leg paid). -### `create_pool(self, *, token0_id: 'str', token1_id: 'str', fee: 'int', initial_tick: 'int', tick_spacing: 'Optional[int]' = None, initial_sqrt_price: 'Optional[int]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[TxResult]'` +### `create_pool(*, token0_id, token1_id, fee, initial_tick, tick_spacing=None, initial_sqrt_price=None, imports=None, account=None)` Create a pool — a single public transaction, no records involved. @@ -462,7 +466,7 @@ The fee tier must be registered with the program (validated before submission); tick spacing defaults to the tier's on-chain binding and the opening price to the tick's sqrt price. -### `mint(self, *, pool_key: 'str', tick_lower: 'int', tick_upper: 'int', amount0_desired: 'int', amount1_desired: 'int', amount0_min: 'int' = 0, amount1_min: 'int' = 0, token0_program: 'Optional[str]' = None, token1_program: 'Optional[str]' = None, token0_record: 'Optional[str]' = None, token1_record: 'Optional[str]' = None, tick_lower_hint: 'Optional[int]' = None, tick_upper_hint: 'Optional[int]' = None, recipient: 'Optional[str]' = None, withdrawal: 'Optional[str]' = None, nonce: 'Optional[str]' = None, compliance_proofs: 'Optional[MintProofs]' = None, wrapper_proofs: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[MintResult]'` +### `mint(*, pool_key, tick_lower, tick_upper, amount0_desired, amount1_desired, amount0_min=0, amount1_min=0, token0_program=None, token1_program=None, token0_record=None, token1_record=None, tick_lower_hint=None, tick_upper_hint=None, recipient=None, withdrawal=None, nonce=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` Mint a concentrated-liquidity position as a private PositionNFT. @@ -474,18 +478,18 @@ Wrapped pool sides route via the LP router; fund with UNDERLYING records. Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds them, or pass 3–5 bundles (wrapped senders, then signer, recipient, withdrawal). -### `increase_liquidity(self, *, pool_key: 'str', amount0_desired: 'int', amount1_desired: 'int', amount0_min: 'int' = 0, amount1_min: 'int' = 0, token0_program: 'Optional[str]' = None, token1_program: 'Optional[str]' = None, token0_record: 'Optional[str]' = None, token1_record: 'Optional[str]' = None, position_record: 'Optional[str]' = None, tick_lower_hint: 'Optional[int]' = None, tick_upper_hint: 'Optional[int]' = None, compliance_proofs: 'Optional[IncreaseProofs]' = None, wrapper_proofs: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[TxResult]'` +### `increase_liquidity(*, pool_key, amount0_desired, amount1_desired, amount0_min=0, amount1_min=0, token0_program=None, token1_program=None, token0_record=None, token1_record=None, position_record=None, tick_lower_hint=None, tick_upper_hint=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` Add funds to an existing position (range fixed at mint). Wrapped pool sides route via the LP router; fund with UNDERLYING records. Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds them, or pass 0–2 bundles (the signer's, per wrapped side). -### `decrease_liquidity(self, *, pool_key: 'str', liquidity_to_remove: 'int', amount0_min: 'int' = 0, amount1_min: 'int' = 0, position_record: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[TxResult]'` +### `decrease_liquidity(*, pool_key, liquidity_to_remove, amount0_min=0, amount1_min=0, position_record=None, imports=None, account=None)` Remove liquidity from a position; owed amounts become collectable. -### `collect(self, *, pool_key: 'str', amount0_requested: 'int', amount1_requested: 'int', position_record: 'Optional[str]' = None, compliance_proofs: 'Optional[CollectProofs]' = None, wrapper_proofs: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[TxResult]'` +### `collect(*, pool_key, amount0_requested, amount1_requested, position_record=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` Collect owed token amounts from a position. @@ -495,58 +499,95 @@ route via the LP router, unwrapping to that address in-transaction. Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds them, or pass 2–4 bundles (owner, withdrawal, then a receiver per wrapped side). -### `burn(self, *, pool_key: 'str', position_record: 'Optional[str]' = None, account: 'Any' = None) -> 'DexCall[TxResult]'` +### `burn(*, pool_key, position_record=None, account=None)` Burn an empty position NFT. -### `plan_rebalance(self, *, pool_key: 'str', position_token_id: 'str', tick_lower: 'int', tick_upper: 'int', liquidity_target: 'Optional[int]' = None, max_funding0: 'Optional[int]' = None, max_funding1: 'Optional[int]' = None) -> 'RebalancePlan'` +### `plan_rebalance(*, pool_key, position_token_id, tick_lower, tick_upper, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None)` -Quote a close-and-remint of one position into a new range. Reads only. +Plan a complete position replacement without signing or submitting. -Reads the pool, slot, ``positions`` entry, both current boundary ticks, -and each side's wrapped-ness, then derives what the close returns, what -the successor range needs, and per side the funding to add or surplus -to refund. Size the successor with exactly one of *liquidity_target* -(exact) or *max_funding0*/*max_funding1* (a budget the planner solves -for; ``0, 0`` rebalances on recovered funds alone). +A positive target with omitted bounds preserves exact quoted recovery +and deposits. ``max_funding0/1`` also produce an exact quote sized at +the current price. Explicit ``amount0/1_desired`` cap token consumption; +``amount0/1_min`` default to the caps. Widen either bound to use actual +recovery, or set ``liquidity_target=0`` to size liquidity at execution. +Flexible funding and refunds are fixed amounts, defaulting to zero; +surplus remains collectible on the successor and earns no LP fees. -The plan is only valid at the pool price it was built against — the -contract asserts every amount at finalize — so build it right before -:meth:`rebalance_position` and never cache one. +Amounts are integer token base units, from 0 through 2**128 - 1. +``estimated_liquidity`` is advisory; token floors do not guarantee a +minimum liquidity. Flexible plans must fit the quoted token +bounds and available funds; funding errors name the amount to supply. +Named planners supply mode-specific defaults. Requires an existing pool, position, and initialized boundary ticks. -Raises: - PoolNotFoundError / PoolNotInitializedError: For an unknown pool. - ValueError: If the position or a boundary tick does not exist, the - aligned range is empty, the sizing is ambiguous, or the budget - supports no liquidity. - -### `rebalance_position(self, *, plan: 'Optional[RebalancePlan]' = None, pool_key: 'Optional[str]' = None, position_token_id: 'Optional[str]' = None, tick_lower: 'Optional[int]' = None, tick_upper: 'Optional[int]' = None, liquidity_target: 'Optional[int]' = None, max_funding0: 'Optional[int]' = None, max_funding1: 'Optional[int]' = None, position_record: 'Optional[str]' = None, token0_program: 'Optional[str]' = None, token1_program: 'Optional[str]' = None, token0_record: 'Optional[str]' = None, token1_record: 'Optional[str]' = None, tick_lower_hint: 'Optional[int]' = None, tick_upper_hint: 'Optional[int]' = None, deadline_offset_blocks: 'int' = 20, nonce: 'Optional[str]' = None, compliance_proofs: 'Optional[RebalanceProofs]' = None, wrapper_proofs: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[RebalanceResult]'` - -Close a position and mint its successor range in ONE transaction. - -Burns the old position, settles its principal and every fee it earned, -adds funding from the signer's records where the new range needs more, -mints the successor with the same owner and withdrawal address, and -pays any surplus to the withdrawal address — atomically, through -``shield_swap_rebalance_router.aleo`` (deployed on testnet). Either -pass a *plan* from :meth:`plan_rebalance` (submitted verbatim), or the -pool, range, and one sizing mode and the plan is built here. - -Every amount is asserted against the pool price at execution: a trade -that moves the price between planning and finalize reverts the whole -transaction (fee paid, no funds moved). Rebuild and resubmit when -that happens; the short default deadline fails stale requests cheaply. -Funding records for a wrapped side are the UNDERLYING asset's records. -Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds -them, or pass 2–6 bundles (funded wrapped senders, wrapped receivers, -then owner and withdrawal). +### `rebalance_position(*, plan=None, pool_key=None, position_token_id=None, tick_lower=None, tick_upper=None, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None, position_record=None, token0_program=None, token1_program=None, token0_record=None, token1_record=None, tick_lower_hint=None, tick_upper_hint=None, deadline_offset_blocks=20, nonce=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` -Raises: - ValueError: Without a plan or a complete (pool, range, sizing), or - with the wrong number of compliance proof bundles. - InsufficientRecordsError: If no record covers a funded side. +Prepare an atomic replacement in the same pool, keeping owner and withdrawal. + +Pass a reviewed ``plan`` verbatim, or pool/range/sizing arguments as in +``plan_rebalance``. Pool/position arguments must match the plan, and +supplied ticks must align to its range. Sizing/amount arguments +are rejected. Exact bounds enforce the quote; wider bounds use actual +recovery and a zero target sizes liquidity at execution. Funding and +immediate refunds stay fixed; flexible surplus remains collectible on +the successor. Wrapped funding uses the underlying asset's records. + +Preparation reads chain state and resolves records and proofs. Submit +with ``delegate()`` or ``transact()``. A rejection rolls back all funds +movements but can still cost a fee; refresh state before retrying. +The default deadline is 20 blocks. Flexible calls require a deployment +supporting execution-time recovery and amount-driven rebalancing. +Freeze-list proofs are built automatically unless supplied explicitly. + +### `plan_rebalance_exact_amounts(*, pool_key, position_token_id, tick_lower, tick_upper, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None)` + +Quote a complete replacement with fixed recovery and deposits. + +Supply a positive target or paired ``max_funding0/1`` budgets. Minimums +must equal caps. Price or fee changes can reject execution. Reads only. + +### `rebalance_position_exact_amounts(*, plan=None, pool_key=None, position_token_id=None, tick_lower=None, tick_upper=None, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None, position_record=None, token0_program=None, token1_program=None, token0_record=None, token1_record=None, tick_lower_hint=None, tick_upper_hint=None, deadline_offset_blocks=20, nonce=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` + +Prepare an exact quote using target-or-budget sizing, or a reviewed plan. + +Uses ``plan_rebalance_exact_amounts`` constraints. Price or fee changes +can reject execution. Submit with ``delegate()`` or ``transact()``. + +### `plan_rebalance_to_liquidity(*, pool_key, position_token_id, tick_lower, tick_upper, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None)` + +Quote fixed successor liquidity with actual recovered funds. + +Supply a positive target and both caps; one bound must be flexible. +Minimums and fixed funding/refunds default to zero. Rejects quotes +outside the bounds or available funds. Later price changes can still +reject execution. Reads only. + +### `rebalance_position_to_liquidity(*, plan=None, pool_key=None, position_token_id=None, tick_lower=None, tick_upper=None, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None, position_record=None, token0_program=None, token1_program=None, token0_record=None, token1_record=None, tick_lower_hint=None, tick_upper_hint=None, deadline_offset_blocks=20, nonce=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` + +Prepare fixed successor liquidity with bounded token consumption. + +Uses ``plan_rebalance_to_liquidity`` constraints, or a reviewed plan. +Insufficient execution-time funds reject rather than minting less. +Submit with ``delegate()`` or ``transact()``. + +### `plan_rebalance_from_amounts(*, pool_key, position_token_id, tick_lower, tick_upper, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None)` + +Estimate replacement liquidity from both token caps. + +Omit the target or set zero. Minimums and fixed funding/refunds default +to zero. Estimates and token minimums do not guarantee liquidity. +Surplus stays collectible; no swap occurs. Reads only; integer base units. + +### `rebalance_position_from_amounts(*, plan=None, pool_key=None, position_token_id=None, tick_lower=None, tick_upper=None, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None, position_record=None, token0_program=None, token1_program=None, token0_record=None, token1_record=None, tick_lower_hint=None, tick_upper_hint=None, deadline_offset_blocks=20, nonce=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` + +Prepare a replacement sized from available tokens at execution. + +Uses ``plan_rebalance_from_amounts`` constraints, or a reviewed plan. +Estimated liquidity is advisory; surplus stays collectible. +Submit with ``delegate()`` or ``transact()``. -### `plan_inventory(self, token: 'str', target: 'InventoryTarget', *, max_transactions: 'Optional[int]' = None, account: 'Any' = None) -> 'InventoryPlan'` +### `plan_inventory(token, target, *, max_transactions=None, account=None)` Plan the joins and splits that give *token* the record layout trades need. @@ -571,7 +612,7 @@ Example:: plan = dex.plan_inventory("USDCx", InventoryTarget(records=6, min_record_amount=100_000, distribution="balanced")) -### `rebalance_inventory(self, token: 'str', target: 'InventoryTarget', *, max_transactions: 'Optional[int]' = None, timeout: 'float' = 120.0, poll_interval: 'float' = 1.0, max_fee_microcredits: 'Optional[int]' = None, cancel: 'Any' = None, account: 'Any' = None) -> 'InventoryResult'` +### `rebalance_inventory(token, target, *, max_transactions=None, timeout=120.0, poll_interval=1.0, max_fee_microcredits=None, cancel=None, account=None)` Reshape *token*'s underlying records to *target*, one confirmed transaction at a time. @@ -588,18 +629,18 @@ Example:: if result.status == "interrupted": dex.inventory.reconcile_record_inventory() -### `get_pool(self, pool_key: 'str') -> 'g.PoolState'` +### `get_pool(pool_key)` Static pool configuration (token pair, fee, decimal scales). -### `get_slot(self, pool_key: 'str') -> 'SlotView'` +### `get_slot(pool_key)` Live trading state (sqrt price, tick, in-range liquidity). Raises :class:`PoolNotFoundError` when the pool does not exist, or :class:`PoolNotInitializedError` when it exists but has no slot yet. -### `get_swap_output(self, swap: "'SwapHandle | str'") -> 'g.SwapOutput'` +### `get_swap_output(swap)` Chain-computed output of a finalized swap request. @@ -607,7 +648,7 @@ Accepts the :class:`SwapHandle` from ``swap()`` or a bare swap id. Raises :class:`SwapOutputNotFinalizedError` when the entry is absent — not finalized yet (retry after a few blocks) or already claimed. -### `get_swap_execution(self, swap: "'SwapHandle | str'") -> 'Optional[SwapExecution]'` +### `get_swap_execution(swap)` Per-hop fill receipt of an executed swap — what each pool leg paid. @@ -621,7 +662,7 @@ Raises: ValueError: If the header names a hop the node did not return — a node lagging its own finalize; retry. -### `get_balances(self, address: 'Optional[str]' = None, account: 'Any' = None, *, include_private: 'bool' = True) -> 'dict[str, dict[str, Any]]'` +### `get_balances(address=None, account=None, *, include_private=True)` Public + private + total per token id, joined via the API's token registry. Defaults to the bound account's address; returns @@ -633,7 +674,7 @@ token (their records are not scannable) rather than silently mixing in the caller's own private holdings. ``include_private=False`` skips the record scan (public only — before scanner credentials). -### `get_public_balances(self, programs: 'list[str]', address: 'Optional[str]' = None) -> 'dict[str, int]'` +### `get_public_balances(programs, address=None)` Public balances per token program from each program's on-chain ``balances`` mapping (plain-address key; one read per program, any @@ -644,12 +685,12 @@ network lacks, or a non-ARC-20 value, is skipped with a warning rather than failing every other token. *address* defaults to the bound account's (ValueError when there is none). -### `get_private_balances(self, programs: 'list[str]', account: 'Any' = None) -> 'dict[str, int]'` +### `get_private_balances(programs, account=None)` Sum of unspent record amounts per wrapper program (spendable privately). Requires a configured record provider. -### `derive_pool_key(self, token0: 'str', token1: 'str', fee: 'int') -> 'str'` +### `derive_pool_key(token0, token1, fee)` Compute the pool key for a token pair and fee tier. Local — no network. @@ -660,7 +701,7 @@ derivation is sensitive to token order and is network-scoped, so swapping a valid-looking ``field`` that matches nothing on chain. *fee* is the contract's ``u16`` fee tier. -### `derive_tick_key(self, pool_key: 'str', tick: 'int') -> 'str'` +### `derive_tick_key(pool_key, tick)` Compute the key of one tick within a pool. Local — no network. diff --git a/shield-swap-sdk/README.md b/shield-swap-sdk/README.md index 57ab64f7..de7b3823 100644 --- a/shield-swap-sdk/README.md +++ b/shield-swap-sdk/README.md @@ -124,7 +124,79 @@ from the chain or the service. | `increase_liquidity(...)` / `decrease_liquidity(...)` | Resizes a position (spends the position NFT record and returns a fresh one). | | `collect(...)` | Pays out `tokens_owed` as private records. | | `burn(...)` | Closes an emptied position and removes it from the `positions` mapping. | -| `plan_rebalance(...)` / `rebalance_position(...)` | Close a position and mint its successor range in ONE transaction via `shield_swap_rebalance_router.aleo` (testnet). The plan quotes what comes back, what the new range needs, and funding vs refund per token; every amount is asserted at the execution price, so re-plan and resubmit if the pool moved. | +| `plan_rebalance(...)` / `rebalance_position(...)` | Plan or prepare a complete position replacement in one transaction. Choose exact quotes, exact liquidity with flexible recovery, or execution-time sizing from token budgets; see below. | + +### Move a position to another range + +A rebalance closes the complete old position and creates a replacement in the +same pool, preserving its owner and withdrawal address. Principal and all owed +and accrued fees become available for the replacement. Optional funding adds +private tokens; no swap occurs. Choose a mode according to what must remain +fixed between planning and execution: + +| Planner / matching execution method | Guarantee and required inputs | +|---|---| +| `plan_rebalance_exact_amounts` / `rebalance_position_exact_amounts` | Exact quoted recovery and deposits. Supply a positive `liquidity_target`, or paired `max_funding0/1` budgets that the planner converts to an exact quote. Price or fee changes can reject execution. | +| `plan_rebalance_to_liquidity` / `rebalance_position_to_liquidity` | Exact successor liquidity using actual recovery. Supply a positive target and both `amount0/1_desired` caps. Minimums default to zero; at least one token bound must remain flexible. Insufficient funds reject rather than minting less liquidity. | +| `plan_rebalance_from_amounts` / `rebalance_position_from_amounts` | Liquidity determined from available tokens at execution. Supply both desired caps; minimums default to zero and the target is zero. `estimated_liquidity` is a preview, not a guaranteed amount. | + +Token caps, minimums, fixed `funded0/1`, and fixed `refund0/1` use integer base +units from 0 through `2**128 - 1`. Funding and immediate refunds default to zero +in flexible modes and cannot both be positive for the same token. Unused funds +stay collectible as `tokens_owed` on the successor; they earn no liquidity fees +until reinvested. Token minimums constrain consumption, not minimum liquidity. + +For flexible plans, planning rejects a quoted deposit outside its +token bounds or above the available recovery plus funding minus refunds. A +funding error reports the fixed amount to supply. Passing these checks does not +guarantee execution: prices and recovery can change before the transaction lands. + +The generic `plan_rebalance` and `rebalance_position` preserve existing exact +calls. With explicit caps, omitted minimums equal those caps. Widening either +bound enables actual recovery; setting `liquidity_target=0` enables execution-time +sizing even when both bounds are equal. `max_funding0/1` remain quote-time sizing +budgets and cannot be combined with explicit caps or fixed transfers. + +Continue with the configured `dex` client from the setup above. This example +uses illustrative token caps; choose caps in each token's own base units and +review the plan before submitting: + +```python +positions = dex.get_owned_positions() +if not positions: + raise ValueError("An owned position is required before rebalancing") +position = positions[0] +plan = dex.plan_rebalance_from_amounts( + pool_key=position.pool_key, + position_token_id=position.position_token_id, + tick_lower=position.tick_lower - 60, + tick_upper=position.tick_upper + 60, + amount0_desired=100_000, + amount1_desired=100_000, +) +print(plan) # Includes fixed transfers, token bounds, and estimated liquidity. +# After reviewing the plan: +result = dex.rebalance_position_from_amounts(plan=plan).delegate() +print(result.transaction_id, result.position_token_id) +``` + +Passing `plan=` preserves its constraints and estimates. Matching pool, position, +and range arguments (after tick alignment) are accepted; conflicting values or +sizing/amount arguments are rejected. Build a new plan to change constraints. Integer-like amount inputs +are normalized to Python integers; booleans and fractional values are rejected. +Preparation reads the network and resolves records/proofs; only `delegate()` or +`transact()` submits. A rejected rebalance leaves the old position unchanged but +can still cost a fee. Refresh state before retrying a confirmed rejection. + +`AsyncShieldSwap` exposes all four planners; liquidity execution remains on +`ShieldSwap`. The same named planner and execution helpers are available through +`aleo_shield_swap.agent` and the MCP server. Agent/MCP amounts are decimal strings +to preserve u128 precision; those execution tools rebuild the plan from the +provided constraints immediately before submission. + +The rebalance router is supported on testnet. Flexible calls require a contract +deployment with execution-time recovery and amount-driven rebalancing support; +SDK availability alone does not establish deployment compatibility. A swap whose input was fully consumed (`amount_remaining == 0`) claims through the no-refund entrypoints (`claim_swap_output_no_refund` and the diff --git a/shield-swap-sdk/codegen/gen_context.py b/shield-swap-sdk/codegen/gen_context.py index 9c684b1b..d29c9e02 100644 --- a/shield-swap-sdk/codegen/gen_context.py +++ b/shield-swap-sdk/codegen/gen_context.py @@ -30,6 +30,9 @@ TIER2_CLIENT = ["confirm_airdrop", "quote", "swap", "claim_swap_output", "create_pool", "mint", "increase_liquidity", "decrease_liquidity", "collect", "burn", "plan_rebalance", "rebalance_position", + "plan_rebalance_exact_amounts", "rebalance_position_exact_amounts", + "plan_rebalance_to_liquidity", "rebalance_position_to_liquidity", + "plan_rebalance_from_amounts", "rebalance_position_from_amounts", "plan_inventory", "rebalance_inventory", "get_pool", "get_slot", "get_swap_output", "get_swap_execution", "get_balances", "get_public_balances", @@ -171,12 +174,16 @@ A swap with nothing left over claims through the no-refund entrypoints automatically; `get_swap_execution` reads the per-hop fill receipt (fees paid, price after) at any later time. -- **Rebalancing is one transaction, testnet only for now** — - `plan_rebalance` quotes the close-and-remint (what comes back, what the - new range needs, funding vs refund per token) and `rebalance_position` - submits it through `shield_swap_rebalance_router.aleo`. Every amount is - asserted at the execution price: a trade in between reverts the whole - transaction (fee paid, no funds moved) — re-plan and resubmit. +- **Rebalancing replaces the complete position in one transaction** — + choose `plan_rebalance_exact_amounts` for exact quotes, + `plan_rebalance_to_liquidity` for exact liquidity with actual recovery, or + `plan_rebalance_from_amounts` for execution-time sizing from token caps. + Review the plan, then pass `plan=` to the matching `rebalance_position_*` + method. Flexible funding/refunds are fixed; surplus stays collectible on + the successor. `estimated_liquidity` is advisory, and token minimums do not + guarantee minimum liquidity. The router is supported on testnet; flexible + calls require an upgraded contract. A rejection rolls back funds movements + but can still cost a fee — refresh state before retrying. - **Concurrency needs partitioned blinded-identity counters AND disjoint input records** — `swap_many` implements the recipe; copy it, don't improvise. @@ -187,7 +194,13 @@ def _entry(name: str, fn: object) -> str: try: - sig = str(inspect.signature(fn)) # type: ignore[arg-type] + signature = inspect.signature(fn) # type: ignore[arg-type] + # Keep every argument and default visible without repeating Python's + # type annotations throughout the compact agent reference. + sig = str(signature.replace(parameters=[ + param.replace(annotation=inspect.Parameter.empty) + for param in signature.parameters.values() if param.name not in ("self", "cls") + ], return_annotation=inspect.Signature.empty)) except (TypeError, ValueError): sig = "(...)" doc = inspect.getdoc(fn) or "" diff --git a/shield-swap-sdk/python/aleo_shield_swap/AGENTS.md b/shield-swap-sdk/python/aleo_shield_swap/AGENTS.md index 3d43c60e..5bd680cb 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/AGENTS.md +++ b/shield-swap-sdk/python/aleo_shield_swap/AGENTS.md @@ -21,7 +21,7 @@ report = dex.swap_many(pool_key=pools[0].key, token_in_id=pools[0].token0, dex.collect_all() # any session, any time ``` -### `from_profile(home: 'Any' = None, *, network: 'Optional[str]' = None, endpoint: 'Optional[str]' = None) -> "'ShieldSwap'"` +### `from_profile(home=None, *, network=None, endpoint=None)` The client for the local participant profile (created on first use). @@ -41,7 +41,7 @@ Args: to testnet. endpoint: Node API origin for a NEW profile. -### `onboard(self, referral_code: 'Optional[str]' = None) -> 'OnboardReport'` +### `onboard(referral_code=None)` Register this profile end to end — safe to re-run any time. @@ -53,7 +53,7 @@ friend shared to credit them as the referrer (recorded once; later calls ignore it). Requires a profile-bound client (``from_profile()``). -### `status(self) -> 'SessionStatus'` +### `status()` One re-orientation call: identity, access, holdings, pending work. @@ -61,7 +61,7 @@ Run this first in any session — it answers "is this account already registered, what do I hold, what is in flight" from the profile, journal, chain, and API without changing anything. -### `get_positions(self, account: 'Any' = None) -> 'list[PositionView]'` +### `get_positions(account=None)` Every open position — journaled ones plus a record scan. @@ -69,7 +69,7 @@ The scan catches positions the journal never saw (account used from another machine, journal lost); it needs a registered record provider and is skipped silently without one. -### `swap_many(self, *, pool_key: 'str', token_in_id: 'str', amount_in: 'int', count: 'int', slippage_bps: 'int' = 50, expected_out: 'Optional[int]' = None, record_wait_seconds: 'float' = 120.0, account: 'Any' = None) -> 'SwapBatchReport'` +### `swap_many(*, pool_key, token_in_id, amount_in, count, slippage_bps=50, expected_out=None, record_wait_seconds=120.0, account=None)` *count* private swaps of *amount_in* each, with reserved counters. @@ -86,7 +86,7 @@ quotes once and refuses rather than falling back to a spot estimate, which ignores the pool fee and would revert every swap after paying for its proof. -### `collect_all(self, account: 'Any' = None) -> 'CollectReport'` +### `collect_all(account=None)` Claim every finalized swap and collect owed fees on open positions. @@ -212,12 +212,16 @@ them): A swap with nothing left over claims through the no-refund entrypoints automatically; `get_swap_execution` reads the per-hop fill receipt (fees paid, price after) at any later time. -- **Rebalancing is one transaction, testnet only for now** — - `plan_rebalance` quotes the close-and-remint (what comes back, what the - new range needs, funding vs refund per token) and `rebalance_position` - submits it through `shield_swap_rebalance_router.aleo`. Every amount is - asserted at the execution price: a trade in between reverts the whole - transaction (fee paid, no funds moved) — re-plan and resubmit. +- **Rebalancing replaces the complete position in one transaction** — + choose `plan_rebalance_exact_amounts` for exact quotes, + `plan_rebalance_to_liquidity` for exact liquidity with actual recovery, or + `plan_rebalance_from_amounts` for execution-time sizing from token caps. + Review the plan, then pass `plan=` to the matching `rebalance_position_*` + method. Flexible funding/refunds are fixed; surplus stays collectible on + the successor. `estimated_liquidity` is advisory, and token minimums do not + guarantee minimum liquidity. The router is supported on testnet; flexible + calls require an upgraded contract. A rejection rolls back funds movements + but can still cost a fee — refresh state before retrying. - **Concurrency needs partitioned blinded-identity counters AND disjoint input records** — `swap_many` implements the recipe; copy it, don't improvise. @@ -245,7 +249,7 @@ sequence. Current stages: Apps that own their onboarding call the same `dex.api` endpoints the stages use: -### `api.authenticate(self, address: 'str', sign: 'Any') -> 'str'` +### `api.authenticate(address, sign)` Challenge/verify handshake; establishes the session. @@ -263,7 +267,7 @@ returning an Aleo signature literal (``sign1…``) — e.g.:: api.authenticate(str(pk.address), lambda msg: str(pk.sign(msg.encode()))) -### `api.referral_status(self) -> 'models.ReferralStatusResponse'` +### `api.referral_status()` This account's referral picture: ``referred_by`` (the referrer's address once a code was redeemed, else None), ``my_code`` (the code @@ -275,7 +279,7 @@ raises :class:`NotAuthenticatedError` when the session is missing or expired, which makes this the session liveness probe (the dedicated ``/access/status`` route was retired in 2026-09). -### `api.my_referral_code(self) -> 'Optional[str]'` +### `api.my_referral_code()` The referral code this account hands to others. @@ -283,7 +287,7 @@ The API issues the code on the first request, so this normally returns a value; None means issuance is disabled for the account. Network read. -### `api.redeem_code(self, code: 'str') -> 'models.ReferralRedeemResponse'` +### `api.redeem_code(code)` Redeem a referral code (``POST /referral/redeem``) — optional. @@ -297,7 +301,7 @@ Sessions live on the ``/auth/*`` endpoints, so no token comes back (one is still adopted if the API resurrects the legacy body-JWT). -### `api.request_airdrop(self, address: 'str') -> 'models.AirdropStartResult'` +### `api.request_airdrop(address)` Start the test-token airdrop job for *address* (private records). @@ -305,11 +309,11 @@ One claim per address per 15 minutes — raises :class:`AirdropRateLimitedError` on 429. Poll the returned ``job_id`` with :meth:`get_airdrop_job`. -### `api.get_airdrop_job(self, job_id: 'str') -> 'models.AirdropJob'` +### `api.get_airdrop_job(job_id)` Progress of an airdrop job — ``running`` until every transfer lands. -### `api.create_api_token(self, name: 'str', expires_in_days: "'int | None'" = None) -> 'models.ApiTokenCreatedResponse'` +### `api.create_api_token(name, expires_in_days=None)` Mint a long-lived DEX API token (the secret is returned ONCE). @@ -318,7 +322,7 @@ JWTs from :meth:`authenticate` expire in 24h; persist the returned tokens work on data/trading endpoints; ``/access/*`` and token management still require a session JWT. -### `api.get_pools(self) -> 'list[PoolEntry]'` +### `api.get_pools()` Every pool the DEX lists, each with its two tokens' metadata. @@ -328,7 +332,7 @@ An entry exposes the pool's own fields directly — ``entry.key`` is the ``decimals``, but the API does not guarantee them — check for ``None`` before reading. -### `api.get_tokens(self) -> 'list[models.TokenDoc]'` +### `api.get_tokens()` Every token the DEX lists, with its id, symbol, and decimals. @@ -337,27 +341,27 @@ The API returns canonical decimal amounts (``"1.5"``), if using this value to call on-chain methods — ``swap(amount_in=…)``, ``mint``, ``collect`` — conversion to raw base units is necessary. -### `api.get_route(self, *, token_in: 'str', token_out: 'str', amount_in: 'Any' = None, pool_key: 'Optional[str]' = None) -> 'models.RouteResultDoc'` +### `api.get_route(*, token_in, token_out, amount_in=None, pool_key=None)` Best route between two tokens. *amount_in* is a CANONICAL decimal amount (human units, e.g. ``1.5``) — not base units — and the returned ``estimated_amount_out`` is decimal too. *pool_key* pins the quote to one pool instead of the router's best path. -### `api.get_route_topology(self) -> 'models.RouteTopologyDoc'` +### `api.get_route_topology()` The routable token graph: every (token0, token1) edge with an enabled pool and the router's ``max_hops``. Lets a client enumerate reachable pairs without probing ``/route`` per pair. -### `api.get_unclaimed(self) -> 'models.UnclaimedPayloadDoc'` +### `api.get_unclaimed()` Everything the authenticated account can still collect, as the indexer sees it: swaps with finalized-but-unclaimed output and positions with owed balances. A cross-check for a local journal — the chain, not this, gates the claim amounts. -### `api.get_protocol_state(self, *, minimum_revision: 'Optional[int]' = None) -> 'models.ProtocolStateResponse'` +### `api.get_protocol_state(*, minimum_revision=None)` The indexer's view of protocol configuration and its own freshness. @@ -375,7 +379,7 @@ pick them: with a journal they reserve under its lock AND verify each counter on chain; without one they probe the chain. Persist `SwapHandle`s — the blinding factor is the claim secret. -### `blinded_identity_at(aleo: 'Any', account: 'Any', program: 'str', counter: 'int') -> 'BlindedIdentity'` +### `blinded_identity_at(aleo, account, program, counter)` The identity at an exact *counter* — no on-chain probing. @@ -383,7 +387,7 @@ Use with journal-reserved counters for concurrent swaps; :func:`next_blinded_identity` (probe-based) remains the recovery path when no journal exists. -### `next_blinded_identity(aleo: 'Any', account: 'Any', program: 'str' = 'shield_swap.aleo', *, start_counter: 'int' = 0, max_scan: 'int' = 64, gallop: 'bool' = True) -> 'BlindedIdentity'` +### `next_blinded_identity(aleo, account, program='shield_swap.aleo', *, start_counter=0, max_scan=64, gallop=True)` An unused single-use identity for *account*. @@ -401,7 +405,7 @@ exhausting it raises — the fail-fast for a systematically wrong program. ### Chain methods -### `confirm_airdrop(self, *, timeout: 'float' = 600.0, poll_interval: 'float' = 5.0, account: 'Any' = None) -> 'ConfirmAirdropResult'` +### `confirm_airdrop(*, timeout=600.0, poll_interval=5.0, account=None)` Fund the account and wait for its airdrop records to become spendable. @@ -410,7 +414,7 @@ faucet settlement and scanning. Check ``success`` and ``error`` before swapping. A record timeout retains the transfer results; inspect those transactions before requesting another airdrop. Scanner errors propagate. -### `quote(self, *, token_in: 'str', token_out: 'str', amount_in: 'str | Decimal', slippage_bps: 'int' = 50) -> 'SwapQuote'` +### `quote(*, token_in, token_out, amount_in, slippage_bps=50)` Quote a direct or multi-hop swap from two symbols and a token amount. @@ -418,7 +422,7 @@ Returns the API's best route and final slippage floor; pass it to ``swap(quote)``. Requires API authentication. Quoting spends no funds and needs no record scanning or transaction signature. -### `swap(self, quote: 'Optional[SwapQuote]' = None, *, pool_key: 'Optional[str]' = None, token_in_id: 'Optional[str]' = None, amount_in: 'Optional[int | str | Decimal]' = None, slippage_bps: 'Optional[int]' = None, expected_out: 'Optional[int | str | Decimal]' = None, sqrt_price_limit: 'Optional[int]' = None, deadline_offset_blocks: 'int' = 10000, nonce: 'Optional[int]' = None, identity: 'Optional[BlindedIdentity]' = None, token_in_program: 'Optional[str]' = None, token_record: 'Optional[str]' = None, compliance_proofs: 'Optional[SwapProofs]' = None, wrapper_proofs: 'Optional[str]' = None, track: 'bool' = True, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[SwapHandle]'` +### `swap(quote=None, *, pool_key=None, token_in_id=None, amount_in=None, slippage_bps=None, expected_out=None, sqrt_price_limit=None, deadline_offset_blocks=10000, nonce=None, identity=None, token_in_program=None, token_record=None, compliance_proofs=None, wrapper_proofs=None, track=True, imports=None, account=None)` Prepare a direct or multi-hop swap; submit with transact/delegate. @@ -435,7 +439,7 @@ journaling. ``deadline_offset_blocks`` defaults to 10,000 (~8 hours). Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds them, or pass 0–1 bundles (the signer's, for a wrapped input). -### `claim_swap_output(self, handle: 'SwapHandle', *, timeout: 'float' = 0.0, compliance_proofs: 'Optional[ClaimProofs]' = None, wrapper_proofs: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[ClaimResult]'` +### `claim_swap_output(handle, *, timeout=0.0, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` Claim a private swap's output. @@ -454,7 +458,7 @@ After swap confirmation, ``timeout`` sets the maximum wait in seconds Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds them, or pass 1–3 bundles (AMM signer, then each wrapped leg paid). -### `create_pool(self, *, token0_id: 'str', token1_id: 'str', fee: 'int', initial_tick: 'int', tick_spacing: 'Optional[int]' = None, initial_sqrt_price: 'Optional[int]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[TxResult]'` +### `create_pool(*, token0_id, token1_id, fee, initial_tick, tick_spacing=None, initial_sqrt_price=None, imports=None, account=None)` Create a pool — a single public transaction, no records involved. @@ -462,7 +466,7 @@ The fee tier must be registered with the program (validated before submission); tick spacing defaults to the tier's on-chain binding and the opening price to the tick's sqrt price. -### `mint(self, *, pool_key: 'str', tick_lower: 'int', tick_upper: 'int', amount0_desired: 'int', amount1_desired: 'int', amount0_min: 'int' = 0, amount1_min: 'int' = 0, token0_program: 'Optional[str]' = None, token1_program: 'Optional[str]' = None, token0_record: 'Optional[str]' = None, token1_record: 'Optional[str]' = None, tick_lower_hint: 'Optional[int]' = None, tick_upper_hint: 'Optional[int]' = None, recipient: 'Optional[str]' = None, withdrawal: 'Optional[str]' = None, nonce: 'Optional[str]' = None, compliance_proofs: 'Optional[MintProofs]' = None, wrapper_proofs: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[MintResult]'` +### `mint(*, pool_key, tick_lower, tick_upper, amount0_desired, amount1_desired, amount0_min=0, amount1_min=0, token0_program=None, token1_program=None, token0_record=None, token1_record=None, tick_lower_hint=None, tick_upper_hint=None, recipient=None, withdrawal=None, nonce=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` Mint a concentrated-liquidity position as a private PositionNFT. @@ -474,18 +478,18 @@ Wrapped pool sides route via the LP router; fund with UNDERLYING records. Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds them, or pass 3–5 bundles (wrapped senders, then signer, recipient, withdrawal). -### `increase_liquidity(self, *, pool_key: 'str', amount0_desired: 'int', amount1_desired: 'int', amount0_min: 'int' = 0, amount1_min: 'int' = 0, token0_program: 'Optional[str]' = None, token1_program: 'Optional[str]' = None, token0_record: 'Optional[str]' = None, token1_record: 'Optional[str]' = None, position_record: 'Optional[str]' = None, tick_lower_hint: 'Optional[int]' = None, tick_upper_hint: 'Optional[int]' = None, compliance_proofs: 'Optional[IncreaseProofs]' = None, wrapper_proofs: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[TxResult]'` +### `increase_liquidity(*, pool_key, amount0_desired, amount1_desired, amount0_min=0, amount1_min=0, token0_program=None, token1_program=None, token0_record=None, token1_record=None, position_record=None, tick_lower_hint=None, tick_upper_hint=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` Add funds to an existing position (range fixed at mint). Wrapped pool sides route via the LP router; fund with UNDERLYING records. Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds them, or pass 0–2 bundles (the signer's, per wrapped side). -### `decrease_liquidity(self, *, pool_key: 'str', liquidity_to_remove: 'int', amount0_min: 'int' = 0, amount1_min: 'int' = 0, position_record: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[TxResult]'` +### `decrease_liquidity(*, pool_key, liquidity_to_remove, amount0_min=0, amount1_min=0, position_record=None, imports=None, account=None)` Remove liquidity from a position; owed amounts become collectable. -### `collect(self, *, pool_key: 'str', amount0_requested: 'int', amount1_requested: 'int', position_record: 'Optional[str]' = None, compliance_proofs: 'Optional[CollectProofs]' = None, wrapper_proofs: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[TxResult]'` +### `collect(*, pool_key, amount0_requested, amount1_requested, position_record=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` Collect owed token amounts from a position. @@ -495,58 +499,95 @@ route via the LP router, unwrapping to that address in-transaction. Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds them, or pass 2–4 bundles (owner, withdrawal, then a receiver per wrapped side). -### `burn(self, *, pool_key: 'str', position_record: 'Optional[str]' = None, account: 'Any' = None) -> 'DexCall[TxResult]'` +### `burn(*, pool_key, position_record=None, account=None)` Burn an empty position NFT. -### `plan_rebalance(self, *, pool_key: 'str', position_token_id: 'str', tick_lower: 'int', tick_upper: 'int', liquidity_target: 'Optional[int]' = None, max_funding0: 'Optional[int]' = None, max_funding1: 'Optional[int]' = None) -> 'RebalancePlan'` +### `plan_rebalance(*, pool_key, position_token_id, tick_lower, tick_upper, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None)` -Quote a close-and-remint of one position into a new range. Reads only. +Plan a complete position replacement without signing or submitting. -Reads the pool, slot, ``positions`` entry, both current boundary ticks, -and each side's wrapped-ness, then derives what the close returns, what -the successor range needs, and per side the funding to add or surplus -to refund. Size the successor with exactly one of *liquidity_target* -(exact) or *max_funding0*/*max_funding1* (a budget the planner solves -for; ``0, 0`` rebalances on recovered funds alone). +A positive target with omitted bounds preserves exact quoted recovery +and deposits. ``max_funding0/1`` also produce an exact quote sized at +the current price. Explicit ``amount0/1_desired`` cap token consumption; +``amount0/1_min`` default to the caps. Widen either bound to use actual +recovery, or set ``liquidity_target=0`` to size liquidity at execution. +Flexible funding and refunds are fixed amounts, defaulting to zero; +surplus remains collectible on the successor and earns no LP fees. -The plan is only valid at the pool price it was built against — the -contract asserts every amount at finalize — so build it right before -:meth:`rebalance_position` and never cache one. +Amounts are integer token base units, from 0 through 2**128 - 1. +``estimated_liquidity`` is advisory; token floors do not guarantee a +minimum liquidity. Flexible plans must fit the quoted token +bounds and available funds; funding errors name the amount to supply. +Named planners supply mode-specific defaults. Requires an existing pool, position, and initialized boundary ticks. -Raises: - PoolNotFoundError / PoolNotInitializedError: For an unknown pool. - ValueError: If the position or a boundary tick does not exist, the - aligned range is empty, the sizing is ambiguous, or the budget - supports no liquidity. - -### `rebalance_position(self, *, plan: 'Optional[RebalancePlan]' = None, pool_key: 'Optional[str]' = None, position_token_id: 'Optional[str]' = None, tick_lower: 'Optional[int]' = None, tick_upper: 'Optional[int]' = None, liquidity_target: 'Optional[int]' = None, max_funding0: 'Optional[int]' = None, max_funding1: 'Optional[int]' = None, position_record: 'Optional[str]' = None, token0_program: 'Optional[str]' = None, token1_program: 'Optional[str]' = None, token0_record: 'Optional[str]' = None, token1_record: 'Optional[str]' = None, tick_lower_hint: 'Optional[int]' = None, tick_upper_hint: 'Optional[int]' = None, deadline_offset_blocks: 'int' = 20, nonce: 'Optional[str]' = None, compliance_proofs: 'Optional[RebalanceProofs]' = None, wrapper_proofs: 'Optional[str]' = None, imports: 'Optional[dict[str, str]]' = None, account: 'Any' = None) -> 'DexCall[RebalanceResult]'` - -Close a position and mint its successor range in ONE transaction. - -Burns the old position, settles its principal and every fee it earned, -adds funding from the signer's records where the new range needs more, -mints the successor with the same owner and withdrawal address, and -pays any surplus to the withdrawal address — atomically, through -``shield_swap_rebalance_router.aleo`` (deployed on testnet). Either -pass a *plan* from :meth:`plan_rebalance` (submitted verbatim), or the -pool, range, and one sizing mode and the plan is built here. - -Every amount is asserted against the pool price at execution: a trade -that moves the price between planning and finalize reverts the whole -transaction (fee paid, no funds moved). Rebuild and resubmit when -that happens; the short default deadline fails stale requests cheaply. -Funding records for a wrapped side are the UNDERLYING asset's records. -Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds -them, or pass 2–6 bundles (funded wrapped senders, wrapped receivers, -then owner and withdrawal). +### `rebalance_position(*, plan=None, pool_key=None, position_token_id=None, tick_lower=None, tick_upper=None, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None, position_record=None, token0_program=None, token1_program=None, token0_record=None, token1_record=None, tick_lower_hint=None, tick_upper_hint=None, deadline_offset_blocks=20, nonce=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` -Raises: - ValueError: Without a plan or a complete (pool, range, sizing), or - with the wrong number of compliance proof bundles. - InsufficientRecordsError: If no record covers a funded side. +Prepare an atomic replacement in the same pool, keeping owner and withdrawal. + +Pass a reviewed ``plan`` verbatim, or pool/range/sizing arguments as in +``plan_rebalance``. Pool/position arguments must match the plan, and +supplied ticks must align to its range. Sizing/amount arguments +are rejected. Exact bounds enforce the quote; wider bounds use actual +recovery and a zero target sizes liquidity at execution. Funding and +immediate refunds stay fixed; flexible surplus remains collectible on +the successor. Wrapped funding uses the underlying asset's records. + +Preparation reads chain state and resolves records and proofs. Submit +with ``delegate()`` or ``transact()``. A rejection rolls back all funds +movements but can still cost a fee; refresh state before retrying. +The default deadline is 20 blocks. Flexible calls require a deployment +supporting execution-time recovery and amount-driven rebalancing. +Freeze-list proofs are built automatically unless supplied explicitly. + +### `plan_rebalance_exact_amounts(*, pool_key, position_token_id, tick_lower, tick_upper, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None)` + +Quote a complete replacement with fixed recovery and deposits. + +Supply a positive target or paired ``max_funding0/1`` budgets. Minimums +must equal caps. Price or fee changes can reject execution. Reads only. + +### `rebalance_position_exact_amounts(*, plan=None, pool_key=None, position_token_id=None, tick_lower=None, tick_upper=None, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None, position_record=None, token0_program=None, token1_program=None, token0_record=None, token1_record=None, tick_lower_hint=None, tick_upper_hint=None, deadline_offset_blocks=20, nonce=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` + +Prepare an exact quote using target-or-budget sizing, or a reviewed plan. + +Uses ``plan_rebalance_exact_amounts`` constraints. Price or fee changes +can reject execution. Submit with ``delegate()`` or ``transact()``. + +### `plan_rebalance_to_liquidity(*, pool_key, position_token_id, tick_lower, tick_upper, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None)` + +Quote fixed successor liquidity with actual recovered funds. + +Supply a positive target and both caps; one bound must be flexible. +Minimums and fixed funding/refunds default to zero. Rejects quotes +outside the bounds or available funds. Later price changes can still +reject execution. Reads only. + +### `rebalance_position_to_liquidity(*, plan=None, pool_key=None, position_token_id=None, tick_lower=None, tick_upper=None, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None, position_record=None, token0_program=None, token1_program=None, token0_record=None, token1_record=None, tick_lower_hint=None, tick_upper_hint=None, deadline_offset_blocks=20, nonce=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` + +Prepare fixed successor liquidity with bounded token consumption. + +Uses ``plan_rebalance_to_liquidity`` constraints, or a reviewed plan. +Insufficient execution-time funds reject rather than minting less. +Submit with ``delegate()`` or ``transact()``. + +### `plan_rebalance_from_amounts(*, pool_key, position_token_id, tick_lower, tick_upper, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None)` + +Estimate replacement liquidity from both token caps. + +Omit the target or set zero. Minimums and fixed funding/refunds default +to zero. Estimates and token minimums do not guarantee liquidity. +Surplus stays collectible; no swap occurs. Reads only; integer base units. + +### `rebalance_position_from_amounts(*, plan=None, pool_key=None, position_token_id=None, tick_lower=None, tick_upper=None, liquidity_target=None, max_funding0=None, max_funding1=None, amount0_desired=None, amount1_desired=None, amount0_min=None, amount1_min=None, funded0=None, funded1=None, refund0=None, refund1=None, position_record=None, token0_program=None, token1_program=None, token0_record=None, token1_record=None, tick_lower_hint=None, tick_upper_hint=None, deadline_offset_blocks=20, nonce=None, compliance_proofs=None, wrapper_proofs=None, imports=None, account=None)` + +Prepare a replacement sized from available tokens at execution. + +Uses ``plan_rebalance_from_amounts`` constraints, or a reviewed plan. +Estimated liquidity is advisory; surplus stays collectible. +Submit with ``delegate()`` or ``transact()``. -### `plan_inventory(self, token: 'str', target: 'InventoryTarget', *, max_transactions: 'Optional[int]' = None, account: 'Any' = None) -> 'InventoryPlan'` +### `plan_inventory(token, target, *, max_transactions=None, account=None)` Plan the joins and splits that give *token* the record layout trades need. @@ -571,7 +612,7 @@ Example:: plan = dex.plan_inventory("USDCx", InventoryTarget(records=6, min_record_amount=100_000, distribution="balanced")) -### `rebalance_inventory(self, token: 'str', target: 'InventoryTarget', *, max_transactions: 'Optional[int]' = None, timeout: 'float' = 120.0, poll_interval: 'float' = 1.0, max_fee_microcredits: 'Optional[int]' = None, cancel: 'Any' = None, account: 'Any' = None) -> 'InventoryResult'` +### `rebalance_inventory(token, target, *, max_transactions=None, timeout=120.0, poll_interval=1.0, max_fee_microcredits=None, cancel=None, account=None)` Reshape *token*'s underlying records to *target*, one confirmed transaction at a time. @@ -588,18 +629,18 @@ Example:: if result.status == "interrupted": dex.inventory.reconcile_record_inventory() -### `get_pool(self, pool_key: 'str') -> 'g.PoolState'` +### `get_pool(pool_key)` Static pool configuration (token pair, fee, decimal scales). -### `get_slot(self, pool_key: 'str') -> 'SlotView'` +### `get_slot(pool_key)` Live trading state (sqrt price, tick, in-range liquidity). Raises :class:`PoolNotFoundError` when the pool does not exist, or :class:`PoolNotInitializedError` when it exists but has no slot yet. -### `get_swap_output(self, swap: "'SwapHandle | str'") -> 'g.SwapOutput'` +### `get_swap_output(swap)` Chain-computed output of a finalized swap request. @@ -607,7 +648,7 @@ Accepts the :class:`SwapHandle` from ``swap()`` or a bare swap id. Raises :class:`SwapOutputNotFinalizedError` when the entry is absent — not finalized yet (retry after a few blocks) or already claimed. -### `get_swap_execution(self, swap: "'SwapHandle | str'") -> 'Optional[SwapExecution]'` +### `get_swap_execution(swap)` Per-hop fill receipt of an executed swap — what each pool leg paid. @@ -621,7 +662,7 @@ Raises: ValueError: If the header names a hop the node did not return — a node lagging its own finalize; retry. -### `get_balances(self, address: 'Optional[str]' = None, account: 'Any' = None, *, include_private: 'bool' = True) -> 'dict[str, dict[str, Any]]'` +### `get_balances(address=None, account=None, *, include_private=True)` Public + private + total per token id, joined via the API's token registry. Defaults to the bound account's address; returns @@ -633,7 +674,7 @@ token (their records are not scannable) rather than silently mixing in the caller's own private holdings. ``include_private=False`` skips the record scan (public only — before scanner credentials). -### `get_public_balances(self, programs: 'list[str]', address: 'Optional[str]' = None) -> 'dict[str, int]'` +### `get_public_balances(programs, address=None)` Public balances per token program from each program's on-chain ``balances`` mapping (plain-address key; one read per program, any @@ -644,12 +685,12 @@ network lacks, or a non-ARC-20 value, is skipped with a warning rather than failing every other token. *address* defaults to the bound account's (ValueError when there is none). -### `get_private_balances(self, programs: 'list[str]', account: 'Any' = None) -> 'dict[str, int]'` +### `get_private_balances(programs, account=None)` Sum of unspent record amounts per wrapper program (spendable privately). Requires a configured record provider. -### `derive_pool_key(self, token0: 'str', token1: 'str', fee: 'int') -> 'str'` +### `derive_pool_key(token0, token1, fee)` Compute the pool key for a token pair and fee tier. Local — no network. @@ -660,7 +701,7 @@ derivation is sensitive to token order and is network-scoped, so swapping a valid-looking ``field`` that matches nothing on chain. *fee* is the contract's ``u16`` fee tier. -### `derive_tick_key(self, pool_key: 'str', tick: 'int') -> 'str'` +### `derive_tick_key(pool_key, tick)` Compute the key of one tick within a pool. Local — no network. diff --git a/shield-swap-sdk/python/aleo_shield_swap/__init__.py b/shield-swap-sdk/python/aleo_shield_swap/__init__.py index 66d8871a..b2f84173 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/__init__.py +++ b/shield-swap-sdk/python/aleo_shield_swap/__init__.py @@ -46,6 +46,10 @@ def _require_aleo_sdk() -> None: from .rebalance import ( RebalancePlan as RebalancePlan, RebalanceResult as RebalanceResult, + plan_rebalance as plan_rebalance, + plan_rebalance_exact_amounts as plan_rebalance_exact_amounts, + plan_rebalance_to_liquidity as plan_rebalance_to_liquidity, + plan_rebalance_from_amounts as plan_rebalance_from_amounts, ) from .compliance import ( ClaimProofs as ClaimProofs, @@ -132,7 +136,8 @@ def agent_guide() -> str: "AirdropPendingError", "AirdropRateLimitedError", "CredentialsMissingError", "OwnedPosition", "OwnedPositionState", "HopFill", "SwapExecution", - "RebalancePlan", "RebalanceResult", + "RebalancePlan", "RebalanceResult", "plan_rebalance", + "plan_rebalance_exact_amounts", "plan_rebalance_to_liquidity", "plan_rebalance_from_amounts", "ConfirmAirdropResult", "Profile", "Journal", "REGISTRATION_STAGES", "OnboardReport", "StageOutcome", "SessionStatus", "PositionView", "SwapBatchReport", "CollectReport", "blinded_identity_at", diff --git a/shield-swap-sdk/python/aleo_shield_swap/agent.py b/shield-swap-sdk/python/aleo_shield_swap/agent.py index 33c923d1..4662e0c2 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/agent.py +++ b/shield-swap-sdk/python/aleo_shield_swap/agent.py @@ -12,6 +12,9 @@ from __future__ import annotations from dataclasses import asdict, is_dataclass +from functools import partial + +from .rebalance import _AMOUNT_FIELDS from typing import Any, Callable _S = {"type": "string"} @@ -112,17 +115,25 @@ def _h_get_swap_execution(dex: Any, args: dict[str, Any]) -> Any: return _serialize(dex.get_swap_execution(args["swap_id"])) -def _opt_int(args: dict[str, Any], key: str) -> Any: +def _opt_int(args: dict[str, Any], key: str) -> int | None: value = args.get(key) - return int(value) if value is not None else None + if value is None: + return None + if type(value) is int: + return value + if isinstance(value, str) and value.isascii() and value.isdecimal(): + return int(value) + raise ValueError(f"{key} must be an integer or an unsigned decimal integer string") def _rebalance_kwargs(args: dict[str, Any]) -> dict[str, Any]: - return dict(pool_key=args["pool_key"], position_token_id=args["position_token_id"], + result = dict(pool_key=args["pool_key"], position_token_id=args["position_token_id"], tick_lower=int(args["tick_lower"]), tick_upper=int(args["tick_upper"]), liquidity_target=_opt_int(args, "liquidity_target"), max_funding0=_opt_int(args, "max_funding0"), max_funding1=_opt_int(args, "max_funding1")) + result.update({key: _opt_int(args, key) for key in _AMOUNT_FIELDS if args.get(key) is not None}) + return result #: RebalancePlan fields that are raw u128 amounts — reported as strings so @@ -130,7 +141,9 @@ def _rebalance_kwargs(args: dict[str, Any]) -> dict[str, Any]: #: (the tool descriptions promise "raw base units as strings"). _PLAN_AMOUNT_FIELDS = ("old_liquidity", "fees_accrued0", "fees_accrued1", "recovered0", "recovered1", "required0", "required1", - "funded0", "funded1", "refund0", "refund1", "liquidity_target") + "funded0", "funded1", "refund0", "refund1", "liquidity_target", + "amount0_desired", "amount1_desired", "amount0_min", "amount1_min", + "estimated_liquidity") def _plan_json(plan: Any) -> dict[str, Any]: @@ -141,12 +154,14 @@ def _plan_json(plan: Any) -> dict[str, Any]: return out -def _h_plan_rebalance(dex: Any, args: dict[str, Any]) -> Any: - return _plan_json(dex.plan_rebalance(**_rebalance_kwargs(args))) +def _h_plan_rebalance(dex: Any, args: dict[str, Any], *, mode: str = "") -> Any: + method = getattr(dex, "plan_rebalance" + (f"_{mode}" if mode else "")) + return _plan_json(method(**_rebalance_kwargs(args))) -def _h_rebalance_position(dex: Any, args: dict[str, Any]) -> Any: - result = _serialize(dex.rebalance_position(**_rebalance_kwargs(args)).delegate()) +def _h_rebalance_position(dex: Any, args: dict[str, Any], *, mode: str = "") -> Any: + method = getattr(dex, "rebalance_position" + (f"_{mode}" if mode else "")) + result = _serialize(method(**_rebalance_kwargs(args)).delegate()) if isinstance(result.get("plan"), dict): for key in _PLAN_AMOUNT_FIELDS: if result["plan"].get(key) is not None: @@ -154,6 +169,19 @@ def _h_rebalance_position(dex: Any, args: dict[str, Any]) -> Any: return result +_REBALANCE_REQUIRED = ["pool_key", "position_token_id", "tick_lower", "tick_upper"] +_REBALANCE_PROPERTIES = { + "pool_key": _S, "position_token_id": _S, "tick_lower": _I, "tick_upper": _I, + "liquidity_target": {**_S, "description": "Positive exact liquidity; zero sizes from tokens at execution."}, + "max_funding0": {**_S, "description": "Quote-time extra token0 budget; requires max_funding1 and no explicit caps."}, + "max_funding1": {**_S, "description": "Quote-time extra token1 budget; requires max_funding0 and no explicit caps."}, + **{f"amount{i}_desired": {**_S, "description": f"Maximum token{i} consumed, in integer base units; supply both caps."} for i in range(2)}, + **{f"amount{i}_min": {**_S, "description": f"Minimum token{i} consumed; generic/exact helpers default to the cap, flexible helpers to zero."} for i in range(2)}, + **{f"funded{i}": {**_S, "description": f"Fixed extra token{i} funding; flexible calls default to zero. Cannot combine with refund{i}."} for i in range(2)}, + **{f"refund{i}": {**_S, "description": f"Fixed immediate token{i} payout; flexible calls default to zero. Cannot combine with funded{i}."} for i in range(2)}, +} + + _TOOLS: list[tuple[str, str, dict[str, Any], Callable[[Any, dict[str, Any]], Any]]] = [ ("setup_account", "Register this machine's shield-swap profile end to end (auth, " @@ -212,33 +240,53 @@ def _h_rebalance_position(dex: Any, args: dict[str, Any]) -> Any: "null until the swap finalizes.", _schema({"swap_id": _S}, ["swap_id"]), _h_get_swap_execution), ("plan_rebalance", - "Quote moving a position to a new tick range in one transaction (testnet " - "only — the rebalance router is not on mainnet). Size with EXACTLY one " - "of liquidity_target (exact successor liquidity) or max_funding0 AND " - "max_funding1 (extra raw units the user will add; 0 and 0 = reuse only " - "what the old position returns). Reports recovered, required, funded, " - "and refund amounts per token; show them to the user before executing. " - "Amounts are raw base units as strings.", - _schema({"pool_key": _S, "position_token_id": _S, "tick_lower": _I, - "tick_upper": _I, "liquidity_target": _S, "max_funding0": _S, - "max_funding1": _S}, - ["pool_key", "position_token_id", "tick_lower", "tick_upper"]), - _h_plan_rebalance), + "Plan moving a complete position to a new range (testnet router). " + "Positive liquidity_target with omitted/equal token bounds enforces an exact quote; " + "max_funding0/1 also size an exact quote. Wider token bounds use actual recovery; " + "a zero target requires both desired caps and sizes liquidity at execution. " + "Funding/refunds are fixed, flexible surplus stays collectible on the successor. " + "Show the plan before executing; amounts are raw base units as strings. " + "estimated_liquidity is advisory, never a guaranteed minimum. Flexible calls require an upgraded contract.", + _schema(_REBALANCE_PROPERTIES, _REBALANCE_REQUIRED), _h_plan_rebalance), ("rebalance_position", - "Execute the rebalance plan_rebalance described: burn the old position, " - "settle its principal and fees, add any funding, and mint the successor " - "range — atomically. Same sizing arguments as plan_rebalance (the plan is " - "rebuilt at submit time). Reverts if the pool price moved since planning; " - "on revert, re-plan and resubmit. Returns the new position id, the " - "transaction id, and the submitted plan.", - _schema({"pool_key": _S, "position_token_id": _S, "tick_lower": _I, - "tick_upper": _I, "liquidity_target": _S, "max_funding0": _S, - "max_funding1": _S}, - ["pool_key", "position_token_id", "tick_lower", "tick_upper"]), - _h_rebalance_position), + "Replace a complete position atomically, keeping its owner and withdrawal address. " + "Uses plan_rebalance arguments and rebuilds the plan before submitting. " + "Exact calls can reject on price/fee changes; flexible calls use actual recovery " + "within token bounds. Funding/refunds stay fixed; surplus stays collectible. " + "A rejected transaction moves no funds but can cost a fee. Returns the successor, " + "transaction ID, and submitted plan with amounts as base-unit strings.", + _schema(_REBALANCE_PROPERTIES, _REBALANCE_REQUIRED), _h_rebalance_position), ] +_REBALANCE_MODES = { + "exact_amounts": "Enforce exact quoted recovery and deposits. Supply either a positive liquidity_target or paired max_funding0/max_funding1 budgets, never both. Token bounds, if supplied, must be equal; price or fee changes can reject execution.", + "to_liquidity": "Require exact successor liquidity using actual recovery. Supply a positive target and both token caps; minimums default to zero and at least one bound must be wider. Insufficient funds reject instead of minting less liquidity.", + "from_amounts": "Size successor liquidity from actual recovered tokens plus fixed funding minus fixed refunds, capped per token. Supply both desired caps; target must be omitted or zero and minimums default to zero. Estimated liquidity is advisory; no swap occurs.", +} +for _mode, _description in _REBALANCE_MODES.items(): + _properties = dict(_REBALANCE_PROPERTIES) + _required = list(_REBALANCE_REQUIRED) + if _mode != "exact_amounts": + _properties.pop("max_funding0") + _properties.pop("max_funding1") + _required.extend(["amount0_desired", "amount1_desired"]) + if _mode == "to_liquidity": + _required.append("liquidity_target") + for _prefix, _handler, _effect in ( + ("plan_rebalance", _h_plan_rebalance, "Read chain state without submitting. Show the plan before execution."), + ("rebalance_position", _h_rebalance_position, "Rebuild the plan and submit atomically, keeping owner and withdrawal. Rejection rolls back funds but can cost a fee."), + ): + _funding_description = ( + "Fixed funding/refunds default to zero; surplus stays collectible on the successor. " + "Flexible calls require an upgraded contract. " + if _mode != "exact_amounts" else "") + _TOOLS.append((f"{_prefix}_{_mode}", + f"{_description} {_effect} Token amounts use integer base-unit strings. " + f"{_funding_description}Rebalance routing is testnet-only.", + _schema(dict(_properties), list(_required)), partial(_handler, mode=_mode))) + + def shield_swap_tools() -> list[dict[str, Any]]: """Tool definitions (Claude API ``tools=`` shape).""" return [{"name": name, "description": desc, "input_schema": schema} diff --git a/shield-swap-sdk/python/aleo_shield_swap/async_client.py b/shield-swap-sdk/python/aleo_shield_swap/async_client.py index 0319268d..87c89d7d 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/async_client.py +++ b/shield-swap-sdk/python/aleo_shield_swap/async_client.py @@ -49,7 +49,8 @@ SHIELD_SWAP_FREEZELIST, ClaimProofs, Slot, SwapProofs, check_proof_arguments, claim_slots, merge_legacy_wrapper_proofs, planned_proof_slots, supplied_literals, swap_slots, ) -from .rebalance import RebalancePlan, plan_rebalance as _plan_rebalance +from .rebalance import (RebalancePlan, plan_rebalance as _plan_rebalance, + _mode_parameters, _validate_planning) from .position_math import ( amounts_for_liquidity, fee_growth_inside, @@ -567,9 +568,16 @@ async def plan_rebalance(self, *, pool_key: str, position_token_id: str, tick_lower: int, tick_upper: int, liquidity_target: Optional[int] = None, max_funding0: Optional[int] = None, - max_funding1: Optional[int] = None) -> RebalancePlan: + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, funded1: Optional[int] = None, + refund0: Optional[int] = None, refund1: Optional[int] = None) -> RebalancePlan: """Quote a close-and-remint — see :meth:`ShieldSwap.plan_rebalance`. Reads only; the boundary-tick and wrapped-ness reads run concurrently.""" + _validate_planning(locals()) import asyncio pool = await self.get_pool(pool_key) slot = (await self.get_slot(pool_key)).raw @@ -590,7 +598,94 @@ async def plan_rebalance(self, *, pool_key: str, position_token_id: str, tick_lower=tick_lower, tick_upper=tick_upper, slot=slot, position=position, lower_tick=lower, upper_tick=upper, wrapped0=w0, wrapped1=w1, liquidity_target=liquidity_target, - max_funding0=max_funding0, max_funding1=max_funding1) + max_funding0=max_funding0, max_funding1=max_funding1, + amount0_desired=amount0_desired, amount1_desired=amount1_desired, + amount0_min=amount0_min, amount1_min=amount1_min, + funded0=funded0, funded1=funded1, refund0=refund0, refund1=refund1) + + async def plan_rebalance_exact_amounts( + self, + *, + pool_key: str, + position_token_id: str, + tick_lower: int, + tick_upper: int, + liquidity_target: Optional[int] = None, + max_funding0: Optional[int] = None, + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, + funded1: Optional[int] = None, + refund0: Optional[int] = None, + refund1: Optional[int] = None, + ) -> RebalancePlan: + """Quote a complete replacement with fixed recovery and deposits. + + Supply a positive target or paired ``max_funding0/1`` budgets. Minimums + must equal caps. Price or fee changes can reject execution. Reads only. + """ + params = {key: value for key, value in locals().items() if key != "self"} + return await self.plan_rebalance(**_mode_parameters("exact_amounts", params)) + + async def plan_rebalance_to_liquidity( + self, + *, + pool_key: str, + position_token_id: str, + tick_lower: int, + tick_upper: int, + liquidity_target: Optional[int] = None, + max_funding0: Optional[int] = None, + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, + funded1: Optional[int] = None, + refund0: Optional[int] = None, + refund1: Optional[int] = None, + ) -> RebalancePlan: + """Quote fixed successor liquidity with actual recovered funds. + + Supply a positive target and both caps; one bound must be flexible. + Minimums and fixed funding/refunds default to zero. Rejects quotes + outside the bounds or available funds. Later price changes can still + reject execution. Reads only. + """ + params = {key: value for key, value in locals().items() if key != "self"} + return await self.plan_rebalance(**_mode_parameters("to_liquidity", params)) + + async def plan_rebalance_from_amounts( + self, + *, + pool_key: str, + position_token_id: str, + tick_lower: int, + tick_upper: int, + liquidity_target: Optional[int] = None, + max_funding0: Optional[int] = None, + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, + funded1: Optional[int] = None, + refund0: Optional[int] = None, + refund1: Optional[int] = None, + ) -> RebalancePlan: + """Estimate replacement liquidity from both token caps. + + Omit the target or set zero. Minimums and fixed funding/refunds default + to zero. Estimates and token minimums do not guarantee liquidity. + Surplus stays collectible; no swap occurs. Reads only; integer base units. + """ + params = {key: value for key, value in locals().items() if key != "self"} + return await self.plan_rebalance(**_mode_parameters("from_amounts", params)) async def get_owned_position(self, position_token_id: str, *, account: Any = None) -> Optional[OwnedPosition]: diff --git a/shield-swap-sdk/python/aleo_shield_swap/client.py b/shield-swap-sdk/python/aleo_shield_swap/client.py index 09acbd15..6c63dd52 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/client.py +++ b/shield-swap-sdk/python/aleo_shield_swap/client.py @@ -109,6 +109,7 @@ RebalancePlan, RebalanceResult, plan_rebalance as _plan_rebalance, + _mode_parameters, _validate_planning, _validate_plan_arguments, ) from .tick_math import ( MAX_TICK, @@ -1644,26 +1645,30 @@ def plan_rebalance(self, *, pool_key: str, position_token_id: str, tick_lower: int, tick_upper: int, liquidity_target: Optional[int] = None, max_funding0: Optional[int] = None, - max_funding1: Optional[int] = None) -> RebalancePlan: - """Quote a close-and-remint of one position into a new range. Reads only. - - Reads the pool, slot, ``positions`` entry, both current boundary ticks, - and each side's wrapped-ness, then derives what the close returns, what - the successor range needs, and per side the funding to add or surplus - to refund. Size the successor with exactly one of *liquidity_target* - (exact) or *max_funding0*/*max_funding1* (a budget the planner solves - for; ``0, 0`` rebalances on recovered funds alone). - - The plan is only valid at the pool price it was built against — the - contract asserts every amount at finalize — so build it right before - :meth:`rebalance_position` and never cache one. - - Raises: - PoolNotFoundError / PoolNotInitializedError: For an unknown pool. - ValueError: If the position or a boundary tick does not exist, the - aligned range is empty, the sizing is ambiguous, or the budget - supports no liquidity. + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, funded1: Optional[int] = None, + refund0: Optional[int] = None, refund1: Optional[int] = None) -> RebalancePlan: + """Plan a complete position replacement without signing or submitting. + + A positive target with omitted bounds preserves exact quoted recovery + and deposits. ``max_funding0/1`` also produce an exact quote sized at + the current price. Explicit ``amount0/1_desired`` cap token consumption; + ``amount0/1_min`` default to the caps. Widen either bound to use actual + recovery, or set ``liquidity_target=0`` to size liquidity at execution. + Flexible funding and refunds are fixed amounts, defaulting to zero; + surplus remains collectible on the successor and earns no LP fees. + + Amounts are integer token base units, from 0 through 2**128 - 1. + ``estimated_liquidity`` is advisory; token floors do not guarantee a + minimum liquidity. Flexible plans must fit the quoted token + bounds and available funds; funding errors name the amount to supply. + Named planners supply mode-specific defaults. Requires an existing pool, position, and initialized boundary ticks. """ + _validate_planning(locals()) pool = self.get_pool(pool_key) slot = self.get_slot(pool_key).raw position = self._position_state(position_token_id) @@ -1681,7 +1686,94 @@ def plan_rebalance(self, *, pool_key: str, position_token_id: str, wrapped0=self._is_wrapped(str(pool.token0)), wrapped1=self._is_wrapped(str(pool.token1)), liquidity_target=liquidity_target, - max_funding0=max_funding0, max_funding1=max_funding1) + max_funding0=max_funding0, max_funding1=max_funding1, + amount0_desired=amount0_desired, amount1_desired=amount1_desired, + amount0_min=amount0_min, amount1_min=amount1_min, + funded0=funded0, funded1=funded1, refund0=refund0, refund1=refund1) + + def plan_rebalance_exact_amounts( + self, + *, + pool_key: str, + position_token_id: str, + tick_lower: int, + tick_upper: int, + liquidity_target: Optional[int] = None, + max_funding0: Optional[int] = None, + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, + funded1: Optional[int] = None, + refund0: Optional[int] = None, + refund1: Optional[int] = None, + ) -> RebalancePlan: + """Quote a complete replacement with fixed recovery and deposits. + + Supply a positive target or paired ``max_funding0/1`` budgets. Minimums + must equal caps. Price or fee changes can reject execution. Reads only. + """ + params = {key: value for key, value in locals().items() if key != "self"} + return self.plan_rebalance(**_mode_parameters("exact_amounts", params)) + + def plan_rebalance_to_liquidity( + self, + *, + pool_key: str, + position_token_id: str, + tick_lower: int, + tick_upper: int, + liquidity_target: Optional[int] = None, + max_funding0: Optional[int] = None, + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, + funded1: Optional[int] = None, + refund0: Optional[int] = None, + refund1: Optional[int] = None, + ) -> RebalancePlan: + """Quote fixed successor liquidity with actual recovered funds. + + Supply a positive target and both caps; one bound must be flexible. + Minimums and fixed funding/refunds default to zero. Rejects quotes + outside the bounds or available funds. Later price changes can still + reject execution. Reads only. + """ + params = {key: value for key, value in locals().items() if key != "self"} + return self.plan_rebalance(**_mode_parameters("to_liquidity", params)) + + def plan_rebalance_from_amounts( + self, + *, + pool_key: str, + position_token_id: str, + tick_lower: int, + tick_upper: int, + liquidity_target: Optional[int] = None, + max_funding0: Optional[int] = None, + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, + funded1: Optional[int] = None, + refund0: Optional[int] = None, + refund1: Optional[int] = None, + ) -> RebalancePlan: + """Estimate replacement liquidity from both token caps. + + Omit the target or set zero. Minimums and fixed funding/refunds default + to zero. Estimates and token minimums do not guarantee liquidity. + Surplus stays collectible; no swap occurs. Reads only; integer base units. + """ + params = {key: value for key, value in locals().items() if key != "self"} + return self.plan_rebalance(**_mode_parameters("from_amounts", params)) def rebalance_position( self, @@ -1694,6 +1786,14 @@ def rebalance_position( liquidity_target: Optional[int] = None, max_funding0: Optional[int] = None, max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, + funded1: Optional[int] = None, + refund0: Optional[int] = None, + refund1: Optional[int] = None, position_record: Optional[str] = None, token0_program: Optional[str] = None, token1_program: Optional[str] = None, @@ -1708,39 +1808,44 @@ def rebalance_position( imports: Optional[dict[str, str]] = None, account: Any = None, ) -> DexCall[RebalanceResult]: - """Close a position and mint its successor range in ONE transaction. - - Burns the old position, settles its principal and every fee it earned, - adds funding from the signer's records where the new range needs more, - mints the successor with the same owner and withdrawal address, and - pays any surplus to the withdrawal address — atomically, through - ``shield_swap_rebalance_router.aleo`` (deployed on testnet). Either - pass a *plan* from :meth:`plan_rebalance` (submitted verbatim), or the - pool, range, and one sizing mode and the plan is built here. - - Every amount is asserted against the pool price at execution: a trade - that moves the price between planning and finalize reverts the whole - transaction (fee paid, no funds moved). Rebuild and resubmit when - that happens; the short default deadline fails stale requests cheaply. - Funding records for a wrapped side are the UNDERLYING asset's records. - Freeze-list proofs: leave ``compliance_proofs`` unset and the SDK builds - them, or pass 2–6 bundles (funded wrapped senders, wrapped receivers, - then owner and withdrawal). - - Raises: - ValueError: Without a plan or a complete (pool, range, sizing), or - with the wrong number of compliance proof bundles. - InsufficientRecordsError: If no record covers a funded side. + """Prepare an atomic replacement in the same pool, keeping owner and withdrawal. + + Pass a reviewed ``plan`` verbatim, or pool/range/sizing arguments as in + ``plan_rebalance``. Pool/position arguments must match the plan, and + supplied ticks must align to its range. Sizing/amount arguments + are rejected. Exact bounds enforce the quote; wider bounds use actual + recovery and a zero target sizes liquidity at execution. Funding and + immediate refunds stay fixed; flexible surplus remains collectible on + the successor. Wrapped funding uses the underlying asset's records. + + Preparation reads chain state and resolves records and proofs. Submit + with ``delegate()`` or ``transact()``. A rejection rolls back all funds + movements but can still cost a fee; refresh state before retrying. + The default deadline is 20 blocks. Flexible calls require a deployment + supporting execution-time recovery and amount-driven rebalancing. + Freeze-list proofs are built automatically unless supplied explicitly. """ + planning = dict(liquidity_target=liquidity_target, + max_funding0=max_funding0, max_funding1=max_funding1, + amount0_desired=amount0_desired, amount1_desired=amount1_desired, + amount0_min=amount0_min, amount1_min=amount1_min, + funded0=funded0, funded1=funded1, refund0=refund0, refund1=refund1) acct = self._account(account) if plan is None: if pool_key is None or tick_lower is None or tick_upper is None: raise ValueError("Pass plan=, or pool_key, tick_lower, and " "tick_upper with one sizing mode.") # Validate the sizing before any chain read. - from .rebalance import _sizing - _sizing(liquidity_target, max_funding0, max_funding1) + _validate_planning(planning) else: + plan = _validate_plan_arguments(plan, locals()) + supplied_ticks = {"tick_lower": tick_lower, "tick_upper": tick_upper} + if any(tick is not None and tick != getattr(plan, key) + for key, tick in supplied_ticks.items()): + spacing = int(self.get_slot(plan.pool_key).raw.tick_spacing) + for key, tick in supplied_ticks.items(): + if tick is not None and round_tick_to_spacing(tick, spacing) != getattr(plan, key): + raise ValueError(f"{key} conflicts with the supplied plan after spacing alignment") pool_key, position_token_id = plan.pool_key, plan.position_token_id assert pool_key is not None pool = self.get_pool(pool_key) @@ -1754,8 +1859,7 @@ def rebalance_position( plan = self.plan_rebalance( pool_key=pool_key, position_token_id=position_token_id, tick_lower=tick_lower, tick_upper=tick_upper, - liquidity_target=liquidity_target, - max_funding0=max_funding0, max_funding1=max_funding1) + **planning) w0 = self._is_wrapped(str(pool.token0)) w1 = self._is_wrapped(str(pool.token1)) @@ -1789,6 +1893,8 @@ def survivor(hint: int) -> int: else upper_pred) deadline = get_deadline(self._aleo, deadline_offset_blocks) + desired0 = plan.amount0_desired if plan.amount0_desired is not None else plan.required0 + desired1 = plan.amount1_desired if plan.amount1_desired is not None else plan.required1 request = g.CoreRebalanceRequest( old_liquidity=plan.old_liquidity, recovered0=plan.recovered0, recovered1=plan.recovered1, @@ -1797,8 +1903,9 @@ def survivor(hint: int) -> int: liquidity_target=plan.liquidity_target, mint=g.MintPositionRequest( pool=pool_key, tick_lower=plan.tick_lower, tick_upper=plan.tick_upper, - amount0_desired=plan.required0, amount1_desired=plan.required1, - amount0_min=plan.required0, amount1_min=plan.required1, + amount0_desired=desired0, amount1_desired=desired1, + amount0_min=plan.amount0_min if plan.amount0_min is not None else desired0, + amount1_min=plan.amount1_min if plan.amount1_min is not None else desired1, tick_lower_hint=lo_hint, tick_upper_hint=hi_hint), deadline=deadline, ).to_plaintext() @@ -1866,6 +1973,131 @@ def build_result(tx_id: str, outputs: list[Any]) -> RebalanceResult: return DexCall(self._aleo, bound, build_result) + def rebalance_position_exact_amounts( + self, + *, + plan: Optional[RebalancePlan] = None, + pool_key: Optional[str] = None, + position_token_id: Optional[str] = None, + tick_lower: Optional[int] = None, + tick_upper: Optional[int] = None, + liquidity_target: Optional[int] = None, + max_funding0: Optional[int] = None, + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, + funded1: Optional[int] = None, + refund0: Optional[int] = None, + refund1: Optional[int] = None, + position_record: Optional[str] = None, + token0_program: Optional[str] = None, + token1_program: Optional[str] = None, + token0_record: Optional[str] = None, + token1_record: Optional[str] = None, + tick_lower_hint: Optional[int] = None, + tick_upper_hint: Optional[int] = None, + deadline_offset_blocks: int = REBALANCE_DEADLINE_OFFSET_BLOCKS, + nonce: Optional[str] = None, + compliance_proofs: Optional[RebalanceProofs] = None, + wrapper_proofs: Optional[str] = None, + imports: Optional[dict[str, str]] = None, + account: Any = None, + ) -> DexCall[RebalanceResult]: + """Prepare an exact quote using target-or-budget sizing, or a reviewed plan. + + Uses ``plan_rebalance_exact_amounts`` constraints. Price or fee changes + can reject execution. Submit with ``delegate()`` or ``transact()``. + """ + params = {key: value for key, value in locals().items() if key != "self"} + return self.rebalance_position(**_mode_parameters("exact_amounts", params)) + + def rebalance_position_to_liquidity( + self, + *, + plan: Optional[RebalancePlan] = None, + pool_key: Optional[str] = None, + position_token_id: Optional[str] = None, + tick_lower: Optional[int] = None, + tick_upper: Optional[int] = None, + liquidity_target: Optional[int] = None, + max_funding0: Optional[int] = None, + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, + funded1: Optional[int] = None, + refund0: Optional[int] = None, + refund1: Optional[int] = None, + position_record: Optional[str] = None, + token0_program: Optional[str] = None, + token1_program: Optional[str] = None, + token0_record: Optional[str] = None, + token1_record: Optional[str] = None, + tick_lower_hint: Optional[int] = None, + tick_upper_hint: Optional[int] = None, + deadline_offset_blocks: int = REBALANCE_DEADLINE_OFFSET_BLOCKS, + nonce: Optional[str] = None, + compliance_proofs: Optional[RebalanceProofs] = None, + wrapper_proofs: Optional[str] = None, + imports: Optional[dict[str, str]] = None, + account: Any = None, + ) -> DexCall[RebalanceResult]: + """Prepare fixed successor liquidity with bounded token consumption. + + Uses ``plan_rebalance_to_liquidity`` constraints, or a reviewed plan. + Insufficient execution-time funds reject rather than minting less. + Submit with ``delegate()`` or ``transact()``. + """ + params = {key: value for key, value in locals().items() if key != "self"} + return self.rebalance_position(**_mode_parameters("to_liquidity", params)) + + def rebalance_position_from_amounts( + self, + *, + plan: Optional[RebalancePlan] = None, + pool_key: Optional[str] = None, + position_token_id: Optional[str] = None, + tick_lower: Optional[int] = None, + tick_upper: Optional[int] = None, + liquidity_target: Optional[int] = None, + max_funding0: Optional[int] = None, + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, + funded1: Optional[int] = None, + refund0: Optional[int] = None, + refund1: Optional[int] = None, + position_record: Optional[str] = None, + token0_program: Optional[str] = None, + token1_program: Optional[str] = None, + token0_record: Optional[str] = None, + token1_record: Optional[str] = None, + tick_lower_hint: Optional[int] = None, + tick_upper_hint: Optional[int] = None, + deadline_offset_blocks: int = REBALANCE_DEADLINE_OFFSET_BLOCKS, + nonce: Optional[str] = None, + compliance_proofs: Optional[RebalanceProofs] = None, + wrapper_proofs: Optional[str] = None, + imports: Optional[dict[str, str]] = None, + account: Any = None, + ) -> DexCall[RebalanceResult]: + """Prepare a replacement sized from available tokens at execution. + + Uses ``plan_rebalance_from_amounts`` constraints, or a reviewed plan. + Estimated liquidity is advisory; surplus stays collectible. + Submit with ``delegate()`` or ``transact()``. + """ + params = {key: value for key, value in locals().items() if key != "self"} + return self.rebalance_position(**_mode_parameters("from_amounts", params)) + def _select_position_record(self, pool_key: str, account: Any, position_token_id: Optional[str] = None) -> str: """Unspent PositionNFT plaintext for *pool_key* from the shield_swap diff --git a/shield-swap-sdk/python/aleo_shield_swap/rebalance.py b/shield-swap-sdk/python/aleo_shield_swap/rebalance.py index c77a1823..f99a391e 100644 --- a/shield-swap-sdk/python/aleo_shield_swap/rebalance.py +++ b/shield-swap-sdk/python/aleo_shield_swap/rebalance.py @@ -1,19 +1,14 @@ -"""Rebalance planning — the exact close-and-remint quote the contract asserts. +"""Plan a complete position replacement from a supplied chain snapshot. -A rebalance (``shield_swap_rebalance_router.aleo``) burns a position, settles -everything it returns, optionally adds funds, and mints the successor range -in ONE transaction. The contract re-derives every amount at finalize and -asserts equality, so the plan is only submittable at the pool price it was -built against: rebuild after any delay rather than caching one. - -Pure functions only — the client feeds them chain state (see -``ShieldSwap.plan_rebalance``); a caller with its own indexer can feed them -directly. Mirrors veil's ``planRebalance`` field for field. +Exact bounds enforce quoted recovery and deposits. Flexible bounds use actual +recovery; a zero target derives liquidity from token budgets at execution. +Planning never signs or submits a transaction. """ from __future__ import annotations -from dataclasses import dataclass -from typing import Optional +from dataclasses import asdict, dataclass +from operator import index +from typing import Any, Mapping, Optional from . import _generated as g from ._routing import rebalance_route @@ -30,51 +25,65 @@ #: a budget by a rounding unit; each retry lowers the target by one. BUDGET_CLAMP_RETRIES = 8 -#: Default request lifetime. Short on purpose: a plan is only valid at the -#: price it was built against, so a stale transaction almost certainly reverts -#: on the exactness asserts anyway — the deadline fails it cheaply instead. +#: Default request lifetime, in blocks, to limit exposure to state changes. REBALANCE_DEADLINE_OFFSET_BLOCKS = 20 @dataclass(frozen=True) class RebalancePlan: - """The exact rebalance a position can submit against the planned state. + """Describe submitted constraints and estimates for a replacement position. - All amounts are raw base units. The contract asserts, per side, - ``recovered + funded == required + refund`` and ``funded * refund == 0``; - every plan the planner produces satisfies both by construction, and a - hand-built plan must too. + Amounts use integer token base units. Flexible surplus stays collectible + on the successor and earns no liquidity fees until reinvested. - ``fees_accrued0/1`` are advisory (already folded into ``recovered``); - execution never reads them. + Attributes: + pool_key: Pool shared by the old and replacement positions. + position_token_id: Position to close completely. + tick_lower: Spacing-aligned lower bound of the replacement range. + tick_upper: Spacing-aligned upper bound of the replacement range. + old_liquidity: Full liquidity removed from the old position. + fees_accrued0: Estimated token0 fees since the last checkpoint. + fees_accrued1: Estimated token1 fees since the last checkpoint. + recovered0: Quoted token0 principal plus owed and accrued fees. + recovered1: Quoted token1 recovery; exact quotes enforce both values. + required0: Estimated token0 consumed, also the cap if bounds are absent. + required1: Estimated token1 consumed, also the cap if bounds are absent. + funded0: Fixed extra token0 supplied from private records. + funded1: Fixed extra token1 supplied from private records. + refund0: Fixed immediate token0 payout to the withdrawal address. + refund1: Fixed immediate token1 payout to the withdrawal address. + liquidity_target: Positive exact liquidity, or zero for execution-time sizing. + function_name: Router entry point determined by tokens and funded sides. + amount0_desired: Token0 consumption cap; None uses required0. + amount1_desired: Token1 consumption cap; None uses required1. + amount0_min: Token0 consumption floor; None uses its cap. + amount1_min: Token1 consumption floor; None uses its cap. + estimated_liquidity: Advisory liquidity when the target is zero. Never + submitted as the target or a guaranteed minimum liquidity. """ pool_key: str position_token_id: str - #: Successor range, spacing-aligned. tick_lower: int tick_upper: int - #: The position's live liquidity — the close removes all of it. old_liquidity: int - #: Fees earned since the position's checkpoint, settled by the close. fees_accrued0: int fees_accrued1: int - #: Everything the close returns: principal at the live price + owed + accrued. recovered0: int recovered1: int - #: What the successor range needs at the live price (rounded up). required0: int required1: int - #: What the caller must add — ``max(required - recovered, 0)``. funded0: int funded1: int - #: Surplus paid to the position's withdrawal address. refund0: int refund1: int - #: The successor position's exact liquidity. liquidity_target: int - #: The router entrypoint the plan selects. function_name: str + amount0_desired: Optional[int] = None + amount1_desired: Optional[int] = None + amount0_min: Optional[int] = None + amount1_min: Optional[int] = None + estimated_liquidity: Optional[int] = None @dataclass(frozen=True) @@ -94,8 +103,8 @@ def _sizing(liquidity_target: Optional[int], max_funding0: Optional[int], raise ValueError("Pass exactly one sizing mode: liquidity_target=, or " "max_funding0= and max_funding1= together") if has_target: - if liquidity_target <= 0: # type: ignore[operator] - raise ValueError("liquidity_target must be greater than zero") + if liquidity_target < 0: # type: ignore[operator] + raise ValueError("liquidity_target must not be negative") return if max_funding0 is None or max_funding1 is None: raise ValueError("Budget sizing needs both max_funding0 and max_funding1 " @@ -104,6 +113,135 @@ def _sizing(liquidity_target: Optional[int], max_funding0: Optional[int], raise ValueError("Funding budgets must not be negative") +_AMOUNT_FIELDS = ("amount0_desired", "amount1_desired", "amount0_min", "amount1_min", + "funded0", "funded1", "refund0", "refund1") +_PLAN_IDENTITY_FIELDS = ("pool_key", "position_token_id") +_PLAN_INPUT_FIELDS = ("liquidity_target", "max_funding0", "max_funding1", *_AMOUNT_FIELDS) + + +def _validate_amounts(params: Mapping[str, Any]) -> dict[str, Any]: + """Normalize integer inputs and reject invalid bounds and accounting.""" + params = dict(params) + fields = (*_AMOUNT_FIELDS, "liquidity_target", "old_liquidity", "recovered0", + "recovered1", "required0", "required1", "max_funding0", "max_funding1") + for key in fields: + value = params.get(key) + if value is None: + continue + message = f"{key} must be a u128 integer (0 through 2**128 - 1)" + if isinstance(value, bool): + raise ValueError(message) + try: + value = index(value) + except TypeError: + raise ValueError(message) from None + if not 0 <= value < 1 << 128: + raise ValueError(message) + params[key] = value + if any(params.get(key) is not None for key in ("max_funding0", "max_funding1")) and any( + params.get(key) is not None for key in ("amount0_desired", "amount1_desired", "amount0_min", "amount1_min")): + raise ValueError("Funding budgets cannot be combined with explicit token bounds; " + "use fixed funding (funded0/funded1) with bounds") + if params.get("liquidity_target") is not None and any( + params.get(key) is not None for key in ("max_funding0", "max_funding1")): + raise ValueError("Pass exactly one sizing mode: liquidity_target, or max_funding0 and max_funding1") + if (params.get("amount0_desired") is None) != (params.get("amount1_desired") is None): + raise ValueError("Supply amount0_desired and amount1_desired together") + if params.get("amount0_desired") is None and any( + params.get(key) is not None for key in ("amount0_min", "amount1_min")): + raise ValueError("Token minimums require amount0_desired and amount1_desired") + desired = [params.get(f"amount{i}_desired") for i in range(2)] + desired = [cap if cap is not None else params.get(f"required{i}") + for i, cap in enumerate(desired)] + minimum = [params.get(f"amount{i}_min") for i in range(2)] + minimum = [value if value is not None else desired[i] for i, value in enumerate(minimum)] + flexible = params.get("liquidity_target") == 0 or any( + lo is not None and cap is not None and lo < cap for lo, cap in zip(minimum, desired)) + for i, cap in enumerate(desired): + if cap is not None and minimum[i] > cap: + raise ValueError(f"Token{i} minimum exceeds its desired amount") + funded, refund = params.get(f"funded{i}"), params.get(f"refund{i}") + if (funded or 0) > 0 and (refund or 0) > 0: + raise ValueError(f"Token{i} cannot have both funding and a refund") + recovered, required = params.get(f"recovered{i}"), params.get(f"required{i}") + if not flexible and cap is not None and required is not None and cap != required: + raise ValueError(f"Exact token{i} amount must match the liquidity target's quoted deposit") + if (not flexible and cap is not None and recovered is not None + and funded is not None and refund is not None): + if recovered + funded != cap + refund: + raise ValueError(f"Exact token{i} recovery and funding must equal its desired amount and refund") + return params + + +def _validate_planning(params: Mapping[str, Any]) -> dict[str, Any]: + params = _validate_amounts(params) + _sizing(params.get("liquidity_target"), params.get("max_funding0"), params.get("max_funding1")) + explicit = params.get("amount0_desired") is not None + if explicit and params.get("liquidity_target") is None: + raise ValueError("Explicit token bounds require liquidity_target; use 0 for execution-time sizing") + if params.get("liquidity_target") == 0 and not explicit: + raise ValueError("A zero liquidity_target requires amount0_desired and amount1_desired") + if not explicit and any(params.get(key) is not None for key in ("funded0", "funded1", "refund0", "refund1")): + raise ValueError("Fixed funding and refunds require explicit token bounds") + return params + + +def _validate_plan_arguments(plan: RebalancePlan, params: Mapping[str, Any]) -> RebalancePlan: + """Validate state-independent arguments; the client aligns repeated ticks.""" + if any(params.get(key) is not None for key in _PLAN_INPUT_FIELDS): + raise ValueError("A supplied plan cannot be combined with planning overrides") + for key in _PLAN_IDENTITY_FIELDS: + if params.get(key) is not None and params[key] != getattr(plan, key): + raise ValueError(f"{key} conflicts with the supplied plan") + plan = RebalancePlan(**_validate_amounts(asdict(plan))) + if plan.liquidity_target == 0 and plan.amount0_desired is None: + raise ValueError("A zero liquidity_target requires amount0_desired and amount1_desired") + return plan + + +def _mode_parameters(mode: str, kwargs: Mapping[str, Any]) -> dict[str, Any]: + """Apply a named helper's guarantee without altering a prebuilt plan.""" + result = dict(kwargs) + plan = result.get("plan") + if plan is not None: + plan = _validate_plan_arguments(plan, result) + result["plan"] = plan + params = asdict(plan) + else: + result = _validate_amounts(result) + params = result + if mode != "exact_amounts": + if any(params.get(key) is not None for key in ("max_funding0", "max_funding1")): + raise ValueError("Use fixed funding (funded0/funded1), not max_funding, with explicit token bounds") + if mode == "from_amounts": + if params.get("liquidity_target") not in (None, 0): + raise ValueError("Amount-driven rebalancing requires a zero liquidity_target") + params["liquidity_target"] = 0 + elif params.get("liquidity_target") is None or params["liquidity_target"] <= 0: + raise ValueError("Exact liquidity requires a positive liquidity_target") + if any(params.get(f"amount{i}_desired") is None for i in range(2)): + raise ValueError("Supply amount0_desired and amount1_desired for bounded rebalancing") + # Omitted minima on an existing plan mean exact caps, not helper defaults. + if plan is None: + for i in range(2): + if params.get(f"amount{i}_min") is None: + params[f"amount{i}_min"] = 0 + _validate_amounts(params) + minima = [params.get(f"amount{i}_min") for i in range(2)] + caps = [params.get(f"amount{i}_desired") for i in range(2)] + caps = [cap if cap is not None else params.get(f"required{i}") for i, cap in enumerate(caps)] + minima = [lo if lo is not None else caps[i] for i, lo in enumerate(minima)] + if mode == "exact_amounts": + target = params.get("liquidity_target") + if target is not None and target <= 0: + raise ValueError("Exact amounts require a positive liquidity_target") + if minima != caps: + raise ValueError("Exact amounts require minimum and desired amounts to be equal") + elif mode == "to_liquidity" and minima == caps: + raise ValueError("Flexible recovery requires a wider bound on at least one token") + return result + + def plan_rebalance(*, pool_key: str, position_token_id: str, tick_lower: int, tick_upper: int, slot: g.Slot, position: g.Position, @@ -111,37 +249,35 @@ def plan_rebalance(*, pool_key: str, position_token_id: str, wrapped0: bool, wrapped1: bool, liquidity_target: Optional[int] = None, max_funding0: Optional[int] = None, - max_funding1: Optional[int] = None) -> RebalancePlan: - """Build the exact rebalance from pre-read chain state. Pure. - - Computes everything the transaction asserts: the full recovery of the old - range (principal at the live price, the settled ``tokens_owed``, and the - fees accrued since the checkpoints), the successor range's deposit, and - per side either the funding to add or the surplus to refund. - - Args: - pool_key: The pool the position belongs to. - position_token_id: The position to close. - tick_lower: Successor lower bound, before spacing alignment. - tick_upper: Successor upper bound. - slot: The pool's live slot (price, tick, spacing, fee accumulators). - position: The ``positions`` entry being closed. - lower_tick: The ``ticks`` entry at the position's CURRENT lower bound. - upper_tick: The entry at its current upper bound. - wrapped0: Whether token0 is a wrapper (routes and proofs follow). - wrapped1: Whether token1 is a wrapper. - liquidity_target: Exact successor liquidity — one sizing mode. - max_funding0: Token0 budget on top of what the close returns — the - other mode, together with *max_funding1*; the planner solves for - the largest liquidity the budget supports. ``0`` rebalances on - recovered funds alone. - max_funding1: Token1 budget. - - Raises: - ValueError: On an empty aligned range, both or neither sizing modes, - or a budget that supports no liquidity in the range. + max_funding1: Optional[int] = None, + amount0_desired: Optional[int] = None, + amount1_desired: Optional[int] = None, + amount0_min: Optional[int] = None, + amount1_min: Optional[int] = None, + funded0: Optional[int] = None, funded1: Optional[int] = None, + refund0: Optional[int] = None, refund1: Optional[int] = None) -> RebalancePlan: + """Plan a replacement position from pre-read pool, position, and tick state. + + Without token bounds, a positive ``liquidity_target`` or paired + ``max_funding0/1`` budgets produce an exact quote. Explicit desired amounts + cap consumption; minimums default to those caps. Widening either bound + uses actual recovery, with fixed funding/refunds defaulting to zero. + A zero target estimates liquidity from the capped available funds, but + leaves the submitted target at zero for execution-time sizing. + + All amount arguments accept integers from 0 through 2**128 - 1. + ``max_funding`` budgets cannot be combined with explicit bounds. Bounds + constrain token consumption, not minimum liquidity. Raises ValueError for + invalid bounds, conflicting transfers, or budgets supporting no liquidity. + No network reads, signing, or submission occurs. """ - _sizing(liquidity_target, max_funding0, max_funding1) + params = _validate_planning(locals()) + liquidity_target = params["liquidity_target"] + max_funding0, max_funding1 = params["max_funding0"], params["max_funding1"] + amount0_desired, amount1_desired = params["amount0_desired"], params["amount1_desired"] + amount0_min, amount1_min = params["amount0_min"], params["amount1_min"] + funded0, funded1 = params["funded0"], params["funded1"] + refund0, refund1 = params["refund0"], params["refund1"] spacing = int(slot.tick_spacing) lo = round_tick_to_spacing(tick_lower, spacing) @@ -180,40 +316,106 @@ def required_for(liquidity: int) -> tuple[int, int]: # anything the recovered balances do not cover is funding. return amounts_for_liquidity(sqrt_price, sqrt_lo, sqrt_hi, liquidity, round_up=True) - if liquidity_target is not None: + explicit = amount0_desired is not None + amount_mode = liquidity_target == 0 + available0 = recovered0 + (funded0 or 0) - (refund0 or 0) + available1 = recovered1 + (funded1 or 0) - (refund1 or 0) + if explicit and (available0 < 0 or available1 < 0): + raise ValueError("Fixed refunds exceed the quoted recovery and funding") + if liquidity_target is not None and not amount_mode: target = liquidity_target required = required_for(target) else: - assert max_funding0 is not None and max_funding1 is not None - target = liquidity_for_amounts(sqrt_price, sqrt_lo, sqrt_hi, - recovered0 + max_funding0, recovered1 + max_funding1) - # The solve floors and the deposit ceils, so the first target can - # exceed the budget by a rounding unit; step down until it fits. + if amount_mode: + assert amount0_desired is not None and amount1_desired is not None + budget0, budget1 = min(available0, amount0_desired), min(available1, amount1_desired) + else: + assert max_funding0 is not None and max_funding1 is not None + budget0, budget1 = recovered0 + max_funding0, recovered1 + max_funding1 + target = liquidity_for_amounts(sqrt_price, sqrt_lo, sqrt_hi, budget0, budget1) for _ in range(BUDGET_CLAMP_RETRIES + 1): if target <= 0: + if amount_mode: + raise ValueError("The token caps and available funds support no liquidity in this range " + "— increase amount0_desired/amount1_desired or funded0/funded1, " + "reduce fixed refunds, or change the range") raise ValueError("The funding budget supports no liquidity in this " "range — raise it or narrow the range") required = required_for(target) - if (required[0] <= recovered0 + max_funding0 - and required[1] <= recovered1 + max_funding1): + if required[0] <= budget0 and required[1] <= budget1: break target -= 1 else: - raise ValueError("Budget sizing did not converge — pass an explicit " - "liquidity_target") + if amount_mode: + raise ValueError("Token-cap sizing did not converge — adjust amount0_desired/amount1_desired " + "or fixed funding/refunds, or change the range") + raise ValueError("Budget sizing did not converge — pass an explicit liquidity_target") - funded0 = max(required[0] - recovered0, 0) - funded1 = max(required[1] - recovered1, 0) - refund0 = max(recovered0 - required[0], 0) - refund1 = max(recovered1 - required[1], 0) + min0 = amount0_min if amount0_min is not None else amount0_desired + min1 = amount1_min if amount1_min is not None else amount1_desired + flexible = amount_mode or (explicit and ( + (min0 is not None and amount0_desired is not None and min0 < amount0_desired) or + (min1 is not None and amount1_desired is not None and min1 < amount1_desired))) + funded0 = funded0 if funded0 is not None else (0 if flexible else max(required[0] - recovered0, 0)) + funded1 = funded1 if funded1 is not None else (0 if flexible else max(required[1] - recovered1, 0)) + refund0 = refund0 if refund0 is not None else (0 if flexible else max(recovered0 - required[0], 0)) + refund1 = refund1 if refund1 is not None else (0 if flexible else max(recovered1 - required[1], 0)) + if flexible: + for i, (cap, minimum, recovered, funded, refund) in enumerate(zip( + (amount0_desired, amount1_desired), (min0, min1), + (recovered0, recovered1), (funded0, funded1), (refund0, refund1))): + assert cap is not None and minimum is not None + if required[i] > cap: + raise ValueError(f"Quoted token{i} deposit {required[i]} exceeds amount{i}_desired={cap}") + if required[i] < minimum: + raise ValueError(f"Quoted token{i} deposit {required[i]} is below amount{i}_min={minimum}") + if required[i] > recovered + funded - refund: + if refund: + raise ValueError(f"Quoted token{i} deposit exceeds available funds after refund{i}={refund}; " + "reduce the refund or target, or remove the refund and supply " + f"funded{i}={max(required[i] - recovered, 0)} or more") + raise ValueError(f"Quoted token{i} deposit exceeds available funds; " + f"supply funded{i}={required[i] - recovered} or more") route = rebalance_route(wrapped0, wrapped1, funded0 > 0, funded1 > 0) - return RebalancePlan( + plan = RebalancePlan( pool_key=pool_key, position_token_id=position_token_id, tick_lower=lo, tick_upper=hi, old_liquidity=old_liquidity, fees_accrued0=fees0, fees_accrued1=fees1, recovered0=recovered0, recovered1=recovered1, required0=required[0], required1=required[1], funded0=funded0, funded1=funded1, refund0=refund0, refund1=refund1, - liquidity_target=target, function_name=route.function, + liquidity_target=0 if amount_mode else target, function_name=route.function, + amount0_desired=amount0_desired, amount1_desired=amount1_desired, + amount0_min=min0, amount1_min=min1, + estimated_liquidity=target if amount_mode else None, ) + _validate_amounts(asdict(plan)) + return plan + + +def plan_rebalance_exact_amounts(**kwargs: Any) -> RebalancePlan: + """Plan exact quoted recovery and deposits; price or fee changes can reject execution. + + Accepts the state and constraints of :func:`plan_rebalance`. + No network reads, signing, or submission occurs. + """ + return plan_rebalance(**_mode_parameters("exact_amounts", kwargs)) + + +def plan_rebalance_to_liquidity(**kwargs: Any) -> RebalancePlan: + """Plan exact successor liquidity using actual recovery and bounded token consumption. + + Accepts the state and constraints of :func:`plan_rebalance`. + No network reads, signing, or submission occurs. + """ + return plan_rebalance(**_mode_parameters("to_liquidity", kwargs)) + + +def plan_rebalance_from_amounts(**kwargs: Any) -> RebalancePlan: + """Estimate successor liquidity from token caps; the contract sizes it at execution. + + Accepts the state and constraints of :func:`plan_rebalance`. + No network reads, signing, or submission occurs. + """ + return plan_rebalance(**_mode_parameters("from_amounts", kwargs)) diff --git a/shield-swap-sdk/tests/test_agent.py b/shield-swap-sdk/tests/test_agent.py index c4ae81f7..7ab76915 100644 --- a/shield-swap-sdk/tests/test_agent.py +++ b/shield-swap-sdk/tests/test_agent.py @@ -9,6 +9,8 @@ CURATED = {"setup_account", "redeem_referral_code", "request_airdrop", "status", "get_swap_execution", "plan_rebalance", "rebalance_position", + "plan_rebalance_exact_amounts", "plan_rebalance_to_liquidity", "plan_rebalance_from_amounts", + "rebalance_position_exact_amounts", "rebalance_position_to_liquidity", "rebalance_position_from_amounts", "get_pools", "get_balances", "get_positions", "swap_many", "mint_position", "adjust_liquidity", "collect_all"} diff --git a/shield-swap-sdk/tests/test_async_parity.py b/shield-swap-sdk/tests/test_async_parity.py index dc37d102..e65d75df 100644 --- a/shield-swap-sdk/tests/test_async_parity.py +++ b/shield-swap-sdk/tests/test_async_parity.py @@ -16,7 +16,9 @@ "swap_many", "collect_all", # require a journal "create_pool", "mint", "increase_liquidity", # LP surface "decrease_liquidity", "collect", "burn", - "rebalance_position", + "rebalance_position", # shared sync LP executor + "rebalance_position_exact_amounts", "rebalance_position_to_liquidity", + "rebalance_position_from_amounts", "get_positions", "find_tick_predecessor", } diff --git a/shield-swap-sdk/tests/test_flexible_rebalance.py b/shield-swap-sdk/tests/test_flexible_rebalance.py new file mode 100644 index 00000000..f49fde17 --- /dev/null +++ b/shield-swap-sdk/tests/test_flexible_rebalance.py @@ -0,0 +1,354 @@ +"""Flexible rebalance constraints, planning and submitted request regression tests.""" +from dataclasses import replace + +import pytest + +from aleo_shield_swap import _generated as g +from aleo_shield_swap.client import ShieldSwap +from aleo_shield_swap.rebalance import plan_rebalance +from .test_rebalance import _state, _stub, POOL, POSITION_ID, OLD_LOWER, OLD_UPPER, TOKEN_RECORD + +COMMON = dict(pool_key=POOL, position_token_id=POSITION_ID, + tick_lower=OLD_LOWER, tick_upper=OLD_UPPER) + + +def test_zero_target_survives_equal_bounds(): + p = plan_rebalance(**_state(), liquidity_target=0, amount0_desired=10_000, amount1_desired=10_000) + assert p.liquidity_target == 0 and p.estimated_liquidity > 0 + assert p.required0 <= 10_000 and p.required1 <= 10_000 + assert p.amount0_min == p.amount1_min == 10_000 + assert (p.funded0, p.funded1, p.refund0, p.refund1) == (0, 0, 0, 0) + + +def test_amount_budgets_include_fixed_transfers(): + p = plan_rebalance(**_state(), liquidity_target=0, amount0_desired=1_000_000, + amount1_desired=1_000_000, amount0_min=0, amount1_min=0, + funded0=123, refund1=456) + assert (p.funded0, p.funded1, p.refund0, p.refund1) == (123, 0, 0, 456) + assert p.required0 <= p.recovered0 + 123 and p.required1 <= p.recovered1 - 456 + assert p.function_name == "rebalance_plain_plain_one" + + +def test_one_sided_amount_budget(): + p = plan_rebalance(**_state(tick_lower=600, tick_upper=1200), liquidity_target=0, + amount0_desired=5_000, amount1_desired=0, amount0_min=0, amount1_min=0) + assert p.estimated_liquidity > 0 + assert 0 < p.required0 <= 5_000 and p.required1 == 0 + assert p.function_name == "rebalance_plain_plain_none" + + +def test_explicit_exact_bounds_derive_quote_transfers(): + exact = plan_rebalance(**_state(), liquidity_target=500_000) + p = plan_rebalance(**_state(), liquidity_target=500_000, + amount0_desired=exact.required0, amount1_desired=exact.required1) + assert (p.refund0, p.refund1) == (exact.refund0, exact.refund1) + assert p.funded0 == p.funded1 == 0 + + +@pytest.mark.parametrize("overrides, message", [ + ({"amount0_desired": -1}, "u128"), + ({"amount0_desired": 1 << 128}, "u128"), + ({"funded0": True}, "u128"), + ({"amount0_min": 10_001}, "minimum"), + ({"funded0": 1, "refund0": 1}, "funding.*refund"), + ({"refund0": 1_000_000}, "refunds exceed"), + ({"amount1_desired": None}, "together"), +]) +def test_invalid_constraints(overrides, message): + args = dict(liquidity_target=0, amount0_desired=10_000, amount1_desired=10_000, + amount0_min=0, amount1_min=0) + args.update(overrides) + with pytest.raises(ValueError, match=message): + plan_rebalance(**_state(), **args) + + +@pytest.mark.parametrize("args, message", [ + ({"liquidity_target": 0}, "zero.*requires"), + ({"liquidity_target": 1, "funded0": 1}, "explicit token bounds"), + ({"max_funding0": 0, "max_funding1": 0, + "amount0_desired": 10, "amount1_desired": 10}, "budgets cannot be combined with explicit token bounds"), + ({"liquidity_target": 1, "amount0_min": 0}, "minimums require"), + ({"liquidity_target": 500_000, "amount0_desired": 1, "amount1_desired": 1}, "quoted deposit"), +]) +def test_ambiguous_bounds(args, message): + with pytest.raises(ValueError, match=message): + plan_rebalance(**_state(), **args) + + +def test_helpers_preserve_modes_and_prebuilt_bounds(): + dex = ShieldSwap(_stub()) + exact = dex.plan_rebalance_exact_amounts(**COMMON, liquidity_target=500_000) + dex.rebalance_position_exact_amounts(plan=exact) + with pytest.raises(ValueError, match="positive"): + dex.plan_rebalance_exact_amounts(**COMMON, liquidity_target=0) + p = dex.plan_rebalance_to_liquidity(**COMMON, liquidity_target=500_000, + amount0_desired=150_000, amount1_desired=160_000, + amount0_min=90_000, amount1_min=80_000, funded0=123, refund1=456) + result = dex.rebalance_position_to_liquidity(plan=p, token0_record=TOKEN_RECORD).transact() + req = next(g.CoreRebalanceRequest.from_plaintext(x) for x in dex._aleo.last_call[1] + if x.startswith("{ old_liquidity:")) + assert req.liquidity_target == 500_000 + assert (req.mint.amount0_desired, req.mint.amount1_desired) == (150_000, 160_000) + assert (req.mint.amount0_min, req.mint.amount1_min) == (90_000, 80_000) + assert req.funded0 == 123 and req.refund1 == 456 and result.plan == p + with pytest.raises(ValueError, match="equal"): + dex.rebalance_position_exact_amounts(plan=p) + with pytest.raises(ValueError, match="wider"): + dex.rebalance_position_to_liquidity(plan=replace(exact, amount0_desired=exact.required0, + amount1_desired=exact.required1)) + p = dex.plan_rebalance_from_amounts(**COMMON, amount0_desired=10_000, amount1_desired=10_000) + assert p.amount0_min == p.amount1_min == 0 + dex.rebalance_position_from_amounts(plan=p).transact() + req = g.CoreRebalanceRequest.from_plaintext(dex._aleo.last_call[1][2]) + assert req.liquidity_target == 0 + assert req.mint.amount0_desired == 10_000 and req.mint.amount0_min == 0 + with pytest.raises(ValueError, match="zero"): + dex.plan_rebalance_from_amounts(**COMMON, liquidity_target=1, + amount0_desired=10_000, amount1_desired=10_000) + with pytest.raises(ValueError, match="fixed funding"): + dex.plan_rebalance_from_amounts(**COMMON, max_funding0=0, max_funding1=0, + amount0_desired=10_000, amount1_desired=10_000) + + +def test_prebuilt_plan_rejects_overrides_and_bad_accounting(): + p = plan_rebalance(**_state(), liquidity_target=500_000) + dex = ShieldSwap(_stub()) + with pytest.raises(ValueError, match="plan.*overrid"): + dex.rebalance_position(plan=p, liquidity_target=1) + with pytest.raises(ValueError, match="recovery.*funding"): + dex.rebalance_position(plan=replace(p, refund0=p.refund0 + 1)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode, constraints", [ + ("exact_amounts", {"liquidity_target": 500_000}), + ("to_liquidity", {"liquidity_target": 500_000, "amount0_desired": 150_000, "amount1_desired": 160_000}), + ("from_amounts", {"amount0_desired": 10_000, "amount1_desired": 10_000}), +]) +async def test_async_and_exported_planners_match_sync(mode, constraints): + import aleo_shield_swap as sdk + from .test_async_client import AsyncStubAleo + stub = _stub() + sync = getattr(ShieldSwap(stub), f"plan_rebalance_{mode}")(**COMMON, **constraints) + async_dex = sdk.AsyncShieldSwap(AsyncStubAleo(mappings=stub.programs._mappings)) + planned = await getattr(async_dex, f"plan_rebalance_{mode}")(**COMMON, **constraints) + assert planned == sync + assert getattr(sdk, f"plan_rebalance_{mode}")(**_state(), **constraints) == sync + + +@pytest.mark.parametrize("mode, constraints", [ + ("exact_amounts", {"liquidity_target": "500000"}), + ("to_liquidity", {"liquidity_target": "500000", "amount0_desired": "150000", "amount1_desired": "160000"}), + ("from_amounts", {"amount0_desired": str((1 << 100) + 123), "amount1_desired": "10000"}), + ("", {"liquidity_target": "0", "amount0_desired": "10000", "amount1_desired": "10000", "amount0_min": "0", "amount1_min": "0"}), +]) +def test_agent_modes_preserve_constraints_and_integer_precision(mode, constraints): + from aleo_shield_swap.agent import dispatch_tool, shield_swap_tools + suffix = f"_{mode}" if mode else "" + tools = {t["name"]: t for t in shield_swap_tools()} + plan_name, execute_name = "plan_rebalance" + suffix, "rebalance_position" + suffix + assert plan_name in tools and execute_name in tools + assert set(constraints) <= tools[plan_name]["input_schema"]["properties"].keys() + dex = ShieldSwap(_stub()) + args = {**COMMON, **constraints} + planned = dispatch_tool(dex, plan_name, args) + result = dispatch_tool(dex, execute_name, args) + assert result["position_token_id"] == "77field" + assert result["plan"] == planned + if mode == "from_amounts": + assert planned["amount0_desired"] == str((1 << 100) + 123) + assert planned["liquidity_target"] == "0" + assert isinstance(planned["estimated_liquidity"], str) + if mode == "to_liquidity": + assert planned["amount0_min"] == "0" and planned["refund0"] == "0" + + +@pytest.mark.parametrize("mode", ["from_amounts", "to_liquidity"]) +def test_bounded_helpers_reject_invalid_values_before_chain_reads(mode): + dex = ShieldSwap(_stub()) + with pytest.raises(ValueError, match="u128"): + getattr(dex, f"plan_rebalance_{mode}")(**COMMON, liquidity_target=0 if mode == "from_amounts" else 1, + amount0_desired=True, amount1_desired=10_000) + + +@pytest.mark.asyncio +async def test_mcp_exposes_and_executes_amount_planner(): + import json + pytest.importorskip("mcp") + from aleo_shield_swap.mcp import tool_definitions, call_tool + tools = {tool.name: tool for tool in tool_definitions()} + assert "amount0_desired" in tools["plan_rebalance_from_amounts"].inputSchema["required"] + result = await call_tool(ShieldSwap(_stub()), "plan_rebalance_from_amounts", + {**COMMON, "amount0_desired": "10000", "amount1_desired": "10000"}) + plan = json.loads(result[0].text) + assert plan["liquidity_target"] == "0" and int(plan["estimated_liquidity"]) > 0 + + +@pytest.mark.parametrize("value", [True, 1.5, "1.5"]) +def test_agent_rejects_amounts_that_would_be_coerced_or_truncated(value): + from aleo_shield_swap.agent import dispatch_tool + with pytest.raises(ValueError, match="integer|decimal"): + dispatch_tool(ShieldSwap(_stub()), "plan_rebalance_from_amounts", + {**COMMON, "amount0_desired": value, "amount1_desired": "10000"}) + + +@pytest.mark.parametrize("side", [0, 1]) +@pytest.mark.parametrize("constraint", ["cap", "minimum", "funding"]) +def test_flexible_target_rejects_infeasible_quote(side, constraint): + dex = ShieldSwap(_stub()) + args = dict(liquidity_target=500_000, amount0_desired=200_000, amount1_desired=200_000) + if constraint == "cap": + args[f"amount{side}_desired"] = 1 + message = f"amount{side}_desired" + elif constraint == "minimum": + args[f"amount{side}_min"] = 199_999 + message = f"amount{side}_min" + else: + args.update(liquidity_target=2_000_000, amount0_desired=1_000_000, amount1_desired=1_000_000) + args[f"funded{1 - side}"] = 1_000_000 + message = f"funded{side}" + with pytest.raises(ValueError, match=message): + dex.plan_rebalance_to_liquidity(**COMMON, **args) + + +def test_flexible_target_funding_suggestion_is_sufficient(): + import re + dex = ShieldSwap(_stub()) + args = dict(liquidity_target=2_000_000, amount0_desired=1_000_000, + amount1_desired=1_000_000, funded1=1_000_000) + with pytest.raises(ValueError, match=r"funded0=(\d+)") as exc: + dex.plan_rebalance_to_liquidity(**COMMON, **args) + funded0 = int(re.search(r"funded0=(\d+)", str(exc.value)).group(1)) + plan = dex.plan_rebalance_to_liquidity(**COMMON, funded0=funded0, **args) + assert plan.recovered0 + plan.funded0 == plan.required0 + assert plan.function_name == "rebalance_plain_plain_both" + + +@pytest.mark.parametrize("mode", ["", "_exact_amounts", "_to_liquidity", "_from_amounts"]) +def test_prebuilt_plan_accepts_matching_identity_arguments(mode): + dex = ShieldSwap(_stub()) + constraints = (dict(liquidity_target=500_000) if mode in ("", "_exact_amounts") + else dict(amount0_desired=150_000, amount1_desired=160_000)) + if mode == "_to_liquidity": + constraints["liquidity_target"] = 500_000 + plan = getattr(dex, "plan_rebalance" + mode)(**COMMON, **constraints) + result = getattr(dex, "rebalance_position" + mode)(plan=plan, **COMMON).transact() + assert result.plan == plan + + +@pytest.mark.parametrize("key,value", [("pool_key", "6field"), + ("position_token_id", "43field"), ("tick_lower", -4200), ("tick_upper", 4200)]) +def test_prebuilt_plan_rejects_conflicting_identity_arguments(key, value): + dex = ShieldSwap(_stub()) + plan = dex.plan_rebalance(**COMMON, liquidity_target=500_000) + with pytest.raises(ValueError, match=key): + dex.rebalance_position(plan=plan, **{key: value}) + + +class IntAmount(int): + pass + + +class IndexAmount: + def __init__(self, value): + self.value = value + + def __index__(self): + return self.value + + +@pytest.mark.parametrize("amount_type", [IntAmount, IndexAmount]) +def test_planner_normalizes_integer_protocol_inputs(amount_type): + dex = ShieldSwap(_stub()) + plan = dex.plan_rebalance_to_liquidity(**COMMON, + liquidity_target=amount_type(500_000), amount0_desired=amount_type(150_000), + amount1_desired=amount_type(160_000), funded0=amount_type(123)) + assert plan.liquidity_target == 500_000 and type(plan.liquidity_target) is int + assert plan.amount0_desired == 150_000 and type(plan.amount0_desired) is int + assert plan.funded0 == 123 and type(plan.funded0) is int + quoted = dex.plan_rebalance(**COMMON, max_funding0=amount_type(0), max_funding1=amount_type(0)) + assert quoted.liquidity_target > 0 and type(quoted.liquidity_target) is int + + +@pytest.mark.parametrize("amount_type", [IntAmount, IndexAmount]) +def test_prebuilt_plan_normalizes_integer_protocol_inputs(amount_type): + dex = ShieldSwap(_stub()) + plan = dex.plan_rebalance(**COMMON, liquidity_target=500_000) + external = replace(plan, liquidity_target=amount_type(plan.liquidity_target), + required0=amount_type(plan.required0), refund0=amount_type(plan.refund0)) + result = dex.rebalance_position_exact_amounts(plan=external).transact() + assert result.plan == plan + assert type(result.plan.liquidity_target) is int + + +@pytest.mark.parametrize("mode", ["to_liquidity", "from_amounts"]) +@pytest.mark.parametrize("value", ["500000", False, 0.0, True, 1.5]) +def test_named_planner_rejects_invalid_target_types(mode, value): + dex = ShieldSwap(_stub()) + with pytest.raises(ValueError, match="u128"): + getattr(dex, f"plan_rebalance_{mode}")(**COMMON, liquidity_target=value, + amount0_desired=150_000, amount1_desired=160_000) + + +@pytest.mark.asyncio +async def test_async_planner_rejects_infeasible_quote(): + from aleo_shield_swap import AsyncShieldSwap + from .test_async_client import AsyncStubAleo + dex = AsyncShieldSwap(AsyncStubAleo(mappings=_stub().programs._mappings)) + with pytest.raises(ValueError, match="amount0_desired"): + await dex.plan_rebalance_to_liquidity(**COMMON, liquidity_target=500_000, + amount0_desired=1, amount1_desired=200_000) + + +@pytest.mark.parametrize("side", [0, 1]) +@pytest.mark.parametrize("method", ["plan_rebalance", "plan_rebalance_from_amounts"]) +def test_amount_driven_rejects_unreachable_minimum(side, method): + dex = ShieldSwap(_stub()) + args = dict(liquidity_target=0, amount0_desired=5_000, amount1_desired=5_000, + amount0_min=0, amount1_min=0) + args[f"amount{side}_desired"] = 10_000 + args[f"amount{side}_min"] = 9_000 + with pytest.raises(ValueError, match=f"below amount{side}_min=9000"): + getattr(dex, method)(**COMMON, **args) + + +def test_generic_amount_mode_checks_its_default_exact_minimums(): + with pytest.raises(ValueError, match="below amount0_min=10000"): + plan_rebalance(**_state(), liquidity_target=0, + amount0_desired=10_000, amount1_desired=5_000) + + +@pytest.mark.asyncio +async def test_async_amount_planner_rejects_unreachable_minimum(): + from aleo_shield_swap import AsyncShieldSwap + from .test_async_client import AsyncStubAleo + dex = AsyncShieldSwap(AsyncStubAleo(mappings=_stub().programs._mappings)) + with pytest.raises(ValueError, match="below amount0_min=9000"): + await dex.plan_rebalance_from_amounts(**COMMON, amount0_desired=10_000, + amount1_desired=5_000, amount0_min=9_000) + + +@pytest.mark.parametrize("mode", ["", "_exact_amounts", "_to_liquidity", "_from_amounts"]) +def test_prebuilt_plan_accepts_original_unaligned_ticks(mode): + dex = ShieldSwap(_stub()) + original = dict(COMMON, tick_lower=-4100, tick_upper=4100) + constraints = (dict(liquidity_target=500_000) if mode in ("", "_exact_amounts") + else dict(amount0_desired=150_000, amount1_desired=160_000)) + if mode == "_to_liquidity": + constraints["liquidity_target"] = 500_000 + plan = getattr(dex, "plan_rebalance" + mode)(**original, **constraints) + assert (plan.tick_lower, plan.tick_upper) == (-4140, 4080) + result = getattr(dex, "rebalance_position" + mode)(plan=plan, **original).transact() + req = next(g.CoreRebalanceRequest.from_plaintext(x) for x in dex._aleo.last_call[1] + if x.startswith("{ old_liquidity:")) + assert (req.mint.tick_lower, req.mint.tick_upper) == (-4140, 4080) + assert result.plan == plan + + +@pytest.mark.parametrize("method", ["plan_rebalance", "plan_rebalance_exact_amounts"]) +@pytest.mark.parametrize("target", [None, 0, 500_000]) +def test_budget_with_bounds_reports_the_conflicting_arguments(method, target): + dex = ShieldSwap(_stub()) + with pytest.raises(ValueError, match="budgets cannot be combined with explicit token bounds"): + getattr(dex, method)(**COMMON, liquidity_target=target, + max_funding0=0, max_funding1=0, amount0_desired=10, amount1_desired=10)