Ask Your Question
3

How to execute a smart contract function using web3.js?

asked 2022-04-30 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-12-12 09:00:00 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-30 11:00:00 +0000

Seen: 11 times

Last updated: Dec 12 '21