PancakeSwap 백서

PancakeSwap

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 52쪽

oolAddress() const [slot0, liquidity] = await Promise.all([ publicClient.readContract({ address: poolAddress, abi: pancakeV3PoolABI, functionName: 'slot0' }), publicClient.readContract({ address: poolAddress, abi: pancakeV3PoolABI, functionName: 'liquidity' }), ]) const pool = new Pool( token0, token1, FeeAmount.MEDIUM, slot0[0], // sqrtPriceX96 liquidity, slot0[1], // tick ) console.log('price token0→token1:', pool.token0Price.toSignificant(6)) console.log('current tick:', pool.tickCurrent) ``` **A position you own** — read it from the NonfungiblePositionManager by `tokenId`: ```tsx const p = await publicClient.readContract({ address: NFPM_ADDRESS, abi: nfpmABI, functionName: 'positions', args: [tokenId], }) // p.tickLower, p.tickUpper, p.liquidity, p.tokensOwed0, p.tokensOwed1, ... const inRange = pool.tickCurrent >= p.tickLower && pool.tickCurrent < p.tickUpper ``` **Is the position in range?** That single boolean is the trigger for a rebalancer. You can tighten it to "within N ticks of the boundary" to act *before* it goes out of range. *** ### 5. Safe transaction sequences This is the part to get exactly right. An unattended agent has no human to catch a bad transaction, so every state-changing call must be defended with the four guardrails below. #### 5.1 Approvals Before a contract can move your tokens it needs an allowance. The right mechanism depends on which contract you're calling — all three below are permissionless: * **ERC-20 `approve`** — works for both the Smart Router and the NonfungiblePositionManager, with any token. One tx per token/spender. Simplest, but a standing infinite approval is a standing risk. * **`selfPermit` (EIP-2612)** — for **NonfungiblePositionManager** liquidity ops. If the token supports EIP-2612, the SDK can bundle a signed, amount-scoped permit *inline* with `mint`/`increaseLiquidity` via multicall — no separate approve tx. Falls back to `approve` for tokens without EIP-2612. * **Permit2** — for **Smart Router** swaps. Approve Permit2 once per token, then grant short-lived, signed, amount-scoped allowances per swap. For an autonomous agent: scope every permit to the exact amount and a short expiry. **Never grant an unbounded approval from an agent wallet that holds meaningful balances.** #### 5.2 Slippage — never send `amountMin = 0` Every add/remove/swap must specify a minimum acceptable output. Let the SDK derive it from a tolerance instead of hand-rolling it: ```tsx import { Percent, Position } from '@pancakeswap/v3-sdk' const slippage = new Percent(50, 10_000) // 0.50% // when minting / adding: const { amount0: amount0Min, amount1: amount1Min } = position.mintAmountsWithSlippage(slippage) // when removing: const { amount0: amount0Min, amount1: amount1Min } = position.burnAmountsWithSlippage(slippage) ``` For swaps, the Smart Router applies `slippageTolerance` and computes `amountOutMinimum` for you (§6, step 0). **A zero minimum is an open invitation to sandwich bots** — on an unattended wallet that can mean repeated, silent losses. #### 5.3 Deadlines — always set one Every call takes a `deadline` (unix seconds). If the tx is still pending at that time it reverts instead of executing at a stale price. Keep it short for an agent: ```tsx const deadline = BigInt(Math.floor(Date.now() / 1000) + 60 * 5) // 5 minutes ``` #### 5.4 Multicall — make multi-step actions atomic The NonfungiblePositionManager and Smart Router support `multicall`: several calls bundled into **one transaction** that all succeed or all revert. This is not just gas savings — it's a safety property. A rebalance that does `decreaseLiquidity` then `collect` must never half-execute. The SDK bundles for you: ```tsx import { Multicall } from '@pancakeswap/v3-sdk' const calldata = Multicall.encodeMulticall([decreaseCalldata, collectCalldata, burnCalldata]) ``` > **There is no atomic "rebalance" function.** Moving a range is a *composed* sequence (remove → collect → mint). Removal and the new mint happen in separate transactions; the price can move between them. Re-read state and recompute minimums for the mint after the removal confirms — don't reuse pre-removal numbers. #### Guardrail checklist (apply to every agent action) * \[ ] Token allowance scoped to the amount (Permit2), not infinite * \[ ] `amount*Min` / `amountOutMinimum` derived from an explicit slippage tolerance, never `0` * \[ ] Short `deadline` on every call * \[ ] Multi-step actions bundled via `multicall` * \[ ] State re-read between separate transactions of a sequence * \[ ] A per-run cap on value moved, and a sanity check that the pool price is within expected bounds before acting (cheap defense against acting into a manipulated/illiquid pool) *** ### 6. Worked example — automated V3 range rebalancer The reference agent. It watches one position; when price approaches the range boundary, it pulls liquidity out and re-mints a fresh range centered on the current price. Five steps. **Trigger:** `pool.tickCurrent` is within a buffer of `tickLower`/`tickUpper` (from §4). #### Step 0 — (optional) rebalance the token ratio After you withdraw, you'll hold token0 and token1 in whatever ratio the old range produced. A new, recentered range usually needs a different ratio, so swap the excess via the Smart Router: ```tsx import { SmartRouter, SwapRouter } from '@pancakeswap/smart-router' import { TradeType } from '@pancakeswap/swap-sdk-core' const quoteProvider = SmartRouter.createQuoteProvider({ onChainProvider: () => publicClient }) const trade = await SmartRouter.getBestTrade(amountIn, tokenOut, TradeType.EXACT_INPUT, { gasPriceWei: () => publicClient.getGasPrice(), maxHops: 2, poolProvider: SmartRouter.createStaticPoolProvider(candidatePools), quoteProvider, }) const { calldata, value } = SwapRouter.swapCallParameters(trade, { slippageTolerance: new Percent(50, 10_000), deadlineOrPreviousBlockhash: deadline, recipient: account.address, }) await walletClient.sendTransaction({ to: SMART_ROUTER_ADDRESS, data: calldata, value: BigInt(value) }) ``` #### Step 1–3 — remove liquidity, collect, burn (one transaction) `removeCallParameters` builds the whole bundle: it `decreaseLiquidity` to zero, `collect`s both the withdrawn principal and accrued fees, and `burn`s the now-empty NFT — as a single atomic `multicall`. ```tsx import { NonfungiblePositionManager, Percent } from '@pancakeswap/v3-sdk' const { calldata, value } = NonfungiblePositionManager.removeCallParameters(oldPosition, { tokenId, liquidityPercentage: new Percent(1), // 100% — full exit slippageTolerance: new Percent(50, 10_000), // 0.50% — sets amount0Min/amount1Min deadline, collectOptions: { expectedCurrencyOwed0: feesOwed0, expectedCurrencyOwed1: feesOwed1, recipient: account.address, }, }) const hash = await walletClient.sendTransaction({ to: NFPM_ADDRESS, data: calldata, value: BigInt(value) }) await publicClient.waitForTransactionReceipt({ hash }) // wait — the next mint depends on these tokens ``` > If the position is **staked in MasterChefV3**, you don't remove from the NFPM. Call `MasterChefV3.withdraw(tokenId, to)` first to unstake (this also harvests pending CAKE), which returns the NFT to your wallet — then run the removal above. See §7. #### Step 4 — mint the new range Recompute ticks around the *current* price (re-read the pool — see §5.4), snap them to the fee tier's spacing, build a `Position` from the tokens you now hold, and mint. ```tsx import { Position, NonfungiblePositionManager, nearestUsableTick } from '@pancakeswap/v3-sdk' const freshPool = /* re-read slot0 + liquidity → new Pool (§4) */ const spacing = freshPool.tickSpacing const halfWidth = 10 * spacing // strategy-defined range width const tickLower = nearestUsableTick(freshPool.tickCurrent - halfWidth, spacing) const tickUpper = nearestUsableTick(freshPool.tickCurrent + halfWidth, spacing) const newPosition = Position.fromAmounts({ pool: freshPool, tickLower, tickUpper, amount0: balance0, amount1: balance1, useFullPrecision: true, }) const { calldata, value } = NonfungiblePositionManager.addCallParameters(newPosition, { slippageTolerance: new Percent(50, 10_000), // sets amount0Min/amount1Min for the mint deadline, recipient: account.address, }) await walletClient.sendTransaction({ to: NFPM_ADDRESS, data: calldata, value: BigInt(value) }) ``` The agent now holds a fresh in-range NFT. If it was farming, re-stake it (§7). Loop back to the §4 read on the next tick. *** ### 7. Farm interactions (MasterChefV3) Staking a V3 position NFT in MasterChefV3 earns CAKE on top of swap fees. > **Only positions from pools with an active farm earn CAKE.** PancakeSwap governance registers which pools are farmable (each gets a `pid`). Staking a position whose pool isn't registered reverts with `InvalidPid`. This is the one place agent activity depends on a PancakeSwap-side list — and it's pool-level, not agent-level: any wallet can stake into any active farm. (Managing a position via the NonfungiblePositionManager — mint/collect/rebalance — needs no farm and works for every pool.) > **Only positions from pools with an active farm earn CAKE.** PancakeSwap governance registers which pools are farmable (each gets a `pid`). Staking a position whose pool isn't registered reverts with `InvalidPid`. This is the *one* place agent activity depends on a PancakeSwap-side list — and it's pool-level, not agent-level: any wallet can stake into any *active* farm. Check the pool has a live farm before building a farming strategy around it. (Managing a position via the NonfungiblePositionManager — mint/collect/rebalance — needs no farm and works for every pool.) * **Stake** — transfer the position NFT to MasterChefV3 (`safeTransferFrom(owner, masterChefV3, tokenId)`). The farm now custodies the NFT. * **Harvest** — `harvest(tokenId, to)` claims pending CAKE without unstaking. Use `batchHarvest` to claim across several positions in one tx. * **Withdraw / exit** — `withdraw(tokenId, to)` unstakes, harvests pending CAKE, and returns the NFT to your wallet. You must withdraw before you can `decreaseLiquidity`/`burn` (the NFPM calls in §6 only work on an NFT your wallet holds). A rebalancer for a **farmed** position therefore runs: `withdraw` → remove/collect/burn → mint → `safeTransferFrom` back into MasterChefV3. *** ### 8. Safety, limits & disclaimers Read this before deploying an agent that moves real funds. * **Autonomy is irreversible.** A deployed agent signs and sends transactions with no human confirmation. A bug, a bad trigger, or a manipulated price feed executes for real. Test on BSC testnet, then cap mainnet exposure (per-trade and per-day limits) before scaling. * **Slippage and deadlines are mandatory**, not optional (§5). An agent that omits them will eventually be sandwiched. * **Price-manipulation defense.** Before acting, sanity-check the pool price against an independent reference and skip the run if they diverge — cheap insurance against trading into a manipulated or thin pool. * **Gas and funding.** Keep the agent wallet funded with BNB for gas; a starved agent can leave a position mid-rebalance (removed but not re-minted). Re-reading state on each run (§4) lets it recover on the next tick. * **Scaled-UI / RWA tokens.** Some BSC tokens (e.g. Binance Stock Tokens) use on-chain UI multipliers (ERC-8056). On-chain raw amounts differ from displayed amounts. If your agent trades these, do all contract math in raw units and only apply the multiplier for human-facing display. * **You are responsible for your agent.** PancakeSwap pools are permissionless contracts; deploying an autonomous agent against them is your decision and your risk. This guide is technical reference, not financial advice, and PancakeSwap makes no warranty as to outcomes. *** ### 9. Reference * **`@pancakeswap/smart-router`** — routing + swap calldata (best in-repo examples are in its README) * **`@pancakeswap/v3-sdk`** — `Pool`, `Position`, `NonfungiblePositionManager`, `Multicall`, tick/price math * **BNB Agent Studio** — describing, building, and deploying the agent (BNB docs) * **PancakeSwap deployment addresses** — canonical contract list (verify before use) * **ERC-8056 (Scaled UI Amount)** — <https://github.com/bnb-chain/BEPs/pull/677> # Reference Agent — Order/Intents Settlement Agent > An ERC-8183 Provider agent that fulfills a single swap-intent Job at a time by routing it through PancakeSwap aggregation and delivering the target token directly to the Client. ### 0. How it maps to ERC-8183 ERC-8183 (Agentic Commerce; Virtuals + Ethereum Foundation) defines a **Job** with three roles and states Open → Funded → Submitted → Terminal. BNB's **BNBAgent SDK** is the live implementation. | Role | In this agent | | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | **Client** (Agent-A) | posts a swap intent: "swap X of token A → token B, deliver me ≥ `minOut`", escrows the input + a tip | | **Provider** (Agent-B) — **this is our reference agent** | quotes via **PancakeSwap aggregation**, and if it can meet/beat `minOut`, executes the swap and delivers token B to the Client | | **Evaluator** | verifies the Client received token-B amount ≥ `minOut`; releases the tip (or refunds the Client) | The deliverable is objective ("did the Client receive ≥ `minOut`?"), which is exactly why this fits ERC-8183 where the rebalancer didn't. *** ### 1. Purpose & one-line scope > A **Provider** agent that fulfills a single swap-intent Job at a time by routing it through PancakeSwap aggregation and delivering the target token directly to the Client — and nothing else. *** ### 2. What the agent is ALLOWED to do (capability allowlist) | # | Capability | Surface | Notes | | - | ---------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------- | | A | Discover open Jobs | BNBAgent SDK (ERC-8183 registry) | Read-only; filter to swap-intent Jobs it can serve | | B | Quote a route | **PancakeSwap aggregation** (Aggregator API / Smart Router) | Read-only; best price across V3 | | C | Accept a Job | BNBAgent SDK (Funded → committed) | Only if its fresh quote ≥ `minOut` and tip ≥ floor | | D | Execute the swap | PancakeSwap router | Input pulled from Job escrow; **output recipient = the Client**, in one tx | | E | Submit the deliverable | BNBAgent SDK (→ Submitted) | The settlement tx hash as proof | | F | Claim the tip | ERC-8183 escrow / x402 | Only after the Evaluator marks the Job Terminal | **Output of every settlement goes directly to the Client. The agent's only earning is the Job's tip.** *** ### 3. Hard guardrails (the gate to featuring) | Guardrail | Rule | | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Never accept what it can't fulfill** | Accept a Job only if a *fresh* quote clears `minOut`. If it can't, leave the Job Funded for another Provider. | | **Requote at execution** | Re-quote immediately before settling; abort if the route no longer clears `minOut` (no stale quotes). | | **Atomic settlement** | Pull-from-escrow → swap → deliver to Client in **one transaction**, output recipient = Client. The agent must never hold the Client's funds across a failed step. | | **Slippage** | Execution slippage bounded; delivered amount must still be ≥ `minOut` after slippage, or the tx reverts. Never `amountOutMin = 0`. | | **Deadline** | Short deadline on the settlement tx (≤ 5 min); respect the Job's own deadline. | | **Min tip / max value** | Don't accept Jobs below a tip floor or above a per-Job value cap. | | **Token safelist** | Only serve Jobs whose tokens are on the PancakeSwap token list (anti-honeypot / fake-token). | | **Single-Job concurrency (v1)** | Fulfill one Job at a time; no over-commitment. | | **Gas precondition** | Confirm enough BNB for the full settlement before accepting. | | **Idempotent** | Never double-submit or re-fulfill a Job already Submitted/Terminal. | If any rule can't be met, **skip the Job** — never force a settlement. *** ### 4. Out of scope — the agent MUST NOT 1. **Use Client funds for anything but the specified swap.** Output recipient is always the Client. 2. **Front its own inventory / take principal risk.** v1 is **escrow-pull only** — it routes the Client's escrowed input; it does not fill from its own balance. 3. **Route through non-PancakeSwap or unverified contracts**, or settle outside PancakeSwap aggregation. 4. **Serve Jobs with non-safelisted tokens**, or (v1) any scaled-UI / RWA token (§5). 5. **Use leverage, perps, margin, or lending.** 6. **Submit a deliverable it didn't actually fulfill** (no false attestation) or **evaluate its own Jobs** (conflict of interest). 7. **Call any owner/admin function** on PancakeSwap or the ERC-8183 contracts. 8. **Hold standing token approvals** beyond a single settlement; scope approvals to the Job amount. *** ### 5. PancakeSwap-specific logic (application correctness) * **Route via PancakeSwap aggregation**, not a single pool — best execution across V2 / V3 / Stable is the whole value proposition ("best price wins the tip"). * **Deliver atomically to the Client** by setting the router's `recipient` to the Client address; never a two-step "swap to self, then transfer." * **Quote freshness** — the on-chain price moves between discovery and settlement; requote at execution (guardrail §3). * **`minOut` is in raw units.** For **scaled-UI / ERC-8056 tokens** (Binance Stock Tokens / RWA equities) raw ≠ displayed; mishandling silently mis-delivers. **Exclude scaled-UI tokens from v1** until eng confirms raw-unit handling end-to-end. * **Slippage minimum** on the settlement swap must be derived so the *delivered* amount ≥ `minOut`, accounting for the tip/fee split. *** ### 6. Failure & recovery behavior * **Quote fails `minOut` at execution** → abort before/atomically with the escrow pull; the Job stays Funded for another Provider. No partial state. * **Already Submitted/Terminal** → skip (idempotent). * **Settlement tx reverts** → Job remains claimable by others; the agent records the failure and moves on. * **Repeated failures on a Job** → blacklist that Job locally and alert, rather than retry-looping. *** ### 7. Integration points (the BNB / ERC-8183 half) These are provided by BNB Agent Studio / BNBAgent SDK, not built by PancakeSwap — but the spec depends on them: * **Job lifecycle** (discover Open → accept Funded → Submitted → claim) via BNBAgent SDK. * **Provider identity** via ERC-8004. * **Escrow + payout** via the ERC-8183 escrow / x402. * **Evaluator** — the predicate must be "Client's token-B balance increased by ≥ `minOut`." Confirm with BNB **who runs the Evaluator** (neutral/protocol vs. Client) and that the predicate is enforceable on-chain. *** ### 8. Recommended v1 posture & open decisions 1. **Escrow-pull only, single Job at a time, token-safelist only, no scaled-UI tokens.** Smallest safe surface to feature at launch. 2. **Confirm the PancakeSwap swap interface** — the **Aggregator (`aggr`) HTTP API** vs the **Smart Router SDK**. Jerry's note says "use pcs aggr api"; needs confirming which the agent calls, as it changes the integration (and whether the guide needs an aggregation section). 3. **Confirm the escrow mechanic** with BNB — can the Provider pull the Client's escrowed input to route the swap, and is delivery-to-Client enforceable as the deliverable? 4. **Confirm the Evaluator owner and predicate** (§7). > Eng sign-off before featuring: atomic escrow-pull → swap → deliver-to-Client routing; requote-at-execution; `minOut`-after-slippage math; safelist enforcement; i
프로젝트로 돌아가기