how to swap tokens on uniswap using web3 js

I am trying to use uniswap contract method to simply swap eth for token, using eth from metamask wallet. Uniswap contract method is:

function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
  external
  payable
  returns (uint[] memory amounts);

My naive impression is that it should look something like this, but I am sure I am missing several crucial parts (like signing the transaction, use apropriate callback method) and I cannot find a full comprehensive example. How should a full working example look like?

const ETHaddress = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
const DAIaddress = "0x6b175474e89094c44da98b954eedeac495271d0f"

const routerContract = new web3.eth.Contract(
                  UniswapRouterABI,
                  "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
                );

routerContract.methods.swapExactETHForTokens(500,[ETHaddress,DAIaddress],myWalletAddress,someDeadline)
.send(from: myWalletAddress, value: "1000000000000")

58 thoughts on “how to swap tokens on uniswap using web3 js”

Leave a Comment