approve.mjs 1.4 KB

12345678910111213141516171819202122232425262728293031
  1. import Web3 from "web3";
  2. import { BigNumber } from "bignumber.js";
  3. import { Wallet, Provider } from "zksync-web3";
  4. import erc20Abi from "./erc20Abi.json" assert { type: "json" };
  5. import { ethers } from "ethers";
  6. const rpc = "https://zksync2-testnet.zksync.dev/";
  7. const privateKey = "0xd768b0b3f8dedcb465ad680268453391f7da6ec4e1942a13fdfcdea8773aab3e";
  8. const tokenAddress = "0xB2bAbfBBB09A17Fb38cBc7E793B18078dd241347";
  9. const spender = "0x6eeF3310E09DF3aa819Cc2aa364D4f3Ad2E6fFe3";
  10. const provider = new Provider(rpc);
  11. const wallet = new Wallet(privateKey).connect(provider);
  12. const web3 = new Web3(new Web3.providers.HttpProvider(rpc));
  13. const token = new web3.eth.Contract(erc20Abi, tokenAddress);
  14. const decimals = await token.methods.decimals().call();
  15. console.log(`decimals: ${decimals}`);
  16. const allowance = await token.methods.allowance(wallet.address, spender).call();
  17. console.log(`allowance: ${ethers.utils.formatUnits(allowance, decimals)}`);
  18. if (!new BigNumber(allowance).isGreaterThan(new BigNumber(0))) {
  19. const approve = token.methods.approve(spender, ethers.constants.MaxUint256.toHexString());
  20. const gasLimit = await approve.estimateGas({ from: wallet.address });
  21. console.log(`gasLimit: ${gasLimit}`);
  22. const tx = await wallet.sendTransaction({
  23. to: tokenAddress,
  24. data: approve.encodeABI(),
  25. gasLimit: parseInt(new BigNumber(gasLimit).times(new BigNumber(0.5)).toFixed(0) ),
  26. });
  27. console.log(tx);
  28. }