Skip to content

Instantly share code, notes, and snippets.

@romain130492
Last active November 27, 2021 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romain130492/6c3bddb7031789ee381a3f1714c896d7 to your computer and use it in GitHub Desktop.
Save romain130492/6c3bddb7031789ee381a3f1714c896d7 to your computer and use it in GitHub Desktop.
Transaction-ethereum-smart-contract
var Web3 = require("web3");
// TO make a transaction from a wallet address to a smart contract address
// The smart contract has a function called : `set()`, which set a value to the data for the variable called : `data`
const init2 = async () => {
try {
const provider = new Web3.providers.HttpProvider(endPoint); // https://ropsten.infura.io/v3/ROPSTEN_API_KEY
web3 = new Web3(provider);
web3.eth.handleRevert = true;
let testContract = await new web3.eth.Contract(abi, addressOfContract); //abi = smart contract JSON
web3.eth.accounts.wallet.add(privateKey); // Wallet privateKey (mine, with some token on it to pay the gaz.)
const tx = testContract.methods.set(2); // set() is a method I made on the smart contract
const gas = await tx.estimateGas({ from: address }); // my public wallet address
const gasPrice = await web3.eth.getGasPrice();
const data = tx.encodeABI();
const nonce = await web3.eth.getTransactionCount(address);
const txData = {
from: address,
to: addressOfContract,
data: data,
gas,
gasPrice,
nonce,
//chain: "ropsten",
//hardfork: "istanbul", About hardfork: https://www.investopedia.com/terms/h/hard-fork.asp
};
console.log(`Old data value: ${await testContract.methods.get().call()}`); // Method to call the other method of the contract : `get()`, which gives me the current `data` variable.
const receipt = await web3.eth.sendTransaction(txData);
console.log(`Transaction hash: ${receipt.transactionHash}`); // We can check the transaction online with that hash at : https://ropsten.etherscan.io/tx/
console.log(`New data value: ${await testContract.methods.get().call()}`);
} catch (error) {
console.log(error, "error init2()");
}
};
init2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment