spacefiaddliquidity.mjs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import Web3, { eth } from "web3";
  2. import { BigNumber } from "bignumber.js";
  3. import { Wallet, Provider } from "zksync-web3";
  4. import { ethers } from "ethers";
  5. import spacefiRouterAbi from "./spacefiRouterAbi.json" assert { type: "json" };
  6. import spacefiFactoryAbi from "./spacefiFactoryAbi.json" assert { type: "json" };
  7. import spacefiPairAbi from "./spacefiPairAbi.json" assert { type: "json" };
  8. const rpc = "https://zksync2-testnet.zksync.dev/";
  9. const privateKey = "0xd768b0b3f8dedcb465ad680268453391f7da6ec4e1942a13fdfcdea8773aab3e";
  10. const spaceFiRouterAddress = "0x6eeF3310E09DF3aa819Cc2aa364D4f3Ad2E6fFe3";
  11. const usdcAddress = "0x0faF6df7054946141266420b43783387A78d82A9";
  12. const provider = new Provider(rpc);
  13. const wallet = new Wallet(privateKey).connect(provider);
  14. const web3 = new Web3(new Web3.providers.HttpProvider(rpc));
  15. const value = ethers.utils.parseEther("0.001");
  16. const spacefiRouter = new web3.eth.Contract(spacefiRouterAbi, spaceFiRouterAddress);
  17. const wethAddress = await spacefiRouter.methods.WETH().call();
  18. console.log(`wethAddress: ${wethAddress}`);
  19. const d = ethers.BigNumber.from(usdcAddress).gt(ethers.BigNumber.from(wethAddress));
  20. const inputToken = "eth";
  21. const inputEth = inputToken === "eth";
  22. console.log(`d: ${d}`);
  23. const factoryAddress = await spacefiRouter.methods.factory().call();
  24. console.log(`factoryAddress: ${factoryAddress}`);
  25. const factory = new web3.eth.Contract(spacefiFactoryAbi, factoryAddress);
  26. const pairAddress = await factory.methods.getPair(wethAddress, usdcAddress).call();
  27. console.log(`pairAddress: ${pairAddress}`);
  28. const pair = new web3.eth.Contract(spacefiPairAbi, pairAddress);
  29. const reserves = await pair.methods.getReserves().call();
  30. const amountOut = await spacefiRouter.methods
  31. .quote(value.toHexString(), d ^ inputEth ? reserves[1] : reserves[0], d ^ inputEth ? reserves[0] : reserves[1])
  32. .call();
  33. console.log(`out: ${ethers.utils.formatUnits(amountOut, 6)}`);
  34. const addLiquidity = await spacefiRouter.methods.addLiquidityETH(
  35. usdcAddress,
  36. amountOut,
  37. 0,
  38. 0,
  39. wallet.address,
  40. Math.floor(new Date().getTime() / 1000 + 60 * 30) + ""
  41. );
  42. const gasLimit = await addLiquidity.estimateGas({ from: wallet.address, value: value.toHexString() });
  43. console.log(`gasLimit: ${gasLimit}`);
  44. const tx = await wallet.sendTransaction({
  45. to: spaceFiRouterAddress,
  46. data: addLiquidity.encodeABI(),
  47. value: value.toHexString(),
  48. gasLimit,
  49. });
  50. console.log(tx);