Connect a Frontend to Smart Contract on Binance Smart Chain (Javascript to Solidity)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
after you deploy a smart contract on binance smart chain if you want to interact with it you need to use the command line not very user friendly that's why you need to build a nice frontend interface but in the front end we use javascript and in a smart contract we use solidity how can we connect them there is a way and that's what i'm going to show you in this video hey if you don't know me i'm julian and on ether blocks i teach blockchain development in your blockchain application also called decentralized application or dab we have two main parts the smart contract which runs on binance watching and the front-end which runs in a web browser of the user the software that runs the binance smart chain is called a client the client exposes the spot contract functionality with an api in this api there are several endpoints for interacting with our smart contract we will use two endpoints if send transaction to modify data and if call to read data from the smart contract on the front end we will have a web page with html css and javascript this is the javascript code that will interact with the smart contract we could use javascript directly to interact with the api of binance matching but it would be too much work the two endpoints we are going to use it send transaction and it call requires a specific encoding for the parameters and it would be too much of a hassle to deal with this instead we are going to use a javascript library to do the heavy lifting there are two options web 3 and ethers web 3 is older ethers is newer has a more simple api and is getting way more traction so we will use ethers but it doesn't matter if later you prefer to use web3 ethers is going to send an http request across the internet until it reaches the api of banyan's smart chin the request will then be sent to the evm or ethereum virtual machine which will execute our request and finally we will have a response sent back to the front end another very important part is the wallet of the user on the front end technically it's not part of our blockchain app but we still need to interact with it it's usually a chrome extension like metamask but it can also be a mobile wallet or a hardware wallet this wallet is used when we want to send a transaction to the smart contract the wallet has the private keys of the user and will sign transaction before they are sent to the binance machine one very important detail is that the private key never leaves the wallet our blockchain app will never have access to these keys the javascript code will just ask the wallet hey i want to send this transaction can you confirm with the user that he or she agrees to sign his transaction the wallet will then show a pop-up to the user and only if the user agrees the transaction will be signed and sent to the blockchain okay so that's it for the overview of how to connect a front-end to a smart contract next we are going to start the coding [Music] so for our project we're going to use a very simple smart contract so this is a truffle project and in a contracts folder i've created a very simple spot contract so it just has a single integer variable and it has two functions a function to update the variable and a function to read this variable and in our front end we're going to connect to this smart contract and call these two functions and we also have a deployment script super simple we just deployed our smart contract and that's it then in the truffle config file i've defined a couple of things so first we import hd wallet provider of truffle then here you have to copy paste your mnemonic phrase to generate an address then here so i've added this to customize the directory where we create the build artifact of truffle so this is for the front end and i've added a network here for abandoned smart chain so i pass in the mnemonic and i put the url to the balance smudge and test net so after with the first address generated by this mnemonic you gotta go to the first set of the balance margin test net get some test net bnb tokens because we're going to do some transaction and you need this token to pay for them and after at the root of the project so i've already run npm install to install all the dependencies and after we are going to deploy this by contract to binding smart chain so truffle migrate reset and then we specify the network that we created in truffle config banning smart chain all right our smart contract is deployed and in the next section we're gonna start the front end [Music] the first step in your front tank is to connect to the wallet of the user so there are many wallet available for banning smart chain but one of the most used one is meta mask which is also very used for ethereum so here in our project we'll go to front and we'll go to src that's where we have the javascript file and we do the integration with metamask in ethereum.js so let's see how it works so we are going to export a function from this file get blockchain and this function is going to return a javascript object that points to our smart contract on the blockchain but before we can create this object there are a couple of steps so first we are going to call this function detect ethereum provider it's going to return a provider object and this is related to metamask and we get this function from a package of metamask minima slash detect provider so this package is not too complicated so we can check out its code in github to understand what's happening so we go in src index dot screen and here we see this function detect ethereum provider so here the interesting action happened here so first if metamask was already loaded in our page it's going to inject this object window.ethereum so we're going to return this object by calling this function we're going to see this function just after otherwise if metamask has not been injected yet then we are going to add this event listener to window so when metamask is injected it's going to emit this event ethereum initialized and when this event is fired then we're gonna call handle ethereum and finally we have a set timeout so if metamask is not injected in a certain time we're gonna call handle ethereum that's going to throw an error meaning that we don't have metamask installed so after when you see this function handle ethereum which concludes the process so first of all we remove the event lessener and here if we have found ethereum in window.ethereum then we return this object otherwise that means we were not able to connect to metamask so we console log an error and we return nothing so there are other details in the code but what i explained here is the most important so then back in our code so here we get the provider which is basically window.ethereum object exported by metamask and if we have this provider we're going to connect to the blockchain so first we need to ask the user to give us access to its metamask address so before it used to be a function called enable but it has been deprecated now you need to call the request method and for the method we're going to specify if request accounts so the user is going to see a pop-up that say hey do you want to allow this dap to connect to your wallet and if you refuse the dap won't even be able to know what is the address of the user and this is a safety mechanism to protect the privacy of user so normally the user will accept and after we going to ask the network id to which metamask is connected so before we were able to directly get this on the window.ethereum object exported by metamask but the api also was deprecated so now we need to call this method and after we're gonna initialize a connection to the blockchain with the ethers library so i told you before that there are two libraries you connect to ethereum smart contract ethers and web three so here we import ethers from above and the way you instantiate a connection with ethers is you do ethers.providers.webstreetprovider we pass it the provider and here basically we overwrite the provider object so now it becomes an ethers provider then we get a signer object from ethers because we're going to need it to connect to a smart contract and after here it's very important we create an ether's contract object with which we will be able to interact with our smart contract so here contract uppercase also comes from ethers and it needs a couple of info first it needs the address of the smart contract so we've also imported a json file here simple storage.json and this is the json file that is produced by truffle when you compile and deploy your smart contract and it has a section with the address of the smart contract under the key networks each network key is indexed with the network id so we know the network id because metamask told us and after we can get the address with dot address we also need to know the api which is a json document that describes the solidity interface of our smart contract so we also get it in the json document of truffle and we also pass the signer object that we created just before this is very important this allows to send transaction and after we return a simple storage object and we stop the execution of the function and if we don't have a provider so this if here is not executed and instead we're gonna reject the promise with an error message that means the user doesn't have meta mask installed so just to be clear if you follow some of my tutorial before you may have noticed that this code i used before to connect to the blockchain was a little bit different so i've updated my code what you see here is the most up-to-date way to do it okay so this is a good first step for the front-end integration next we're gonna do the integration with our react application all right so let's see this integration with react so we are going to another file app dot js so this is our main react component so you don't have to use react in order to integrate with smart contract on binance matching but that's the most standard solution so i recommend to use react so first we import some object required for for react then we import the get blockchain function we defined just before and here we have our main component up so first we define the state of our component so this is some dynamic data related to our components so first we have the javascript object simple storage that allows to interact with our smart contract then data that's the value of the data variable in the smart contract so the first element of the array is the value itself and the second element is a function to update the data state so this u state thing this is related to react this is not specific to the blockchain so let me scroll down so when the component is first loaded so this if statement here is going to find that simple storage and data are undefined so we are going to return loading to the user then what's going to happen is that this code here is going to be executed so when the component first load the init function here is going to be executed so we're going to get the simple storage object from get blockchain then we are going to call the read data function on smart contract and we're going to get the value for the data variable then we are going to save our state so first we're going to save the simple storage object thanks to set simple storage and same thing for data and react after it sees that the state has been updated it's going to re-render the component so this time the if statement here this is not undefined so we're not going to have this branch executed but instead we're going to return this thing so here we render some html so the class here are related to bootstrap a css framework that i like to use could allow you to get some nice styling very easily but the main point here is to see how we can populate the data with javascript so that we see inside the curly braces so here we're going to render the data variable and since this is not going to be a javascript number but this is going to be an instance of big number this is javascript library to deal with really big numbers that are too big for javascript and in order to transform a javascript big number into a representation we can call the tostring function so this is to visualize the data and after to modify the data we're gonna have a form so here we have an input so that's where we're going to specify the new value for data then a button to submit the new value and when we click on submit it's going to fire the on submit event and we attached the update data function so we go up we go up and here we define this update data function so it's going to receive an even object from the web browser so we want to prevent the form from being submitted otherwise it's going to be a full page reload it's not what we want then we extract the value of the input thanks to this line then we're going to send the transaction to the smart contract so we use the simple storage object that is stored in the state of the component and we call update data and we pass the new value of data and we await this because this is an async operation that is sent to the network so then metamask is going to take over and show the user a pop-up to confirm the transaction the user is going to confirm this then we have a transaction object but at this stage the transaction is not mined yet it's just sent to the network we need to wait for a miner to mine our transaction and after we call the wait function and this is going to wait until the transaction is mined and after we need to update the state of our smart contract because the data variable was changed so now we call read data we have the new value of data and then we update our internal state and when react see that our internal state has been updated it's going to re-render our component so this is going to be re-render here with the new value of data so that's how we keep our component up to date okay so that's it for the front-end code and next we're going to do a demo [Music] the next video you're gonna need to install metamask in your browser and after when it's installed you will need to import the mnemonic phrase that you use in truffle config so just as a reminder before i mention in truffle config that you need to put a mnemonic phrase here and personally i just use the one that is generated by the truffle develop command so you put your mnemonic here and after when you have metamask installed you need to import this mnemonic phrase and you're going to select the first address that is generated with this mnemonic phrase and of course you also need to have some bnb test net token you can get some with the faucet of the bnb test net and after we're gonna start the front end so in another terminal window you go in front end you run npm install to install the dependency and after you run npm start to start the front-end server and since we already deploy our smart contract to the balance match and test net it exported the address images and document and this json document is imported by the front-end so that's how we can link the smart contract to the front-end so npm start he starts the front-end server it's going to take you to your browser it's going to load localhost colon 3000 and then you go to metamask and here you need to add a network for the balance matching test net so here this is cut off on my screen but you have to click on custom rpc and for the different parameters of the band inspection test net you can google it you'll find the apps url the chain id everything and once you have added this network you select it so me is bsc test net okay so here actually you can see the parameter um and yes i select bsc test net all right and by the way if you use the faux set properly then you should see that you have some bnb token here so even though it's a if this is actually bnb token uh and then after we're going to reload the front end and you should see this so we're going to change the data so for example we're going to put 10 click on submit we see the confirmation pop-up of metamask so we agree with the transaction we click on confirm we wait a little bit that the transaction is mine then you're going to see a notification of metamask and here automatically you can see the data that is updated and if we try to do it again for example five we confirm we wait a bit this is mine and the front end is automatically updated it works there are really a lot of moving parts when you want to connect a front front-end to a smart contract personally after having done some smart contract work and front-end integration i realized i prefer to work on smart contract because i find it more simple and it pays better but sometimes you have to do the front-end as well especially if you are in a small team and you will soon realize that working with metamask as a developer can be really annoying fortunately for you i've prepared this video where i give you my best tips to debug metamask i will see you there
Info
Channel: EatTheBlocks
Views: 30,744
Rating: undefined out of 5
Keywords:
Id: eCc_TyIETw8
Channel Id: undefined
Length: 19min 52sec (1192 seconds)
Published: Fri Mar 26 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.