Ask Your Question

Revision history [back]

To execute a smart contract function using web3.js, follow these steps:

  1. Set up your web3 provider and instantiate your contract:
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/your-project-id');

const abi = [...]; // the ABI of your contract
const contractAddress = '0x...'; // the address of your contract
const contract = new web3.eth.Contract(abi, contractAddress);
  1. Call the smart contract function you want to execute:
const methodName = 'myFunction'; // the name of your contract function
const parameter1 = 42; // the first parameter of your function
const parameter2 = 'hello'; // the second parameter of your function

contract.methods[methodName](parameter1, parameter2).send({from: '0x...'}).then(function(receipt) {
    console.log('Transaction receipt:', receipt);
}).catch(function(error) {
    console.error('Error:', error);
});

This will send a transaction to the Ethereum network to execute your smart contract function. The send() method returns a promise that resolves to a transaction receipt containing information about the transaction. If an error occurs, the catch() method will be called with an error object.