[Ethereum] How to send correct SwapExactEthForTokens params types on ethers/web3.js

contract-deploymentethers.jspancakeswaptransactionsweb3js

I need to know how to send correct paramaters / paramater types as in what does the parameter type has to be is it a hex number , a string ?
help would be massively appreciated.
Notes:

1)i cant set value in trade (object sent with value and gasPrice) to 1 bnb in wei i get an error that its a bignumber.

2)sometimes the code actually works and i get a hashcode but this hashcode doesnt yield any information of an existing transaction at all.

I imported pancake swaps router functions like this :

const router = new ethers.Contract('0x10ED43C718714eb63d5aA57B78B54704E256024E', [
'function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) 
 external virtual override payable returns (uint[] memory amounts)',
'function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns 
(uint[] memory amounts)'], account);

Then I proceeded to use these functions to pull a trade with the following code :

const init = async () => {
desiredCoin = '0x0231f91e02DebD20345Ae8AB7D71A41f8E140cE7';
bnb = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c';
const pairAddress = [bnb, desiredCoin];
//use https://bscscan.com/unitconverter to input bnb amount.
const amountIn = 1
amounts = await router.getAmountsOut(
    amountIn,
    pairAddress
);
amountOutMin = amounts[1].sub(amounts[1].div(slippage)); //slipapge set here 
console.log('Calculated Amounts out: ' + amountOutMin);
const to = bnbwalletAdress;
const deadline = Math.floor(Date.now() / 1000) + 60 * 10; //this represents 10 mins of deadline, change to ur liking.
const tx = await router.swapExactETHForTokens(
    amountOutMin,
    pairAddress,
    to,
    deadline,
    {value: 1, gasPrice: 10e9}
)
console.log('Transaction Submitted, heres the hashcode '+ tx.hash)
receipt = await tx.wait();
console.log(receipt);
}

Best Answer

Answer for Q1

If not specified, usually the value is in "wei".

So "1 ether" would be 1000000000000000000 wei.

You can use web3.utils to convert "ether"->"wei". web3.utils.toWei('0.01', 'ether')

Related Topic