Created
July 6, 2023 08:48
-
-
Save cokia/91291a0128526b31e76ab58b79991b77 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Web3 = require('web3'); | |
// Create a new instance of Web3 | |
const web3 = new Web3('YOUR_PROVIDER_URL'); | |
// Set the private key for your wallet | |
const privateKey = 'YOUR_PRIVATE_KEY'; | |
// Create an account from the private key | |
const account = web3.eth.accounts.privateKeyToAccount(privateKey); | |
// Unlock the account if necessary | |
web3.eth.personal.unlockAccount(account.address, 'YOUR_ACCOUNT_PASSWORD', 600) | |
.then(() => { | |
// ABI (Application Binary Interface) of the contract | |
const contractABI = [ | |
// Your ABI definition here | |
]; | |
// Address of the contract | |
const contractAddress = 'YOUR_CONTRACT_ADDRESS'; | |
// Create an instance of the contract | |
const contract = new web3.eth.Contract(contractABI, contractAddress); | |
// Customize your contract function call here | |
const functionName = 'YOUR_FUNCTION_NAME'; | |
const functionArguments = ['ARGUMENT_1', 'ARGUMENT_2']; | |
// Create the transaction object | |
const txObject = contract.methods[functionName](...functionArguments); | |
// Estimate the gas required for the transaction | |
txObject.estimateGas({ from: account.address }) | |
.then((gas) => { | |
// Set the gas limit for the transaction | |
const gasLimit = gas + 10000; | |
// Build the transaction object | |
const tx = { | |
from: account.address, | |
to: contractAddress, | |
gas: gasLimit, | |
data: txObject.encodeABI(), | |
}; | |
// Sign the transaction with the account's private key | |
return account.signTransaction(tx); | |
}) | |
.then((signedTx) => { | |
// Send the signed transaction | |
return web3.eth.sendSignedTransaction(signedTx.rawTransaction); | |
}) | |
.then((receipt) => { | |
console.log('Transaction successful!'); | |
console.log('Receipt:', receipt); | |
}) | |
.catch((error) => { | |
console.error('Error occurred:', error); | |
}); | |
}) | |
.catch((error) => { | |
console.error('Error occurred:', error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment