5

Which function will I use in web3.js for buying erc20 token from my website?

1 Answers1

4

It depends on your web3 version. if you are using 1.2.1

You first need to create a raw transaction and then sign it with your private key. Once you have signed transaction with you, you can use the sendSignedTransaction method to send transaction to the blockchain. Refer this

For a raw transaction, you need to send some ether (depends on token price and token value you want to purchase). The token contract will be using the payable function to receive ether on the smart contract.

Once the smart contract receives the amount the sending address will get the desired amount of tokens.

The other option would be by using MetaMask Extension

iAmADeveloper
  • 647
  • 3
  • 9
  • Are gas, gasPrice, and value parameters expected to be given in eth or wei? and should it be hex ? – 0xD1x0n Oct 31 '20 at 04:33
  • 1
    it should be in wei and you can represent this value in hex. – iAmADeveloper Nov 06 '20 at 06:09
  • 1
    so im specifically interested in how Selling works. What contract address do i use to sell a specific token for eth (aka the 'to' field)? I am able to purchase tokens at this point. not sure how to apply the function in a selling scenario though – 0xD1x0n Nov 06 '20 at 16:46
  • @Fadolphin did you succeed to sell ? i'm asking myself same question – Valentin Garreau Feb 02 '21 at 22:31
  • @ValentinGarreau I haven't attempted it yet. i got buying to work tho! – 0xD1x0n Mar 06 '21 at 01:31
  • I've been running a sniping bot for a while now and sofar ethers.js is much easier todo transactions with (Buys and sells). The only drawback is that errors are not well fleshed out so "cannot estimate gas" tends to be the error for incorrect decimal places or insufficient balance or NoSell coins. – Yugenswitch Jan 16 '22 at 08:53