### Quick Start Example Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/swap-sdk-core.md Demonstrates basic usage of Token, CurrencyAmount, Percent, Fraction, and Price for swap calculations. Ensure necessary imports are included. ```typescript import { Token, CurrencyAmount, Price, Percent, Fraction } from '@pancakeswap/swap-sdk-core' import { ChainId } from '@pancakeswap/chains' const USDC = new Token(ChainId.ETHEREUM, '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 6, 'USDC', 'USD Coin') const DAI = new Token(ChainId.ETHEREUM, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18, 'DAI', 'Dai') const oneUSDC = CurrencyAmount.fromRawAmount(USDC, 1_000_000n) // 1 USDC (6 decimals) const slippage = new Percent(50, 10_000) // 0.5% const minOut = oneUSDC.multiply(new Fraction(1).subtract(slippage)) const price = new Price(USDC, DAI, 1_000_000n, 10n ** 18n) console.log(price.toSignificant(6)) // "1.00000" ``` -------------------------------- ### Quick Start: V3 SDK Usage Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/v3-sdk.md A quick start example demonstrating how to import necessary classes, construct a Pool and a Position, and generate add-liquidity calldata using the V3 SDK. ```typescript import { Pool, Position, NonfungiblePositionManager, FeeAmount } from '@pancakeswap/v3-sdk' import { Token, CurrencyAmount, Percent } from '@pancakeswap/swap-sdk-core' import { ChainId } from '@pancakeswap/chains' const USDC = new Token(ChainId.BSC, '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d', 18, 'USDC') const CAKE = new Token(ChainId.BSC, '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82', 18, 'CAKE') // Construct pool from on-chain state const pool = new Pool( USDC, CAKE, FeeAmount.MEDIUM, // 2500 = 0.25% sqrtPriceX96, // current sqrt price from contract liquidity, // current liquidity from contract tickCurrent, // current tick from contract ) // Build a position const position = new Position({ pool, liquidity: 10n ** 18n, tickLower: -60, tickUpper: 60, }) // Get add-liquidity calldata const { calldata, value } = NonfungiblePositionManager.addCallParameters(position, { slippageTolerance: new Percent(5, 1000), recipient: '0xYOUR_ADDRESS', deadline: Math.floor(Date.now() / 1000) + 60 * 20, }) ``` -------------------------------- ### Install Price API SDK Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/price-api-sdk.md Install the SDK using npm. This command fetches and installs the necessary package for using the price API. ```bash npm install @pancakeswap/price-api-sdk ``` -------------------------------- ### Install Universal Router SDK Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/universal-router-sdk.md Install the SDK using npm. This command fetches and installs the necessary package for building transaction calldata. ```bash npm install @pancakeswap/universal-router-sdk ``` -------------------------------- ### Install Bun.js Source: https://github.com/pancakeswap/pancake-developer/blob/master/README.md Install the Bun.js runtime environment. This is a prerequisite for running the project. ```bash curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Install Smart Router SDK Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/smart-router.md Install the Smart Router SDK using npm. This command fetches and installs the necessary package for your project. ```bash npm install @pancakeswap/smart-router ``` -------------------------------- ### Install V3 SDK Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/v3-sdk.md Install the V3 SDK using npm. This is the first step to using the SDK for concentrated liquidity management. ```bash npm install @pancakeswap/v3-sdk ``` -------------------------------- ### Quick Start with PancakeSwap Chains SDK Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/chains.md Import and use chain IDs, human-readable names, and testnet checks from the SDK. This example demonstrates basic usage for EVM chains. ```typescript import { ChainId, chainNames, testnetChainIds } from '@pancakeswap/chains' // Use chain IDs const bscId = ChainId.BSC // 56 const ethId = ChainId.ETHEREUM // 1 const arbId = ChainId.ARBITRUM_ONE // 42161 // Human-readable name console.log(chainNames[ChainId.BASE]) // "base" // Check for testnet if (testnetChainIds.includes(chainId)) { console.warn('Connected to a testnet') } ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/guides/develop-a-hook.mdx Install dependencies and run existing tests for the hook template. ```bash > forge install // install dependencies > forge test // run the existing tests in the repository ``` -------------------------------- ### Install Swap SDK Core Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/swap-sdk-core.md Install the core SDK package using npm. ```bash npm install @pancakeswap/swap-sdk-core ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/pancakeswap/pancake-developer/blob/master/README.md Install all necessary project dependencies using Bun.js. ```bash bun install ``` -------------------------------- ### Run Development Server Source: https://github.com/pancakeswap/pancake-developer/blob/master/README.md Start the local development server to begin working on the project. ```bash bun dev ``` -------------------------------- ### Install PCSX SDK Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/pcsx-sdk.md Install the PCSX SDK using npm. ```bash npm install @pancakeswap/pcsx-sdk ``` -------------------------------- ### Quick Start: Add Liquidity Calldata for CL Pool Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/infinity-sdk.md This example demonstrates how to build calldata for adding liquidity to a concentrated liquidity (CL) pool using the Infinity SDK. It includes defining pool keys, desired amounts, and recipient details. ```typescript import { CLPool, CLPositionManager, PoolKey, } from '@pancakeswap/infinity-sdk' import { Token, CurrencyAmount } from '@pancakeswap/swap-sdk-core' import { ChainId } from '@pancakeswap/chains' const USDC = new Token(ChainId.BSC, '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d', 18, 'USDC') const CAKE = new Token(ChainId.BSC, '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82', 18, 'CAKE') // Define a pool key const poolKey: PoolKey = { currency0: USDC, currency1: CAKE, fee: 2500, tickSpacing: 50, hooks: '0x0000000000000000000000000000000000000000', } // Build add-liquidity calldata for CL const { calldata, value } = CLPositionManager.addLiquidity({ poolKey, tickLower: -100, tickUpper: 100, amount0Desired: CurrencyAmount.fromRawAmount(USDC, 1_000_000n), amount1Desired: CurrencyAmount.fromRawAmount(CAKE, 10n ** 18n), recipient: '0xYOUR_ADDRESS', deadline: Math.floor(Date.now() / 1000) + 60 * 20, }) ``` -------------------------------- ### Install Infinity SDK Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/infinity-sdk.md Install the Infinity SDK using npm. This command adds the necessary package to your project dependencies. ```bash npm install @pancakeswap/infinity-sdk ``` -------------------------------- ### Install PancakeSwap Tokens SDK Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/tokens.md Install the @pancakeswap/tokens package using npm. ```bash npm install @pancakeswap/tokens ``` -------------------------------- ### Permit2 SDK Quick Start Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/permit2-sdk.md Demonstrates how to use the Permit2 SDK for both allowance and signature transfer flows. Requires wallet client for signing. ```typescript import { AllowanceTransfer, SignatureTransfer, PERMIT2_ADDRESS } from '@pancakeswap/permit2-sdk' import { ChainId } from '@pancakeswap/chains' // --- Allowance transfer flow --- const permitSingle = { details: { token: '0xTOKEN_ADDRESS', amount: BigInt(1e18), expiration: Math.floor(Date.now() / 1000) + 60 * 60 * 24, // 24h nonce: 0, }, spender: '0xROUTER_ADDRESS', sigDeadline: Math.floor(Date.now() / 1000) + 60 * 30, } const { domain, types, values } = AllowanceTransfer.getPermitData( permitSingle, PERMIT2_ADDRESS, ChainId.BSC, ) const signature = await walletClient.signTypedData({ domain, types, primaryType: 'PermitSingle', message: values }) // --- Signature transfer flow --- const { domain: sDomain, types: sTypes, values: sValues } = SignatureTransfer.getPermitData( { permitted: { token: '0xTOKEN', amount: BigInt(1e18) }, spender: '0xROUTER', nonce: 1n, deadline: BigInt(Math.floor(Date.now() / 1000) + 1800), }, PERMIT2_ADDRESS, ChainId.BSC, ) ``` -------------------------------- ### Install Permit2 SDK Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/permit2-sdk.md Install the Permit2 SDK using npm. This command is used to add the SDK to your project dependencies. ```bash npm install @pancakeswap/permit2-sdk ``` -------------------------------- ### Quick Start: Create and Submit an Exclusive Dutch Order Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/pcsx-sdk.md This example demonstrates the workflow for creating an Exclusive Dutch Order trade using the PCSX SDK. It involves fetching a quote, parsing it, signing with Permit2, and submitting the order. ```typescript import { createExclusiveDutchOrderTrade, } from '@pancakeswap/pcsx-sdk' import { parseQuoteResponse } from '@pancakeswap/price-api-sdk' import { TradeType } from '@pancakeswap/swap-sdk-core' import { ChainId } from '@pancakeswap/chains' import { bscTokens } from '@pancakeswap/tokens' // 1. Fetch a quote from the PCSX price API const res = await fetch('/api/price-quote', { ... }) const quoteResponse = await res.json() // 2. Parse the quote — encodedOrder and permitData come from the API const result = parseQuoteResponse(quoteResponse, { chainId: ChainId.BSC, currencyIn: bscTokens.cake, currencyOut: bscTokens.usdt, tradeType: TradeType.EXACT_INPUT, }) const trade = result.trade // ExclusiveDutchOrderTrade // 3. Sign with Permit2 using the permitData from the trade const signature = await walletClient.signTypedData(trade.permitData) // 4. Submit the encoded order + signature to the filler network await submitOrder({ encodedOrder: trade.encodedOrder, signature }) ``` -------------------------------- ### PancakeSwap Infinity CLPool: PoolKey Example Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/faq/pancakeswap-infinity-vs-uniswap-v4.mdx Demonstrates the structure of a PoolKey for a Concentrated Liquidity Pool in PancakeSwap Infinity, showing how hook permissions and tick spacing are encoded within the `parameters` field. This example is derived from a BNB/CAKE pool with a dynamic fee hook. ```solidity // ref: https://pancakeswap.finance/liquidity/pool/bsc/0x737a7d974a19bafb34c8d74d898188c9b59689b91f291fa6ade69f71fa0f5afa // PoolId: 0x737a7d974a19bafb34c8d74d898188c9b59689b91f291fa6ade69f71fa0f5afa // Query poolKey via CLPoolManager.poolIdToPoolKey(bytes32 poolId) PoolKey: [ poolIdToPoolKey(bytes32) method Response ] currency0 address : 0x0000000000000000000000000000000000000000 currency1 address : 0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82 hooks address : 0x32C59D556B16DB81DFc32525eFb3CB257f7e493d poolManager address : 0xa0FfB9c1CE1Fe56963B0321B32E7A0302114058b fee uint24 : 8388608 parameters bytes32 : 0x00000000000000000000000000000000000000000000000000000000000a00c2 ``` -------------------------------- ### Install @pancakeswap/chains Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/chains.md Install the package using npm. This package provides chain IDs and network metadata for PancakeSwap. ```bash npm install @pancakeswap/chains ``` -------------------------------- ### Quick Start: Fetch Token Prices Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/price-api-sdk.md Demonstrates how to import and use key functions from the SDK to fetch single token prices, multiple token prices, and prices using raw token addresses. Ensure necessary chain and token definitions are imported. ```typescript import { getCurrencyPrice, getCurrencyListUsdPrice, getTokenPrices, getNativeTokenPrices, } from '@pancakeswap/price-api-sdk' import { ChainId } from '@pancakeswap/chains' import { bscTokens } from '@pancakeswap/tokens' // Single token price const cakePrice = await getCurrencyPrice({ currency: bscTokens.cake, chainId: ChainId.BSC, }) console.log(`CAKE: $${cakePrice}`) // Multiple tokens at once const prices = await getCurrencyListUsdPrice({ currencies: [bscTokens.cake, bscTokens.usdt], chainId: ChainId.BSC, }) // { '0x0E09...': 2.34, '0x55d3...': 1.00 } // Raw addresses (more efficient for large lists) const tokenPrices = await getTokenPrices({ chainId: ChainId.BSC, addresses: ['0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82'], }) ``` -------------------------------- ### Example: Calculate Price Ratio from sqrtPriceX96 (CAKE/WETH) Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/overview/amm-layer/concentrated-liquidity.mdx Demonstrates calculating the price ratio for the CAKE/WETH pool using sqrtPriceX96. Assumes 18 decimals for both tokens. ```solidity // token0: CAKE (18 decimals) // token1: WETH (18 decimals) // sqrtPriceX96: 2574020484831874748518739167 (as of 12 March 2024) // Price ratio of token0 (CAKE) and token1 (WETH): price = (2574020484831874748518739167 / 2**96) **2 = 0.00105551602 CAKE to WETH: 1 CAKE = 0.00105551602 WETH WETH to CAKE: 1 / 0.00105551602: 1 WETH = 947.40 CAKE // CAKE is around $4.3 and ETH is $4100. so 947.40 CAKE = 4073 USDC ``` -------------------------------- ### CLCounterHook Contract Example Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/guides/develop-a-hook.mdx Example of a CLCounterHook contract inheriting from CLBaseHook, setting up required callbacks. ```solidity // Snippet from CLCounterHook.sol import {CLBaseHook} from "./CLBaseHook.sol"; contract CLCounterHook is CLBaseHook { constructor(ICLPoolManager _poolManager) CLBaseHook(_poolManager) {} // 1. Set up callback required. in this case, 4 callback are required function getHooksRegistrationBitmap() external pure override returns (uint16) { return _hooksRegistrationBitmapFrom( Permissions({ beforeInitialize: false, afterInitialize: false, beforeAddLiquidity: true, afterAddLiquidity: true, beforeRemoveLiquidity: false, afterRemoveLiquidity: false, beforeSwap: true, afterSwap: true, beforeDonate: false, afterDonate: false, beforeSwapReturnDelta: false, afterSwapReturnDelta: false, afterAddLiquidityReturnDelta: false, afterRemoveLiquidityReturnDelta: false }) ); } // 2. For each callback required, overwrite the method function _beforeAddLiquidity(address, PoolKey calldata key, ICLPoolManager.ModifyLiquidityParams calldata, bytes calldata) external override poolManagerOnly returns (bytes4) { // implement hook logic and then return selector return this.beforeAddLiquidity.selector; } } ``` -------------------------------- ### Constructing adapterParams in JavaScript Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/cake/cross-chain-cake-bridging.md Example of how to construct the `adapterParams` byte string using `solidityPack` for cross-chain gas airdropping. ```javascript const adapterParams = utils.solidityPack( ["uint16", "uint", "uint", "bytes"], [2, 200000, 0, "0xYourAptosAddress"] ) ``` -------------------------------- ### Example: Calculate Price from Tick (WETH/USDT) Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/overview/amm-layer/concentrated-liquidity.mdx Shows how to calculate the price for the WETH/USDT pool with different token decimals. Adjusts for decimal differences to represent the price ratio correctly. ```solidity // token0: WETH (18 decimals) // token1: USDT (6 decimals) // tick: -193256 (as of 12 March 2024) price: 1.0001 ** -193256 = 4.04965646e-9 // this also imply 1 WETH = 4.04965646e-9 USDT // However WETH is 18 decimals and USDT is 6 decimal, we have to multiply by 12 decimals ratio of WETH/USDT with decimals: = 4.04965646e-9 * (10**18/10**6): 1 WETH = 4049.65646 USDT ``` -------------------------------- ### Example: Calculate Price Ratio from sqrtPriceX96 (WETH/USDT) Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/overview/amm-layer/concentrated-liquidity.mdx Illustrates calculating the price ratio for the WETH/USDT pool with different token decimals using sqrtPriceX96. Adjusts for decimal differences to represent the price ratio correctly. ```solidity // token0: WETH (18 decimals) // token1: USDT (6 decimals) // sqrtPriceX96: 5046499860369450237927407 (as of 12 March 2024) // Price ratio of token0 (WETH) in term of token1 (USDT): 4.0571e-9 ETH for 1 USDC price = (5046499860369450237927407 / 2**96) **2 = 4.0571e-9 WETH to USDC: 4.0571e-9 / (10**6/10**18): 1 WETH = 4057 USDT USDT to WETH: 4.0571e-9 / (10**18/10**6): 1 USDT = 4.0571e-21 WETH ``` -------------------------------- ### Initialize Pool with Starting Price Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/v3/pancakev3pool.md Sets the initial price for the pool. This function is not locked and can be called when the pool is unlocked. ```solidity function initialize(uint160 sqrtPriceX96) external ``` -------------------------------- ### Example: Calculate Price from Tick (CAKE/WETH) Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/overview/amm-layer/concentrated-liquidity.mdx Illustrates calculating the price for the CAKE/WETH pool using a specific tick value. Assumes both tokens have 18 decimals. ```solidity // token0: CAKE (18 decimals) // token1: WETH (18 decimals) // tick: -68554 (as of 12 March 2024) price: 1.0001 ** -68554 = 0.00105411128 // this also imply 1 CAKE = 0.00105411128 WETH ``` -------------------------------- ### Quick Start: Accessing and Using Token Objects Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/tokens.md Import and access pre-configured token objects for various chains. You can also use these tokens to build currency amounts. ```typescript import { bscTokens, ethTokens, arbitrumTokens, baseTokens } from '@pancakeswap/tokens' import { CurrencyAmount } from '@pancakeswap/swap-sdk-core' // Access tokens directly const cake = bscTokens.cake // CAKE on BSC const usdt = bscTokens.usdt // USDT on BSC const weth = ethTokens.weth // WETH on Ethereum const usdc = baseTokens.usdc // USDC on Base // Build an amount const amount = CurrencyAmount.fromRawAmount(cake, 10n ** 18n) // 1 CAKE ``` -------------------------------- ### Example Farm APR Calculation Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/v3/faq.mdx An example demonstrating the calculation of Farm APR using specific values for yearly CAKE rewards, CAKE price, and pool TVL. ```plaintext farmAPR = (630,720 * 2) / 10,000,000 = 12.61% ``` -------------------------------- ### beforeSwap for Dynamic Fee Implementation Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/overview/custom-layer-hook.mdx An example implementation of the beforeSwap hook that returns a dynamic LP fee of 0.3% for a swap. The fee override is combined with the OVERRIDE_FEE_FLAG. ```solidity // Pool will call hook.beforeSwap() before a swap: // With the hook.beforeSwap() implementation: function beforeSwap(..) external returns (bytes4 selector, BeforeSwapDelta delta, uint24 lpFeeOverRide) { // Set 0.3% for this swap. In your hook, you can add custom logic here. uint24 lpFee = 3000; return ( this.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFee | LPFeeLibrary.OVERRIDE_FEE_FLAG); } ``` -------------------------------- ### Minting a Position with CLPositionManager using Planner Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/guides/manage-liquidity.mdx This example demonstrates how to mint a position using `CLPositionManager` by leveraging the `Planner` helper contract to construct the necessary actions and parameters. It includes adding a `CL_MINT_POSITION` action and finalizing with `CLOSE_CURRENCY` actions before calling `modifyLiquidities`. ```solidity PoolKey memory clPoolKey; int24 tickLower; int24 tickUpper; // Assume other field such as liquidity and amount0Max are present Plan memory planner = Planner.init(); // For each action to add, call planner.add planner.add(ACTIONS.CL_MINT_POSITION, abi.encode(clPoolKey, tickLower, tickUpper, liquidity, amount0Max, amount1Max, recipient, hookData)); // finalizeModifyLiquidityWithClose is a helper method to add CLOSE_CURRENCY actions for both currencies bytes memory payload = planner.finalizeModifyLiquidityWithClose(config.poolKey) uint256 deadline = block.timestamp; clPositionManager.modifyLiquidities(payload, deadline); ``` -------------------------------- ### Example Quote Response Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/aggregator.md This JSON object represents a successful quote response from the /quote endpoint, detailing the optimal swap route, amounts, and gas estimation. ```json { "srcToken": { "address": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "decimals": 18, "symbol": "WETH", "name": "Wrapped Ether", "chainId": 1 }, "dstToken": { "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "decimals": 6, "symbol": "USDT", "name": "Tether USD", "chainId": 1 }, "fromAmount": "1000000000000000000", "dstAmount": "3192936412525193112600", "protocols": [ { "percent": 55, "path": ["..."], "pools": ["..."], "inputAmount": "550000000000000000", "outputAmount": "1755948085078420231919" }, { "percent": 45, "path": ["..."], "pools": ["..."], "inputAmount": "450000000000000000", "outputAmount": "1436988327446772880681" } ], "gas": 306000 } ``` -------------------------------- ### Swap ExactInSingle Across CL and Bin Pool Types Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/guides/perform-a-swap.mdx This example demonstrates a multi-hop swap involving both a Concentrated Liquidity (CL) pool and a Bin pool. It swaps token0 to token1 via CL, then token1 to token2 via Bin. ```solidity // step 1: build the Infinity swap param ICLRouterBase.CLSwapExactInputSingleParams memory clParam = ICLRouterBase.CLSwapExactInputSingleParams({ poolKey: poolKey0, // struct which determine the poolKey zeroForOne: true, // if true means 0->1 else 1->0 amountIn: amountIn, // amountIn amountOutMinimum: 0, // minAmountOut, ideally it should not be 0 hookData: "" // hook data }); IBinRouterBase.BinSwapExactInputSingleParams memory binParam = IBinRouterBase.BinSwapExactInputSingleParams({ poolKey: poolKey1, // struct which determine the poolKey swapForY: true, // if true means 0->1 else 1->0 amountIn: ActionConstants.OPEN_DELTA, amountOutMinimum: 0, // minAmountOut, ideally it should not be 0 hookData: "" // hook data }); // step 2: build the Infinity payload with CL token0->token1 and Bin token1->token2 Plan plan = Planner.init(); plan.add(Actions.CL_SWAP_EXACT_IN_SINGLE, abi.encode(clParam)); plan.add(Actions.BIN_SWAP_EXACT_IN_SINGLE, abi.encode(binParam)); bytes memory data = plan.finalizeSwap(poolKey0.currency0, poolKey1.currency1, ActionConstants.MSG_SENDER); // step 3: build command/input bytes memory commands = abi.encodePacked(bytes1(uint8(Commands.INFI_SWAP))); bytes[] memory inputs = new bytes[](1); inputs[0] = data; // Step 4: call universal router router.execute(commands, inputs); ``` -------------------------------- ### Vault Lock Mechanism Example Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/overview/accounting-layer-vault.mdx Demonstrates the four-step process of acquiring a lock from the vault, performing actions with the pool manager, accounting for balance changes, and reconciling the balance. ```Sol contract ExamplePositionManager { function addLiquidity(AddLiquidity calldata params) external { // Step 1: Get a lock vault.lock(..) } function lockAcquired(bytes calldata rawData) external { // Step 2: Perform action with pool manager CallbackData memory data = abi.decode(rawData, (CallbackData)); (BalanceDelta delta, ) = poolManager.mint(...) // Step 4: Reconcile balance, an example of token0 below if (delta.amount0() > 0) { vault.take(poolKey.currency0, user, uint128(delta.amount0())); } else { // sync -> transfer token0 to the vault -> then call vault.settle vault.sync(poolKey.currency0); pay(poolKey.currency0, user, address(vault), uint256(int256(-delta.amount0()))); vault.settle(poolKey.currency0); } } } ``` -------------------------------- ### Quick Start: Find Best Trade Route Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/smart-router.md Demonstrates how to find the optimal trade route for a given token pair using the Smart Router. It involves setting up a public client, quote provider, fetching candidate pools, and then determining the best trade with specified parameters like max hops and splits. ```typescript import { SmartRouter, SwapRouter, SMART_ROUTER_ADDRESSES } from '@pancakeswap/smart-router/evm' import { CurrencyAmount, TradeType, Percent } from '@pancakeswap/swap-sdk-core' import { bscTokens } from '@pancakeswap/tokens' import { ChainId } from '@pancakeswap/chains' import { createPublicClient, http } from 'viem' import { bsc } from 'viem/chains' const client = createPublicClient({ chain: bsc, transport: http() }) const quoteProvider = SmartRouter.createQuoteProvider({ onChainProvider: () => client, }) const [v2Pools, v3Pools] = await Promise.all([ SmartRouter.getV2CandidatePools({ onChainProvider: () => client, currencyA: bscTokens.cake, currencyB: bscTokens.usdt, }), SmartRouter.getV3CandidatePools({ onChainProvider: () => client, subgraphProvider: () => null, currencyA: bscTokens.cake, currencyB: bscTokens.usdt, }), ]) const trade = await SmartRouter.getBestTrade( CurrencyAmount.fromRawAmount(bscTokens.cake, 10n ** 18n), bscTokens.usdt, TradeType.EXACT_INPUT, { gasPriceWei: () => client.getGasPrice(), poolProvider: SmartRouter.createStaticPoolProvider([...v2Pools, ...v3Pools]), quoteProvider, maxHops: 3, maxSplits: 4, }, ) // Build transaction calldata const { value, calldata } = SwapRouter.swapCallParameters(trade, { recipient: '0xYOUR_ADDRESS', slippageTolerance: new Percent(50, 10000), // 0.5% }) ``` -------------------------------- ### Quick Start: Swap ERC20 Call Parameters Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/universal-router-sdk.md Demonstrates how to generate transaction calldata for an ERC20 swap using the Universal Router SDK. It includes setting slippage tolerance, recipient, and deadline. Optional Permit2 signature can be provided to skip a separate approval transaction. ```typescript import { PancakeSwapUniversalRouter, getUniversalRouterAddress, UniversalRouterVersion } from '@pancakeswap/universal-router-sdk' import { ChainId } from '@pancakeswap/chains' import { Percent } from '@pancakeswap/swap-sdk-core' // After getting a trade from SmartRouter: const { calldata, value } = PancakeSwapUniversalRouter.swapERC20CallParameters(trade, { slippageTolerance: new Percent(50, 10000), // 0.5% recipient: '0xYOUR_ADDRESS', deadlineOrPreviousBlockhash: Math.floor(Date.now() / 1000) + 60 * 20, inputTokenPermit: permit2Signature, // optional — from @pancakeswap/permit2-sdk }) const routerAddress = getUniversalRouterAddress(ChainId.BSC) ``` -------------------------------- ### Example Calldata Response Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/aggregator.md This JSON object is a successful response from the /calldata endpoint, providing the necessary parameters to execute a token swap transaction. ```json { "value": "0x00", "calldata": "0x9aa90356...", "to": "0x..." } ``` -------------------------------- ### Get a Quote Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/aggregator.md Retrieve the best swap route and expected output amount for a given input. This endpoint requires chain ID, source and destination token addresses, and the input amount in wei. ```APIDOC ## GET /v2/quote ### Description Get the best swap route and expected output amount for a given input. ### Method GET ### Endpoint /v2/quote ### Query Parameters - **chainId** (number) - Required - Chain ID. Supported: **1** (Ethereum), **8453** (Base). - **src** (string) - Required - Source token contract address. Use `0x0000000000000000000000000000000000000000` for the chain's native token (ETH). - **dst** (string) - Required - Destination token contract address. Use the zero address for native token. - **amountIn** (string) - Required - Input amount in **wei** (smallest unit). Example: `"1000000000000000000"` for 1 token with 18 decimals. - **gasPrice** (string) - Optional - Gas price in wei for route optimization. Omit to use current network gas price. - **maxHops** (string) - Optional - Max hops in a route. Default: `"2"`. Min: 1, Max: 4. - **maxSplits** (string) - Optional - Max route splits. Default: `"2"`. Min: 1, Max: 4. ### Request Example ```bash curl -G "https://hub-gateway.pancakeswap.com/v2/quote" \ -H "x-secure-token: YOUR_SECRET_TOKEN" \ --data-urlencode "chainId=1" \ --data-urlencode "src=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" \ --data-urlencode "dst=0xdAC17F958D2ee523a2206206994597C13D831ec7" \ --data-urlencode "amountIn=1000000000000000000" \ --data-urlencode "maxHops=2" \ --data-urlencode "maxSplits=2" ``` ### Success Response (200) If the response contains an `error` object, treat it as a failed quote — see [Error handling](#error-handling). - **srcToken** (object) - Source token info (address, decimals, symbol, name, chainId). - **dstToken** (object) - Destination token info. - **fromAmount** (string) - Input amount in wei. - **dstAmount** (string) - Expected output amount in wei. - **protocols** (array) - Route(s) with path, pools, and per-route amounts. - **gas** (number) - Estimated gas (gas units). Multiply by gas price in wei for cost. ``` -------------------------------- ### View Lottery Details Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/lottery-v2/index.md Retrieves comprehensive information about a specific lottery round. Use this to get details such as start and end times, ticket price, reward structure, and collected funds. ```solidity function viewLottery(uint256 _lotteryId) external view returns (Lottery memory); ``` ```solidity uint256 startTime; uint256 endTime; uint256 priceTicketInCake; uint256 discountDivisor; uint256[6] rewardsBreakdown; // 0: 1 matching number // 5: 6 matching numbers uint256 treasuryFee; // 500: 5% // 200: 2% // 50: 0.5% uint256[6] cakePerBracket; uint256[6] countWinnersPerBracket; uint256 firstTicketId; uint256 firstTicketIdNextLottery; uint256 amountCollectedInCake; uint32 finalNumber; ``` -------------------------------- ### Get Calldata Request Example Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/aggregator.md This cURL command demonstrates how to request transaction parameters (calldata, value, and router address) from the /calldata endpoint, using a quote response and additional parameters. ```bash curl -X POST "https://hub-gateway.pancakeswap.com/v1/calldata" \ -H "Content-Type: application/json" \ -H "x-secure-token: YOUR_SECRET_TOKEN" \ -d '{ "srcToken": { "address": "0x0000000000000000000000000000000000000000", "decimals": 18, "symbol": "ETH", "name": "Ether", "chainId": 1 }, "dstToken": { "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "decimals": 6, "symbol": "USDT", "name": "Tether USD", "chainId": 1 }, "fromAmount": "1000000000000000000", "dstAmount": "3192936412525", "protocols": ["..."], "gas": 248000, "recipient": "0x9D24d495F7380BA80dC114D8C2cF1a54a68e25A4", "slippageTolerance": 0.005 }' ``` -------------------------------- ### Pool Initialization Functions Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/overview/amm-layer-poolmanager.mdx Shows the function signatures for initializing a Concentrated Liquidity (CL) pool or a Liquidity Book (Bin) pool. Initialization must occur before any swap or liquidity operations. ```solidity // CLPoolManager function initialize(PoolKey memory key, uint160 sqrtPriceX96); ``` ```solidity // BinPoolManager function initialize(PoolKey memory key, uint24 activeId); ``` -------------------------------- ### startLottery Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/lottery-v2/lottery-contract.md Allows the Operator to start a new lottery round with specified parameters. ```APIDOC ## startLottery - **Operator** ### Description The `startLottery` function is only callable by the **Operator** in order to start a new lottery round. ### Method External ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **_endTime** (uint256) - Required - The timestamp when the lottery round ends. - **_priceTicketInCake** (uint256) - Required - The price of a single ticket in CAKE. - **_discountDivisor** (uint256) - Required - The divisor for ticket discounts. - **_rewardsBreakdown** (uint256[6]) - Required - An array specifying the reward distribution percentages for each bracket. - **_treasuryFee** (uint256) - Required - The fee percentage for the treasury. ### Request Example ```typescript function startLottery( uint256 _endTime, uint256 _priceTicketInCake, uint256 _discountDivisor, uint256[6] calldata _rewardsBreakdown, uint256 _treasuryFee ) external override onlyOperator { // ... implementation ... } ``` ### Response #### Success Response (200) - None (Emits LotteryOpen event) #### Response Example - Emits `LotteryOpen(currentLotteryId, block.timestamp, _endTime, _priceTicketInCake, currentTicketId, pendingInjectionNextLottery)` ``` -------------------------------- ### PancakeV3Pool Internal Functions Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/v3/pancakev3pool.md Internal view function to get the block timestamp. ```APIDOC ## PancakeV3Pool Internal Functions ### _blockTimestamp ```solidity function _blockTimestamp() internal view virtual returns (uint32) ``` Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests. ``` -------------------------------- ### getUniversalRouterAddress Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/sdks/universal-router-sdk.md Get the deployed Universal Router address for a specific chain and optionally a router version. ```APIDOC ## getUniversalRouterAddress ### Description Get the deployed Universal Router address for a specific chain and optionally a router version. ### Method `getUniversalRouterAddress(chainId: ChainId, version?: UniversalRouterVersion) → string` ### Parameters - **chainId** (ChainId) - Required - The chain ID for which to get the router address. - **version** (UniversalRouterVersion) - Optional - The specific version of the Universal Router. ### Response - **string** - The deployed Universal Router address. ``` -------------------------------- ### Get User Stake Amount Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts-aptos/syrup-pools.md Queries the total amount of tokens a specific user has staked in the pool. ```APIDOC ## Get User Stake Amount Get the user stake amount in the pool. ### Function Signature ```rust public fun get_user_stake_amount(account: address) ``` ### Parameters #### Path Parameters - **account** (`address`) - Required - The depositor address. ### Return Values - **0** (`u64`) - The total amount of depositor staked token in the pool. ``` -------------------------------- ### Constructor Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/masterchef/masterchef-v3.md Initializes the MasterChef V3 contract with necessary token and manager addresses. ```solidity constructor(contract IERC20 _CAKE, contract INonfungiblePositionManager _nonfungiblePositionManager, address _WETH) public ``` -------------------------------- ### Get Pending Reward Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts-aptos/syrup-pools.md Calculates and returns the amount of pending reward tokens a user is eligible to claim from the pool. ```APIDOC ## Get Pending Reward Get the pending reward of the depositor in the pool. ### Function Signature ```rust public fun get_pending_reward(account: address): u64 ``` ### Parameters #### Path Parameters - **account** (`address`) - Required - The depositor address. ### Return Values - **0** (`u64`) - The amount of pending reward token in the pool that depositor is eligible to claim. ``` -------------------------------- ### Get Pending Reward for User Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts-aptos/syrup-pools.md Fetches the amount of reward tokens a user is eligible to claim from a Syrup Pool. ```move public fun get_pending_reward(account: address): u64 ``` -------------------------------- ### Get Round Information Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/prediction/how-to-bet-and-claim.mdx Retrieve detailed information about a specific prediction round, including prices, timestamps, and amounts. ```Solidity /// @param epoch The round number to check /// @return round Round information function rounds(uint256 epoch) public view returns (Round memory); ``` -------------------------------- ### Get and Increment Nonce Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/v3/nonfungiblepositionmanager.md Internal function to retrieve the current nonce for a token ID and then increment it, returning the original value. ```Solidity function _getAndIncrementNonce(uint256 tokenId) internal returns (uint256) ``` -------------------------------- ### Get Latest Period Info By PID Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/masterchef/masterchef-v3.md Retrieves the current CAKE per second and end time for a given pool PID. ```solidity function getLatestPeriodInfoByPid(uint256 _pid) public view returns (uint256 cakePerSecond, uint256 endTime) ``` -------------------------------- ### Init Event Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/masterchef/masterchef-v3.md Emitted when the MasterChef V3 contract is initialized. ```solidity event Init() ``` -------------------------------- ### Enabling Dynamic LP Fees in PoolKey Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/overview/custom-layer-hook.mdx Demonstrates how to set the DYNAMIC_FEE_FLAG in the poolKey to enable dynamic LP fees. This requires a hook with beforeSwap() permission. ```solidity key = PoolKey({ currency0: currency0, currency1: currency1, hooks: hook, poolManager: poolManager, fee: LPFeeLibrary.DYNAMIC_FEE_FLAG, // [!code focus] parameters: bytes32(uint256(hook.getHooksRegistrationBitmap())).setTickSpacing(10) }); ``` -------------------------------- ### Get Pool Info Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts-aptos/syrup-pools.md Retrieves comprehensive information about the syrup pool, including total staked amounts, rewards, and timing details. ```APIDOC ## Get Pool Info Get the pool information. ### Function Signature ```rust public fun get_pool_info(): (u64, u64, u64, u64, u64, u64, u64) ``` ### Return Values - **0** (`u64`) - The total amount of staked token in the pool. - **1** (`u64`) - The total amount of reward token in the pool. - **2** (`u64`) - The reward emitting out per second. - **3** (`u64`) - The start time in seconds. - **4** (`u64`) - The end time in seconds. - **5** (`u64`) - The time that user limit will apply after the start time. - **6** (`u64`) - The amount of token allow to be stake within the seconds_for_user_limit. ``` -------------------------------- ### Get Pool Length Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts-aptos/masterchef.mdx Returns the total number of active pools managed by the MasterChef contract. This can be used to iterate through all available pools. ```rust public fun pool_length():u64 ``` -------------------------------- ### Get User Stake Amount in Pool Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts-aptos/syrup-pools.md Queries the total amount of stake tokens a specific user has deposited in a Syrup Pool. ```move public fun get_user_stake_amount(account: address) ``` -------------------------------- ### Get Approved Address for Token Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/v3/nonfungiblepositionmanager.md Returns the address approved to manage a specific token ID. The token ID must exist. ```Solidity function getApproved(uint256 tokenId) public view returns (address) ``` -------------------------------- ### exactOutputSingle Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/v3/smartrouter/v3swaprouter.md Executes a single-hop swap to obtain a specific output amount, using the minimum possible input amount. ```APIDOC ## exactOutputSingle ### Description Swaps as little as possible of one token for `amountOut` of another token that may remain in the router after the swap. ### Method `external payable` ### Parameters #### Parameters - **params** (struct IV3SwapRouter.ExactOutputSingleParams) - The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata ### Return Values #### amountIn (uint256) - The amount of the input token. ``` -------------------------------- ### initialize Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/v3/pancakev3pool.md Sets the initial price of the pool. This function can only be called once as it initializes the pool in an unlocked state. ```APIDOC ## initialize ### Description Sets the initial price for the pool. _not locked because it initializes unlocked_ ### Parameters #### Path Parameters - **sqrtPriceX96** (uint160) - Required - the initial sqrt price of the pool as a Q64.96 ``` -------------------------------- ### Initializing a Pool with a Custom Hook Source: https://github.com/pancakeswap/pancake-developer/blob/master/docs/pages/contracts/infinity/overview/custom-layer-hook.mdx When initializing a pool, specify the hook contract address in the `PoolKey` and include the hook's `getHooksRegistrationBitmap()` result in the `parameters`. This ensures the callbacks are registered with the pool. ```solidity key = PoolKey({ currency0: currency0, currency1: currency1, hooks: hook, // hook contract address poolManager: poolManager, fee: uint24(3000), // 0.3% swap fee // parameters include hook callback and tickSpacing: 10 parameters: bytes32(uint256(hook.getHooksRegistrationBitmap())).setTickSpacing(10) }); /// Initialize the pool poolManager.initialize(key, Constants.SQRT_RATIO_1_1, new bytes(0)); ```