| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- import base, { ChainId } from "iziswap-sdk/lib/base/index.js";
- import Web3 from "web3";
- import { BigNumber } from "bignumber.js";
- import quoter from "iziswap-sdk/lib/quoter/index.js";
- import swap from "iziswap-sdk/lib/swap/index.js";
- import token from "iziswap-sdk/lib/base/token/index.js";
- import { Wallet, Provider } from "zksync-web3";
- const rpc = "https://zksync2-testnet.zksync.dev/";
- const privateKey = "0xd768b0b3f8dedcb465ad680268453391f7da6ec4e1942a13fdfcdea8773aab3e";
- const quoterAddress = "0xE93D1d35a63f7C6b51ef46a27434375761a7Db28";
- const swapAddress = "0x3040EE148D09e5B92956a64CDC78b49f48C0cDdc";
- const fromTokenAddress = "0x0faF6df7054946141266420b43783387A78d82A9";
- const swapAmount = 100;
- const chain = base.initialChainTable[ChainId.ZkSyncAlphaTest];
- console.log("rpc: ", rpc);
- const web3 = new Web3(new Web3.providers.HttpProvider(rpc));
- const account = web3.eth.accounts.privateKeyToAccount(privateKey);
- console.log("address: ", account.address);
- const fromToken = await token.fetchToken(fromTokenAddress, chain, web3);
- console.log("fromToken: ", fromToken);
- const toToken = base.getGasToken(base.ChainId.ZkSyncAlphaTest);
- console.log("toToken: ", toToken);
- const quoterContract = quoter.getQuoterContract(quoterAddress, web3);
- const payAmount = new BigNumber(swapAmount).times(10 ** fromToken.decimal);
- const fee = 2000; // 2000 means 0.2%
- const params = {
- // pay testA to buy testB
- tokenChain: [fromToken, toToken],
- feeChain: [fee],
- inputAmount: payAmount.toFixed(0),
- };
- const { outputAmount } = await quoter.quoterSwapChainWithExactInput(quoterContract, params);
- const receiveAmount = outputAmount;
- const receiveAmountDecimal = token.amount2Decimal(new BigNumber(receiveAmount), toToken);
- console.log(fromToken.symbol + " to pay: ", swapAmount);
- console.log(toToken.symbol + " to acquire: ", receiveAmountDecimal);
- const swapContract = swap.getSwapContract(swapAddress, web3);
- const swapParams = {
- ...params,
- // slippery is 1.5%
- minOutputAmount: new BigNumber(receiveAmount).times(0.985).toFixed(0),
- strictERC20Token: false,
- };
- const { swapCalling, options } = swap.getSwapChainWithExactInputCall(swapContract, account.address, chain, swapParams);
- const gasLimit = await swapCalling.estimateGas(options);
- console.log("gas limit: ", gasLimit);
- const provider = new Provider(rpc);
- const wallet = new Wallet(privateKey).connect(provider);
- const tx = await wallet.sendTransaction({
- value: Web3.utils.numberToHex(options.value),
- data: swapCalling.arguments[0][0],
- to: swapAddress,
- gasLimit,
- });
- console.log(JSON.stringify(tx, null, 4));
|