004 S05L04-Using-the-Browser-to-Interact-with-Smart-Contracts
004 S05L04-Using-the-Browser-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
Inside the root folder (where your node_modules folder is) create a new index.html file with the
following content:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>My Website</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='node_modules/web3.js-browser/build/web3.js'></script>
</head>
<body>
</body>
</html>
It should be a completely blank page. Then open the developer console in your browser (F12). And enter
a few commands to see if you can connect to Ganache:
undefined
web3.eth.getAccounts().then(console.log);
Promise {<pending>}
(10) ["0xeeEa556133B5C76a2b92e8Df8F0Ff90BbbbD8ce6",
"0xEddC05d9B2CB4D3965ee9d01C0c47960FAAbf273",
"0xD152FdAea0F5c39bD38Ce6c29312af14B93F40E3",
"0xf2Af5a487b989EcFd4F6310E2A964c1649C0CD43",
"0x4Fff1eD88e721140729fd3C179c807984bc70dfe",
"0xc0BBc1Eb8F66b494B08Ec843e12742c351499fDa",
"0x4AC266A48d587e541b6f6520246Ec1Fd94B9F6bd",
"0x0e369aEDD00dC0bcc3fa3ffF63A46fA5fDD55A4c",
"0x34C027923c8c3cE277E2aE8b0eadc4b7f486804c",
"0xAeC5b09f722d36622F811631493E60f7ce6dB4c4"]
Let’s do the same as we did before in the browser and see if it still works!
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);
This should give you the hex-value of 0x32. You can also convert it to a regular string with:
myContract.methods.myUint().call().then(result => {
console.log(result.toString());
});
So, we did the same as before on the console with the browser. What does that mean? There is a
standardized interface to “talk” to your smart contract.
FULL COURSE:
https://www.udemy.com/course/blockchain-developer/?referralCode=E8611DF99D7E491DFD96