To send a token using web3.js, you need to use the transfer function of the token smart contract. Here’s a simple example code demonstrating how to send a token using web3.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | // Import the web3.js library const { Web3 } = require('web3'); // Connect to an Ethereum node const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'); // Sender's account private key const senderPrivateKey = 'YOUR_SENDER_PRIVATE_KEY'; // Token contract address and ABI const tokenAddress = '0xYourTokenContractAddress'; // Replace with your token smart contract address const tokenABI = [...]; // Replace with your token smart contract ABI // Receiver's address const receiverAddress = '0xReceiverAddress'; // Replace with the receiver's address // Create a token contract instance const tokenContract = new web3.eth.Contract(tokenABI, tokenAddress); // Create an account with the private key const senderAccount = web3.eth.accounts.privateKeyToAccount(senderPrivateKey); // Build transaction parameters const transferAmount = web3.utils.toWei('10', 'ether'); // Replace with the amount of tokens you want to send const gasPrice = '1000000000'; // Replace with an appropriate gas price const gasLimit = '50000'; // Replace with an appropriate gas limit const txParams = { from: senderAccount.address, to: tokenAddress, gas: gasLimit, gasPrice: gasPrice, data: tokenContract.methods.transfer(receiverAddress, transferAmount).encodeABI(), nonce: null, // Replace with an appropriate nonce value }; // Sign the transaction web3.eth.accounts.signTransaction(txParams, senderPrivateKey) .then((signedTx) => { // Send the signed transaction return web3.eth.sendSignedTransaction(signedTx.rawTransaction); }) .then((receipt) => { console.log(Transaction Hash: ${receipt.transactionHash}); console.log(Transaction successful!); }) .catch((error) => { console.error(Error sending tokens: ${error}); }); |
Make sure to replace the following in the sample code:
-
‘https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID’: Replace with the URL of your Ethereum node provider.
-
‘0xYourTokenContractAddress’: Replace with the actual address of your token smart contract.
-
tokenABI: Replace with the ABI of your token smart contract.
-
‘YOUR_SENDER_PRIVATE_KEY’: Replace with the private key of the sender’s account.
-
‘0xReceiverAddress’: Replace with the Ethereum address of the receiver.
-
transferAmount: Replace with the amount of tokens you want to send (in Wei).
-
gasPrice and gasLimit: Replace with appropriate gas price and gas limit.
This code connects to the Ethereum network, creates a token contract instance, builds transaction parameters, signs the transaction, and sends the tokens to the receiver’s address. Please handle private keys with care and ensure you have enough Ether to cover the gas fees.