交易哈希 : 0x97d713742eeb6479ae48ac8376aeb4d5397566a469153f8842698778036dd322
const data = {
WBNB: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c', //wbnb
to_PURCHASE: '0xe9e7cea3dedca5984780bafc599bd69add087d56', // 代币合约地址
factory: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73', //PancakeSwap V2 factory
router: '0x10ED43C718714eb63d5aA57B78B54704E256024E', //PancakeSwap V2 router
recipient: '0xCFFFd9fa1B34B82C9883C854bb6A8f7C72Bcd8Dc', // 钱包地址
AMOUNT_OF_WBNB: '0.0002',
Slippage: '49', //in Percentage
gasPrice: '5', //in gwei
gasLimit: '3401676' //at least 21000
}
const bscMainnetUrl = 'https://bsc-dataseed.binance.org/'; //ankr or quiknode
const privatekey = '私钥'; //without 0
const provider = new ethers.providers.JsonRpcProvider(bscMainnetUrl)
const wallet = new ethers.Wallet(privatekey);
const account = wallet.connect(provider);
const factory = new ethers.Contract(
data.factory,
['function getPair(address tokenA, address tokenB) external view returns (address pair)'],
account
);
const router = new ethers.Contract(
data.router,
[
'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
],
account
);
send()
async function send() {
const tokenIn = data.WBNB;
const tokenOut = data.to_PURCHASE;
const pairAddress = await factory.getPair(tokenIn, tokenOut);
console.log(pairAddress);
// 交易对 ERC20
const pair = new ethers.Contract(pairAddress, ['event Mint(address indexed sender, uint amount0, uint amount1)', 'event Transfer(address indexed from, address indexed to, uint256 value)', 'event Approval(address indexed owner, address indexed spender, uint256 value)', 'event transactionHash(address owner)'], account);
//We buy x amount of the new token for our wbnb
const amountIn = ethers.utils.parseUnits(`${data.AMOUNT_OF_WBNB}`, 'ether');
const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
//Our execution price will be a bit different, we need some flexbility
const amountOutMin = amounts[1].sub(amounts[1].div(`${data.Slippage}`));
const tx = await router.swapExactTokensForTokens(
amountIn,
amountOutMin,
[tokenIn, tokenOut],
data.recipient,
Date.now() + 1000 * 60 * 10, //10 minutes
{
'gasLimit': data.gasLimit,
'gasPrice': ethers.utils.parseUnits(`${data.gasPrice}`, 'gwei')
});
tx.wait().then((receipt) => {
console.log('Transaction receipt'); console.log(receipt);
}).catch((error) => {
console.log("error", error)
})
}