多个账号批量购买代币

  • i am duck
  • 更新于 2022-07-27 14:05
  • 阅读 3432

多个账号批量购买代币

场景需求

用户需要多个账号,批量购买同一代币。批量购买代币涉及到多个流程。 假如用户需要在bsc-test链用usdt购买busd。

则简单的流程如下

  1. 用户获取bnb作为gas费用
  2. 用户获取usdt作为买的币
  3. 用户授权usdt给router合约
  4. 用户调用router购买函数

批量转账工具

其中用户获取代币时,需要大号给小号转。 我开发了一款免费批量转账工具https://www.ducks.life/#/ 欢迎收藏使用,支持eth,bsc,rinkeby,bsc-test

代码地址

https://github.com/Sexy-J/batch-buy.git

基本调用流程

// 安装环境 需要 安装node
npm install  //安装第三方库

1. 调用 node ./createAccount.js 生成 1000 个账号
2. 将 accounts 目录下的 privateKeyAndAccountArr 按需黏贴至 privateKeys.json
3. 向 1000 个账号转账 适量的 bnb
4. 向 1000 个账号转账 适量的 usdt
5. 将要使用的账号导入 privateKeys.json
6. 修改 approve 文件中的 token 信息,填入要授权的代币,然后命令行调用 node ./approve.js ,
7. 修改 index 文件中 path 路径, 然后命令行调用 node ./index.js

购买结束

本代码实现了3个主要功能。

  1. 批量创建账号
  2. 批量approve给router合约
  3. 批量购买代币

核心购买代币功能代码。

//  bsc测试网 环境
const Tx = require("ethereumjs-tx");
const ROUTER_ABI = require("./abis/router.json");
const PAIR_ABI = require("./abis/pair.json");
const { parseAmount } = require("./format");
const { defaultChainId, addresses, web3, privateKeyList } = require("./config");
const pancakeRouter = addresses.router; //pancakeRouter

async function swapExactTokensForTokens(
  amountIn,
  amountOutMin,
  path,
  fromAddr,
  privateKey
) {
  const myContract = new web3.eth.Contract(ROUTER_ABI, pancakeRouter);
  const code = myContract.methods
    .swapExactTokensForTokens(
      amountIn.toString(),
      amountOutMin.toString(),
      path,
      fromAddr,
      2950523336 //时间戳 随便填个大的时间
    )
    .encodeABI();
  const nonce = await web3.eth.getTransactionCount(fromAddr);
  const rawTx = {
    from: fromAddr,
    to: pancakeRouter,
    nonce: nonce,
    gasPrice: 5100000000,
    gasLimit: 300000,
    chainId: defaultChainId,
    value: 0,
    data: code,
  };
  let tx = new Tx(rawTx);
  tx.sign(privateKey);
  let serializedTx = tx.serialize();
  web3.eth
    .sendSignedTransaction("0x" + serializedTx.toString("hex"))
    .on("transactionHash", (hash) => {
      console.log(hash);
    })
    .on("error", (err) => {
      console.log(err);
    });
}

// 用busd 买usdt
const buyToken = async () => {
  const inToken = addresses.busd;
  const outToken = addresses.usdt;
  const path = [inToken, outToken];
  const tokenContract = new web3.eth.Contract(PAIR_ABI, path[0]);
  const decimal = await tokenContract.methods.decimals().call();
  const _amount = "0.1"; //花费的数量
  const amount = parseAmount(_amount, decimal); //
  for (let i = 0; i < privateKeyList.length; i++) {
    const fromAddr = privateKeyList[i].account;
    const privateKey = Buffer.from(privateKeyList[i].privateKey, "hex");
    swapExactTokensForTokens(amount, 0, path, fromAddr, privateKey);
  }
};

buyToken();

这个代码只适用于标准erc20购买标准erc20,如果其中有native token或者带手续费型代币,则需要调用其他函数。

新增配置文件,更好的修改代码

点赞 3
收藏 1
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

1 条评论

请先 登录 后评论
i am duck
i am duck
免费批量转账工具,https://www.ducks.life/