Why On-Chain Price?
Using a centralized price API introduces a trust assumption and a point of failure. PancakeSwap V2's getAmountsOut function gives a decentralized, manipulation-resistant price directly from the liquidity pool.
The getAmountsOut Call
// PANCAKESWAP_ROUTER_V2 = 0x10ED43C718714eb63d5aA57B78B54704E256024E (BSC mainnet)
const router = new ethers.Contract(PANCAKESWAP_ROUTER_V2, ROUTER_ABI, provider);
const path = [WBNB_ADDRESS, USDT_ADDRESS];
const amountsOut = await router.getAmountsOut(
ethers.utils.parseEther('1'), // 1 BNB
path
);
const bnbPriceInUsdt = parseFloat(ethers.utils.formatUnits(amountsOut[1], 18));
Converting Gas Cost
// gasUsed comes from transaction receipt
// gasPrice comes from the signed transaction
const bnbGasCost = gasUsed * gasPrice; // in wei
const usdtGasCost = (bnbGasCost / 1e18) * bnbPriceInUsdt;
// This USDT amount is deducted from the merchant's net payout
Gas Refill via Swap
When the gas wallet BNB balance drops below GAS_WALLET_MIN_BNB, the GasRefillProcessor swaps GAS_REFILL_USDT_AMOUNT from the fee wallet for BNB via PancakeSwap V2 swapExactTokensForETH.
Slippage Protection
The swap uses a 1% slippage tolerance (amountOutMin = amountOut × 0.99) to protect against sandwich attacks while keeping refills reliable even in volatile conditions.
Configuring the Router Address
PANCAKESWAP_ROUTER_V2=0x10ED43C718714eb63d5aA57B78B54704E256024E
Leave blank to use the default BSC mainnet address. Override for testnet or other chains.