You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

技术咨询:如何在智能合约中从PancakeSwap获取BNB价格并基于Solidity实现BNB到WBNB的PancakeSwap兑换(需代码示例)

Technical Solutions for PancakeSwap Integration in Solidity

1. Retrieving BNB Price from PancakeSwap Liquidity Pool

To get BNB's USD price from a PancakeSwap liquidity pool, we’ll use the WBNB-BUSD pair (a widely used stablecoin pair on BSC). PancakeSwap pairs follow the Uniswap V2 standard, so we can fetch reserve data directly from the pair contract to calculate the price.

Here’s a complete Solidity implementation:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IERC20 {
    function decimals() external view returns (uint8);
}

interface IPancakePair {
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function token0() external view returns (address);
    function token1() external view returns (address);
}

contract BNBPriceFeed {
    // WBNB-BUSD pair address (BSC Mainnet)
    address public constant WBNB_BUSD_PAIR = 0x58F876857a02D6762E0101bb5C46A8c1ED44Dc16;
    address public constant WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c;
    address public constant BUSD = 0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56;

    function getBNBPriceInBUSD() external view returns (uint256) {
        IPancakePair pair = IPancakePair(WBNB_BUSD_PAIR);
        (uint112 reserve0, uint112 reserve1, ) = pair.getReserves();
        
        // Map reserves to WBNB and BUSD based on token order in the pair
        (uint256 wbnbReserve, uint256 busdReserve) = pair.token0() == WBNB 
            ? (reserve0, reserve1) 
            : (reserve1, reserve0);

        // Calculate 1 BNB price (WBNB is 1:1 with BNB)
        // Multiply by 1e18 to preserve precision (both tokens use 18 decimals)
        uint256 price = (busdReserve * 1e18) / wbnbReserve;
        return price;
    }
}

Important Notes:

  • Replace the pair address with the correct one for your network (e.g., testnet vs mainnet).
  • The returned price has 18 decimals: a value of 2500000000000000000000 means 1 BNB = 2500 BUSD.
  • Always verify the token order (token0 vs token1) to avoid inverted price calculations.

2. Swapping BNB to WBNB via PancakeSwap

To swap native BNB to WBNB using PancakeSwap, we’ll use the PancakeSwap Router V2, which handles native token swaps by wrapping BNB internally. Here’s a practical implementation:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IPancakeRouter {
    function swapExactETHForTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external payable returns (uint256[] memory amounts);
}

contract BNBToWBNBSwap {
    // PancakeSwap Router V2 address (BSC Mainnet)
    address public constant PANCAKE_ROUTER = 0x10ED43C718714eb63d5aA57B78B54704E256024E;
    address public constant WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c;

    // Swap native BNB to WBNB
    function swapBNBToWBNB(
        uint256 amountOutMin,
        uint256 deadline
    ) external payable returns (uint256[] memory amounts) {
        // Path for BNB -> WBNB (router wraps native BNB to WBNB internally)
        address[] memory path = new address[](1);
        path[0] = WBNB;

        amounts = IPancakeRouter(PANCAKE_ROUTER).swapExactETHForTokens{value: msg.value}(
            amountOutMin,
            path,
            msg.sender,
            deadline
        );
    }

    // Allow the contract to receive native BNB
    receive() external payable {}
}

Key Details:

  • Slippage Tolerance: amountOutMin is the minimum WBNB you’ll accept. For example, set it to 0.99e18 when swapping 1 BNB to allow 1% slippage.
  • Deadline: deadline is a Unix timestamp after which the swap will fail, preventing stale transactions.
  • Router Address: Use the correct router address for your target network (mainnet or testnet).
  • Receive Function: Required to let the contract accept native BNB deposits.

Alternatively, you could directly call the deposit() function on the WBNB contract to wrap BNB, but this example strictly follows your request to use PancakeSwap’s infrastructure.


内容的提问来源于stack exchange,提问作者asalef alena

火山引擎 最新活动