Untitled

 avatar
Mike112
javascript
5 months ago
2.4 kB
12
Indexable
Never
import { Wallet, Contract, Web3Provider, Provider } from "zksync-web3";
import { ethers } from "ethers";
const provider = new Provider('https://mainnet.era.zksync.io');

async function execute(privateKey: string) {
    const wallet = new Wallet(privateKey).connect(provider);
    const abi = [
    {
        "constant": false,
        "inputs": [
          {
            "name": "amountOutMin",
            "type": "uint256"
          },
          {
            "name": "routes",
            "type": "tuple[]",
            "components": [
              {
                "name": "from",
                "type": "address"
              },
              {
                "name": "to",
                "type": "address"
              },
              {
                "name": "stable",
                "type": "bool"
              }
            ]
          },
          {
            "name": "to",
            "type": "address"
          },
          {
            "name": "deadline",
            "type": "uint256"
          }
        ],
        "name": "swapExactETHForTokens",
        "outputs": [
          {
            "name": "",
            "type": "uint256"
          }
        ],
        "payable": true,
        "stateMutability": "payable",
        "type": "function"
      }
      
    ];
    const contract = new Contract(
        '0xF29Eb540eEba673f8Fb6131a7C7403C8e4C3f143',
        abi,
        wallet
    );
    
    //parameters
    const amount = "0.02";  // ETH amount
    const amountOutMin = ethers.BigNumber.from('0x01f39516');  // This can be different depends on the Ether amount, To avoid errors, give it 0x0
    const routes = [
        {
            from: '0x5AEa5775959fBC2557Cc8789bC1bf90A239D9a91',  
            to: '0x3355df6D4c9C3035724Fd0e3914dE96A5a83aaf4',
            stable: false
        }
    ];
    const to = "0x5b6EDEf50b81c64C1bc1401D6dB7d5bd2A69CEc8";
    const deadline = Math.floor(Date.now() / 1000) + 60 * 20;  // 20 minutes deadline
    
    //run
    const parsedEthers = ethers.utils.parseEther(amount);

    const feeInGas = await contract.estimateGas.swapExactETHForTokens(
        amountOutMin, routes, to, deadline,
        {
            value: parsedEthers
        }
    );

    await contract.swapExactETHForTokens(
        amountOutMin, routes, to, deadline,
        {
            gasLimit: feeInGas,
            value: parsedEthers
        }
    )
}