Interact with Smart Contracts in React w/ Web3.js | Beginner Web3 Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys so in this video i'll be showing you how you can interact with the blockchain from your web app whether that's using react vue angular or whatever other library framework you're using but definitely react so let's get into it right now what i have here is a very basic create reactor and the first thing that we're going to do is actually go ahead and install a library called web 3 so just go ahead and type npm install web 3. so what web 3 does is it's essentially a collection of libraries that make it easier to just do blockchain stuff for example you can use it to check if a given string is a valid ethereum address or maybe sign a message with a private key and it also makes interacting with contracts a lot easier it will take care of encoding decoding all different calls and transactions for you and just to clarify i will be mainly referring to ethereum but this whole thing actually applies to layer 2 solutions and side chains like finance smart chain and by the end of this video there's no reason why you shouldn't be able to go to a16z and raise 200 million dollars in bitcoin funding for your revolutionary d5 startup so let's get into it so let's go ahead and uh into our just up component for now and put down a use effect just to start off and now let's begin with the web 3 so we have const web 3 and new web 3. and here you will be passing your provider url and this is a link to your ethereum node this node is basically your gateway to the rest of the network but don't worry you won't need to actually set up your own node and host on something like aws or anything luckily there's many services like in fiora that already do all that for you and all you'll be needing is a link from them so you just paste the link here and you're ready to go so we have cons to provide a url and you typically be storing this as an environment variable so you can do provide a url also in this video i will be showing you two different scenarios that you may be facing so let me show you the first one to begin with so in this case you will have your own smart contracts um that you will deploy using truffle or something which is what i'm using so here we have a very simple nft contract that will be deployed to the local ganache instance which is a local blockchain that you can use for testing purposes so we'll be going here and npx ganache cli and that's it now we have a local blockchain running on our device so let's deploy the contract first so what we'll do is mpx truffle migrate what truffle will now do is we'll compile the contracts and create this json file inside the build slash contracts directory this json file now contains a lot of information most of it you won't be using but this file also contains the address your contract was deployed to along with the abi which is something i'll get to very soon so now we've deployed the contract as we can see we have this build json file so we can go back to our app so we have the provider url but if we're going to be only testing locally we can add a string like localhost 8545. eight five four five this is the port that ganache will be running out okay so now we have a provider set up and provide a url perfect okay so now the thing with um decentralized applications is that your users will need a wallet to actually sign the transactions and other stuff and the most popular out of all these wallets is of course meta mask which if your users are quite familiar with crypto and the blockchain space they will probably already have it installed as a chrome extension but if your users are not very familiar with crypto and blockchain stuff you can use many services like fortmatic what they do is they will give your users a wallet without having anything installed in this video i will only be showing you how to integrate metamask but once you have learned that the steps for other wallets should also be quite similar so what metamask does is it injects itself into the browser so when you make any transactions or calls you will be dealing with metamask itself and not with your provider and by the way metamask itself uses infiora in the background but you will never be interacting directly with them you'll be dealing with metamask or whatever or the wallet service you're using so how do we go on about integrating metamask first we will check if metamask is actually installed so window and dot ethereum as i said metamask injects itself into the browser so you will be able to access it through the window object so if type of provider is not undefined so the provider has been injected that means metamask is installed the next step is to ask the user to connect their wallet to the website and the way we do that is we will send this request to the provider uh to get access to the accounts of the user and then because this is a promise we wait for the response for now we'll just log the accounts also let's just catch the error console log very simple for now like so save and now let's run this okay so if we go to our web app now 3000 now we will be prompted with this metamask connection dialog so we will select the account that we want to use press next connect and there we go so if we check the console now there will be an array and this is the account it won't show all the accounts only the one that's connected and selected so we want to go back to our code and take the provider and pass it to our web 3 instance now we can use our web 3 instance to make calls transactions and kill stuff like that also we can get rid of this url now because metamask will be handling everything for us in fact even the network selection will be done right here right now we're on mainnet but we can go to localhost because that's what we will be using for today okay so here's something else we can do now we can listen to metamask account changes so if we add this event listener console log accounts save so metamask if i change my account now to this i'm going to connect it first and yeah so as you can see there's another output in the console this is the other account so every time i change it there's a new output so with just these few lines of code we've already linked metamask and we can now start interacting with smart contracts but first we will need to do some tidying up because this code isn't very reusable and it doesn't look good so web3 client.js i'll create this new file you can name it whatever you want so here we can go export const init and we can take this code from our up component and paste it here let's declare this new variable let's selected account okay so every time we select a account we assign it to this variable selected account is selected account and now we can do the same thing just a lot better so rob three and in here we'll do this save web3 is not defined of course import web 3 from web 3 there we go save yeah let's check selected account is this now account three change to change again yeah okay so now it's time to actually define the contracts okay so this is the first scenario we will use the contract i showed you guys earlier so new web3.eth contract and in here we will be using the file inside here the json file and to do that we will be importing that nft contract build whatever you want to call it from um truffle build contracts nfp.json okay so we have this contract we do that and then avi the api part is what we're interested in and also the second parameter is the address of the contract we can also get that from the same file but first we will need to get the network id for the current network so awaits a web 3 eth net once we have the network id we can use nft contract dot networks i think that's what it is net id network id and address that should give us the address and of course we will need to make this function async okay so you get this so we get this error message it says you attempted to import this which falls outside of the project src directory and if you use create react app to create the application then what you will need to do is go into your dependencies for react and add a new dependency you can call it something like contracts and then we'll do sorry file truffle build contracts truffle build contracts now let's exit the application npm install okay and now in here we can all we can just do contracts which is the name we defined here we can just treat it as another dependency so contracts and then just nfv.json let's save this npm start okay so now that issue has been resolved that was quite simple by the way you don't need to do it this way you could simply copy the file from build and paste it in the src directory and access it that way but if you do it that way every time you deploy the contract locally or to a network you will need to copy each time copy and paste each time because your copied file won't contain the latest address and deployment details okay so now we have this and what was the error message we again cannot access nft contract before initialization here we need nfp contract build yeah so that's all set now we can do different things with the nfd contract let's declare it here instead mft contract and then assign here because we'll create another function with this contract all we're going to do is just mint a new token it's just fun showing you guys so we'll do mint token we'll take the nft contract dot methods so once you have the contract to access methods you do methods and then dot and then this will be the actual function that you have in your contract in this case it's just a function mint and it takes one parameter which is the owner we go back here methods dot mint and here we can add the selected account that we have over here which we get from metamask now we have that selected account and then we use send and now here we'll also specify the from this is the account that will be actually sending the transaction by the way this can be different this is just a account that sends the transaction and this is the account that will be owning the minted token in this case so we will return this and yeah now let's go back into our app component let's do some more stuff so const minted segmented this will just be a boolean value use state false if it's not minted we will have a button that says mint token and on click we will mint however if it's already minted then we'll display a simple message like token minted successfully okay so we import mint token from our web3 client file and we create a new function called means over here this will call means token dot and then because this is a promise we will also add a then tx this will return the transaction details and then catch for any errors i mean token console log clip transaction and we will also set minted to true yes let's go back to our application and now we have mint token and let's try pressing it um we will need to first initialize we didn't initialize the actual contract we just went straight to main token so first we check if let's create a variable over here let it is initialized it's false and once we have it be initialized we'll set it initialize equals true and also if there's an error over here it will just return so if it's not initialized we will await the initialization of it and let's make this easy going back to the browser let's try again mint token there we go so now metamask pops up with the asks us to actually approve the transaction and send it however there's a problem we don't have any ether so before we can send any transactions we need to have some ether to pay the gas fees so we'll reject it for now and let's go back now because i'm using ganache it's just for testing purposes i can go up to when i started ganache and i can find my private key so this private key i can add it to metamask and go here import account paste and import now i magically have 99 ether that's because when i start ganache it will automatically generate 10 i think it's 10 10 accounts and each of them will have 100 ether by default it's not exactly 100 because i paid some gas fee to actually deploy the contract and now this is what's left because this was a new account let's link it to the web app and yes that's sorted if i go to something like mainnet i will actually need to buy real ether which i won't be doing for this tutorial but let's just go to localhost and try the transaction again and yes um no errors and let me just open up the console here and these are the logs from ganache let's just keep an eye on them and if i confirm and we have the transaction hash this is all the transaction details events there was a transfer event which is emitted by the erc721 uh contract i used um transfer raw return values you also see the token id to from everything so also if we go back to vs code we can see here that there was a transaction and yeah we have token minted successfully and that was pretty much it we just used web3 to transact with a real smart contract now let's move on to scenario number two in this scenario you won't actually be deploying the contracts yourself you might want to interact with a contract that's already been deployed by maybe someone else so let's see how we would go on about that okay so for this the contract that we'll be using is the die stablecoin contract deployed to a test network i already have the address of this contract and i just want to see my balance through my own app and i know that the die contract is actually a erc20 contract and which i can see on ether scan and yeah so it's a erc20 contract let's do some more stuff so here nft contract and let's also have an erc20 contract here erc 20 contract okay so now we run into somewhat of an issue we don't or we don't really have the build file for this because it's not our contract but that's perfectly fine i mean we don't necessarily need it we just need the api that's contained in this json file so the api is just a description of the functions of the contract but we don't need all of it for example if we look at the abi for this it's actually quite big i mean that's that's a lot of information the thing is we don't need all the all the functions we just needed this one function mint and just like that for the erc20 contract we only need the balance off function that's the function that we will be calling so let's erc 20 avi and this will be an array and then inside there will be an object okay so now i don't really know the actual api so i'm just going to go on google type erc20 api if it uses a popular standard like erc20 it should be quite simple just finding it online so we can just click on this one and there we go that's the whole api that's everything we need actually it's more than what we need so we just need the balance off function i'm going to copy this and paste it here and there we go we have the avi here we do erc20 abi and now all we need is the address which i already have because i found it online so i'm just gonna paste that here and now we have the contract for the erc20 and we can interact with it export const and get own balance and here we go return erc20 contract again methods balance off by the way you can go here into the api and you can see the actual arguments that it takes in so we have the address type address and that's the only one that it takes and here's the output which is an integer inside integer and it's the actual balance so methods balance off and we pass in the selected account again and that's the account that we want to balance off and then dot call now okay let's try this out go back to our get up component import to get on balance and fetch balance now let's comment all this out related to minting because that's going to cause some problems as we're going to be using two different networks if you add all the error handling and stuff then it's fine i mean then you can use as many networks as you want but for the purpose of this tutorial we won't be adding any um error handling and stuff so let's just comment out this okay so that should be good enough so we go here type balance set balance and we'll initially set this to zero okay so let's go here we have let's have your balance is balance and then down here we'll have a button that says refresh balance and on click we will go ahead and fetch the balance and here we'll have to get on balance that we imported from web3 client and because again this is a promise just like before all calls and transactions are asynchronous so we will use then get the balance inside balance and also add a catch function okay so let's save this and go to the web app now if we refresh refresh balance and we get this error cannot read properties up undefined oh yeah of course so just like we did before for this transaction we need to actually initialize the web3 instance and set up the contracts properly so let's try again okay so now the problem is um it does work i'll get to why that's so long just just in a bit but we the first time we get an error and that's because here we set up everything but in the background web 3 is still trying to connect to the provider and set up the contract and to fix that problem what we can do is just keep this because this will await until the network until we have the network id and if we test it now again refresh curve balance and there we go that's fixed now why do we have such a long number if we look here in metamask the actual amount should be 82 but here we have something that starts with 82 ball then has a long list of numbers but that's just how most erc20 contracts work not all of them just most it's just a convention they have like something like 18 decimal places and to sort of fix that what we can do is here in the call we can add then get the balance here and then let's use web3 again to convert from we i think that's how you pronounce it balance to uh the more standard unit so let's save this and check it out actually there's an error web 3 is not defined we're using this over here there's import so that's capital so that should be capital w save let's check it out so refresh balance and there we go it's 2.023 now we have that decimal place so yes okay so that's pretty much it we've learned quite a bit i think we've learned how to make calls to contracts but also how to send transactions how we can use contracts that we deploy ourselves but also the ones that have already been deployed you may have the avi or you may not have the api we also explored how you can connect with metamask and what it does and all that stuff yeah you should be able to so just go and raise some funding
Info
Channel: HUSNAiN
Views: 18,229
Rating: undefined out of 5
Keywords:
Id: h9PdvEDuZS8
Channel Id: undefined
Length: 24min 54sec (1494 seconds)
Published: Tue Sep 21 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.