PancakeSwap 백서

PancakeSwap

원문

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

-efficient and future-proof. By decoupling core functions like accounting and trading logic, it allows for seamless integration of new pricing curves with hook capabilities—enabling the protocol to evolve without requiring redeployment. ### ⭐️ Key Features 1. Singleton 2. Flash Accounting 3. Hooks 4. Native Token Support 5. Custom Pricing Curves 6. ERC-6909 7. `donate()` {% hint style="success" %} **Open-sourced:** [PancakeSwap Infinity](https://github.com/pancakeswap/infinity-core) is released under an open-source license, encouraging developers to innovate, customize, and collaborate freely. {% endhint %} # Key Features ### 1️⃣ Singleton In PancakeSwap v3, every liquidity pool had its own contract, which made creating pools and swapping across multiple pools more expensive. Infinity fixes this by implementing the Singleton model. Now, all pools live inside a single contract called the PoolManager. This change cuts pool creation gas costs by up to 99% and makes multi-hop swaps (swaps that go through multiple pools) much cheaper by avoiding unnecessary token transfers. #### ⚙️ **How it works:** * Each pool’s data is stored in a shared contract using a unique pool ID. * Creating a new pool is now just a state update, not a full contract deployment. * Swapping across pools is faster and uses less gas.<br> This Singleton approach, along with other optimizations like Flash Accounting and ERC-6909, helps make PancakeSwap Infinity one of the most gas-efficient DEX platforms available today. *** ### ⚡️ Flash Accounting Flash Accounting is a powerful optimization in PancakeSwap Infinity that helps reduce gas fees during complex transactions like multi-hop swaps and liquidity changes. In older versions (like v3), tokens were moved in and out of each pool during every step of a transaction. This led to high gas costs, especially for multi-hop swaps. With Flash Accounting, that’s no longer necessary. Instead of moving tokens after each step, PancakeSwap Infinity keeps track of all token movements internally and only makes one final transfer at the end of the whole transaction. This saves a lot of gas. #### ⚙️ **How It Works:** * When you interact with Infinity (e.g., swapping or adding liquidity), the system calculates the net balance of tokens you owe or receive. * These net token balances are stored temporarily using Transient Storage, a new feature introduced with Ethereum’s Cancun upgrade (EIP-1153). * Transient Storage is cheaper than traditional storage because it only lasts for the duration of the transaction — no permanent writing or reading is needed. *** ### 🪙 Native Token Support With the introduction of Singleton architecture and Flash Accounting, PancakeSwap Infinity now supports native gas tokens (e.g., BNB, ETH) directly in liquidity pools — no more wrapping and unwrapping required. #### ✅ Key Highlights * **Direct Native Token Pools:** You can now create pools like ETH/USDC, BNB/CAKE without needing WETH or WBNB. * **Gas Efficient:** Native token transfers are \~50% cheaper than ERC-20 token transfers, leading to lower gas costs for swaps and liquidity actions.<br> **Previously Removed, Now Re-enabled:** Native token support was absent in earlier versions due to implementation complexity and liquidity fragmentation. *** ### 📈 Custom Pricing Curves PancakeSwap Infinity gives developers the power to create custom pricing models for pools — moving beyond the traditional model used in most AMMs. {% hint style="success" %} **Developers can build entirely new swap behaviors and liquidity models tailored to specific asset types or trading strategies.** {% endhint %} #### 🔧 What Are Custom Pricing Curves? Custom pricing curves allow developers to: * Bypass the native pool manager logic, creating pools with custom-defined swap behaviors. * Alter how token amounts are calculated for swaps or liquidity modifications. * Incorporate custom fee mechanics, such as: * Liquidity withdrawal fees * Rebates or penalties based on strategy All of this is made possible through before / after swap hook callbacks, which can intercept and modify swap parameters dynamically. #### 🛠 Example Use Cases * **StableSwap Curves:** Design flatter curves around a 1:1 price ratio, reducing price impact between assets like USDC and USDT. * **RWAs:** Create custom behaviors for different asset types with dynamic supply. * **Hook-Level Fees:** Charge unique fees that differ from pool-level fees, such as developer fees. * **Custom Risk Models:** Adjust pricing to reflect volatility, oracle data, or external metrics. {% hint style="info" %} In previous AMM versions (e.g., PancakeSwap v2/v3), pricing logic was hardcoded and rigid. PancakeSwap Infinity’s architecture unlocks the ability to build more capital-efficient and tailored pools. {% endhint %} #### 🔍 Developer Flexibility * Developers can deploy custom hook contracts to override the pricing logic. * Hook callbacks such as beforeSwap and afterSwap allow full control over how token deltas are calculated and applied. *** ### 🧮 ERC-6909: Efficient Multi-Token Accounting PancakeSwap Infinity adopts[ ERC-6909](https://eips.ethereum.org/EIPS/eip-6909), a lightweight and gas-efficient token standard designed for internal accounting of multiple tokens within a single contract. It replaces many traditional ERC-20 operations with mint and burn primitives—leading to significant gas savings and simplified transaction flows. #### ⚙️ How It Works Rather than moving tokens in and out of the protocol with each interaction, ERC-6909 tokens represent internal balances: * Mint: When users deposit tokens or perform a trade, they can choose to receive ERC-6909 tokens as claims. * Burn: Later, instead of transferring ERC-20 tokens again, users can simply burn these ERC-6909 tokens to settle balances or fund new operations. This model drastically reduces the need for external token transfers, which typically incur higher gas costs and interact with third-party logic (e.g., USDC's blacklisting checks). #### 🪙 Benefits of ERC-6909 <table><thead><tr><th width="262.9921875">Feature</th><th width="497.7421875">Benefit</th></tr></thead><tbody><tr><td>✅ Internal Balance Claims</td><td>No need to transfer tokens repeatedly between user and contract</td></tr><tr><td>✅ Gas-Efficient Mint/Burn</td><td>Constant overhead regardless of token, no external contract calls</td></tr><tr><td>✅ Simpler Than ERC-1155</td><td>Smaller code size, no callbacks, no batched transfer requirements</td></tr><tr><td>✅ Multi-Token Support</td><td>A single contract can track multiple token types with isolated balances</td></tr><tr><td>✅ Seamless with PoolManager</td><td>Eliminates redundant ERC-20 approvals and transfers</td></tr></tbody></table> #### 🚀 Use Cases * **High-frequency traders:** Avoid gas-heavy transfers and interact directly using internal balances. * **Liquidity managers:** Open and close positions more efficiently without excessive token movements. #### 💡 Key Notes * Users opt-in to ERC-6909 flow when they don’t need to immediately settle token transfers. * Internal balances can be consolidated and net-settled later, giving power users greater control and flexibility. *** ### 💸 Donate Method The `donate()` method allows users to directly incentivize in-range liquidity providers within a pool by donating tokens. This method relies on the pool's fee accounting system to facilitate the payments, ensuring that only pool tokens are supported. #### 🔹 Key Features: * **Direct Payments to LPs:** Donations are made directly to liquidity providers, rewarding those who maintain liquidity within the active range of the pool. * **Supports Pool Tokens Only:** The `donate()` method only supports donations in the pool's tokens, as it leverages the fee accounting system to ensure proper distribution. * **Open to All Users:** Any user can call the `donate()` method, enabling anyone to incentivize active liquidity provision. While the `donate()` method is a powerful tool to incentivize LPs, donors should be aware that their donations may be front run by other users. This can occur when a user quickly adds liquidity to the pool right before a donation is made, receiving a portion of the donated funds. To prevent front-running, donors may need to consider additional strategies when designing their donation mechanisms, such as: * Ensuring that donations occur in a way that minimizes the ability for opportunistic front-running. * Adding time delays or specific conditions (using before / after donate hook callbacks) that ensure the donations are not being exploited in this way. # Hooks {% hint style="info" %} If you're a developer or looking for detailed technical documentation on developing a hook, please visit [here](https://developer.pancakeswap.finance/contracts/infinity/guides/develop-a-hook). {% endhint %} Hooks are powerful add-ons that let developers extend and customize the behavior of liquidity pools in PancakeSwap Infinity. Think of them as "plugins" or "widgets" that add new features to liquidity pools. #### 🔍 What Are Hooks? * Hooks are external smart contracts created by anyone — developers, protocols, or community members — and attached to liquidity pools to enhance or modify their behavior. * Each pool can have only one hook attached, but a single hook can serve many pools. * Hooks can run custom code before or after key actions like: * Initializing a pool * Swapping * Adding/removing liquidity * Donating<br> **⛓️ How Hooks Work:** * A hook is selected during pool creation and can’t be changed later. * A hook contract triggers on specific actions (swap, add liquidity, etc) and executes logic before or after those actions as defined within the contract. * For example, a hook could: * Offer swap fee discounts to CAKE holders * Charge custom fees and distribute rewards * Enable new swap logic like stableswaps or TWAMM-style orders<br> #### ⚙️ Hook Callbacks Hooks can be triggered during ten specific moments. Developers can choose which ones they want to implement: * beforeInitialize / afterInitialize * beforeAddLiquidity / afterAddLiquidity * beforeRemoveLiquidity / afterRemoveLiquidity * beforeSwap / afterSwap * beforeDonate / afterDonate<br> These allow to implement highly customizable and modular behavior through hooks. #### 🔧 Two Types of Hooks **Type 1: No Authorization Needed** These hooks run automatically and do not require user permission. They are triggered by actions like swaps or liquidity changes. Examples: * Dynamic Fees: Adjust swap fees based on market volatility * Fee Rebates: Give discounts to users holding CAKE or trading high volumes Example Flow (CAKE Fee Discount): 1. A user initiates a swap. 2. The hook checks their CAKE balance via `beforeSwap` hook callback. 3. If the user holds enough CAKE as per defined thresholds, they get a 50% discount on pool fees. 4. The rest of the transaction proceeds as usual.<br> {% hint style="success" %} These hooks don’t need a special UI or additional interaction. The benefits are applied automatically. {% endhint %} **Type 2: User Authorization Required** These hooks need users to interact directly with them, provide authorisation and may require to transfer funds, often to create or manage positions. Examples: * Limit Orders: Execute a swap only when target price is reached. * TWAMM: Break large orders into smaller pieces for better execution. * Active Liquidity Management: Automatically manage LP positions for optimal returns. Example Flow (Limit Order Hook): 1. User interacts directly with the hook contract (not the usual swap UI). 2. They enter details like limit price, token pair, amount. 3. The hook issues a receipt token representing the order. 4. Later, when pool price hits the target, the hook executes the order using afterSwap. 5. The user can return the receipt token to claim the swapped assets. {% hint style="info" %} These hooks often need a custom UI and users must trust and approve the hook contract to hold their funds. {% endhint %} #### 🚀 Use Cases & Innovation Hooks unlock limitless possibilities, including: * Custom AMMs (e.g., stablecoin curves) * Liquidity mining rewards * Automated trading strategies, liquidity management * On-chain limit orders, other order types * Dynamic pricing and fee adjustments * Yield-enhancing LP strategies<br> With hooks, developers can build an entirely new DeFi experience using the existing infrastructure of PancakeSwap Infinity — speeding up development and lowering costs. # Dynamic Fee Hook PancakeSwap’s official Dynamic Fee Hook is designed to create a fairer value exchange between Liquidity Providers and Traders. It protects LPs from excessive impermanent loss (IL) while keeping the market efficient for traders. Built by the PancakeSwap core team, this hook is tailored specifically to offer a smart, adaptive alternative to conventional fixed-fee models. #### 🔍 Why Dynamic Fees? Large Arbitrage trades cause greater price divergence in pools, increasing IL for LPs. Our dynamic fee model charges proportionally higher fees on larger arbitrage trades to offset this risk — while still leaving enough room for arbitrageurs to profit and keep prices aligned. #### 📊 How Is This Different From Other Models? Other models in the past have used historical data to estimate volatility, other factors to adjust fees. However: * Historical data is a lagging indicator and may not accurately predict future volatility. * External market events (like regulatory changes or economic shifts) can render past trends unreliable. * Complex, parameter-heavy models risk overfitting — performing well on past data but poorly on new, unseen conditions. Our approach is simpler, adaptive, and grounded in real-time trading behaviour. #### ⚙️ How It Works * **We don’t predict volatility or other macro factors**\ Instead, our model inherently benefits from the behaviour of arbitrageurs under different market regimes: * **High volatility:** More arbitrage trades at larger sizes → Higher fees for LPs, covering a larger share of IL. * **Low volatility:** Fewer, smaller trades → IL is lower by nature, but LPs still earn higher fees than in a fixed-fee model. * **Our model uses** * An exponentially weighted pool price to detect arbitrage trades. * An exponential fee curve based on the price impact of each swap. * A maximum fee cap of 5% to maintain trader fairness. {% hint style="success" %} This ensures fees scale dynamically with trade impact while adapting automatically to changing market conditions. {% endhint %} * **Balanced Incentives**\ Arbitrageurs still retain \~50% of their profits after dynamic fees, ensuring they're motivated to keep pool prices in line with the market. #### 📌 Key Takeaways * No reliance on volatility or other macro factor predictions. * Adapts automatically to market volatility based on actual trade behaviour. * Protects LPs from IL on a per-swap basis. * Maintains strong incentives for arbitrageurs to close price gaps. * Benefits traders with deeper liquidity and lower base fees. # Shared Inventory Hook PancakeSwap's official Shared Inventory Hook (SIH) is designed to allow a single pool of capital market-make across every pool that shares its tokens, instead of locking separate liquidity into each one. It give traders deeper quotes and lower price impact, while letting liquidity providers deploy less capital for the same coverage. Built by the PancakeSwap core team, this hook is tailored for asset issuers and market makers who want to quote multiple pairs on-chain without fragmenting their inventory. #### 🔍 Why Shared Inventory? Providing liquidity to multiple pairs the conventional way means locking dedicated capital into separate pools, most of it sitting idle between trades. SIH instead holds one balance per token and injects it as liquidity only when a swap needs it, so the same capital can back every pool that shares that token. #### 📊 How Is This Different From Other Models? Conventional concentrated liquidity requires committing the full principal to a single pool. Other cross-pool approaches such as virtual-balance settlement layers typically sit outside the AMM itself, where liquidity might not be visible as on-chain pool depth and routed directly by aggregators. SIH's liquidity enters and exits PancakeSwap Infinity CLAMM pool by the hook on every swap, so it shows up as genuine pool depth that routers can see and fill against. #### ⚙️ How It Works * **Just-in-time (JIT) injection**\ Before each swap, the hook mints a configured concentrated liquidity position into the pool; after the swap executes, it burns and settles the net result. The position exists only for the duration of one swap, the balance is free to serve the very next pool that needs it. * **One balance, many pools**\ Inventory is the hook's own token balance, there is no per-pool deposit. Any token that is to be used in more than one pool is shared across all of them. {% hint style="success" %} This decouples the depth a pool quotes from the in-pool capital directly holds: a funded hook can quote deep, tight liquidity across a number of pools that share a token. {% endhint %} * **Configurable hook**\ For every pool it serves, the hook holds an adjustable independent configuration for price range and depth. Moving the band requires just a configuration update, making it simple to recenter the quotes around a moving reference price. #### 📌 Key Takeaways * One shared token balance backs every pool that uses that token. Adding a new pool utilises no new principal. * Fully on-chain and composable: SIH liquidity is real pool depth, routable by PancakeSwap and third-party aggregators alike. * Traders get deeper quotes and lower price impact on size; operators earn the same trading fees on a fraction of the conventional capital. # Introducing Shared Inventory Hook 2026-08-21 <figure><img src="https://2908774936-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MHREX7DHcljbY5IkjgJ-1972196547%2Fuploads%2Fqa6G9bE65IxUZv1pOpkY%2Fimage.png?alt=media&amp;token=9b751349-f6b2-43bf-9217-ebae0b61ee1d" alt=""><figcaption></figcaption></figure> Quoting five pairs shouldn't cost five times the capital. But onchain, that's the deal every asset issuer gets: liquidity is tied to each pair, so every new pair means putting up another chunk of capital - most of it just sitting there, earning nothing until that exact pair trades within the exact price range. Every time you want to quote a new pair, you LP fresh capital into it — capital that's then locked to that one pair and can't be used anywhere else. The Shared Inventory Hook (SIH) breaks that link. It's the newest hook on PancakeSwap Infinity — and the first built for capital efficiency. *💡 Recap: A hook is a smart contract (like an add-on) that plugs into an Infinity pool and runs custom logic mid-swap — no new venue to spin up.* So how does it work? Instead of locking a separate stack in every pool, an RWA asset issuer funds **one shared inventory**, and the shared inventory hook quotes depth from it into whichever pair is trading — just-in-time, right as the swap happens. Think of it as one stock room supplying every dish in the kitchen, instead of a separate stock room for each. One balance does the work of many. That single shift is what makes SIH capital efficient, and it shows up three ways: * **Capital stays active and working.** Liquidity from the hook inventory is injected just-in-time on a swap, so it's actively working and earning you fees instead of sitting idle. * **Fee opportunity from one balance, across multiple pairs.** One inventory earns across all the pairs it serves, so you capture fee flow with far less capital deployed. * **Lower price impact.** Because the liquidity quoted at swap time is deeper, large trades see lower price impact whenever SIH is quoting the
프로젝트로 돌아가기