How do you take the number of input tokens when I metamask is integrated?



  • I have the following block: введите сюда описание изображения

    The code included in Metamask:

        const ethereumButton = document.querySelector('.enableEthereumButton');
    const sendEthButton = document.querySelector('.sendEthButton');
    

    let accounts = [];

    //Sending Ethereum to an address
    sendEthButton.addEventListener('click', () => {
    ethereum
    .request({
    method: 'eth_sendTransaction',
    params: [
    {
    from: accounts[0],
    to: '0x2f318C334780961FB129D2a6c30D0763d9a5C970',
    value: '0x29a2241af62c0000',
    gasPrice: '0x09184e72a000',
    gas: '0x2710',
    },
    ],
    })
    .then((txHash) => console.log(txHash))
    .catch((error) => console.error);
    });

    ethereumButton.addEventListener('click', () => {
    getAccount();
    });

    async function getAccount() {
    accounts = await ethereum.request({ method: 'eth_requestAccounts' });
    }

    I need the user to take the number of tokens into shape, and after the button of the purchase has been pressed, the token ring has already been chosen.

    Question: How do you do that?



  • All records https://docs.metamask.io/guide/sending-transactions.html#transaction-parameters

    sendEthButton.addEventListener('click', () => {
            const decimals = 18; // decimals для ETH
            const amount = 2; // кол-во эфира, которое нужно отправить
            const amountWithDecimals = amount * Math.pow(10, decimals) // кол-во токенов с учетом decimals
            const value = amountWithDecimals.toString(16); // превращаем в Hex
            window.ethereum
                .request({
                    method: 'eth_sendTransaction',
                    params: [
                        {
                            from: accounts[0],
                            to: '0x104017c4B28fBFd4A789d2B8b0E872562E3139f5',
                            value: value,
                            gasPrice: '0x09184e72a000',
                            gas: '0x2710',
                        },
                    ],
                })
                .then((txHash) => console.log(txHash))
                .catch((error) => console.error);
        });
    

    Important comments for the future:

    1. Better use the library for the math of calculations. https://github.com/indutny/bn.js/ to eliminate errors of type 0.1 + 0.2 = 0.30000004 in js. Or else to choose https://mikemcl.github.io/bignumber.js/ For example.
    2. Look at the library. https://web3js.readthedocs.io/en/v1.5.2/ ♪ In the future, it would be easier to scale the annex.
    3. The formula amount * Math.pow(10, decimals) may be used for any token other than ETH. You really need a ready-to-be contract for that.

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2