003 S05L03-Using-Web3Js-to-Interact-with-Smart-Contracts
003 S05L03-Using-Web3Js-to-Interact-with-Smart-Contracts
contract SomeContract {
uint public myUint = 10;
function setUint(uint _myUint) public {
myUint = _myUint;
}
}
Choose the Web3-Provider in Remix! Port 7545 if you are using Ganache
Start the NodeJS environment by typing in “node” in your terminal or command line
Use web3.js to interact with your Smart Contract on a very low level.
Now we know that 0x06540f7e sent as data field is interacting with the function “myUint” -- by why?
The encoding happens in a very specific way: It’s the first 4 bytes of the keccak hash of the function
signature.
Give it a try in node where we have access to web3.utils.sha3 which give us the keccak hash:
web3.utils.sha3("myUint()");
Which gives:
'0x06540f7eac53ad8a460dca00c89ac4438982ca36ff3248355f14b688948f672a'
web3.utils.sha3("myUint()").substr(0,10);
The result is exactly our data-field. We need this because in the compiled bytecode of our smart contract
there is no “myUint()” as a function definition. Instead it’s a jump statement to the right position in the
code! And this is the function definition.
Whenever we interact with our smart contract from outside, we need to know the function names to
generate these signatures as data-fields. This is where the ABI array comes in. The Application Binary
Interface is a json encoded array with all the information needed to encode the data field the right way.
Let’s use the ABI Array now to interact in an easier way with our smart contract.
myContract.methods.myUint().call().then(console.log).catch(console.error);
Now let’s update the uint and call it again afterwards. But for this we must actually send off a transaction
to our ganache. Web3 doesn’t know which is the account we want to send the transaction from, so we
have to set this first:
Then, once the transaction is mined (on Ganache instantaneously, but on a real network it might take 10-
20 seconds), we read out the updated value.
myContract.methods.setUint(50).send({from:
'FIRST_ACCOUNT_FROM_GANACHE'}).then(result => {console.log(result);
myContract.methods.myUint().call().then(console.log);}).catch(console.error);
No matter how complicated the smart contract is, with the ABI Array and Web3 you can easily interact
with it. You will see later that it’s all just like calling a JavaScript function and all the technical part is
abstracted away from you.
FULL COURSE:
https://www.udemy.com/course/blockchain-developer/?referralCode=E8611DF99D7E491DFD96