chainlink vrf coordinatorWeb3 Tutorial Project Build a web3js dApp with a Solidity lottery smart contract on Ethereum

The Dogecoin Foundation Allocates 5 Million Doge to the - Bitcoinist Dogecoin Foundation Announced A New Fund for Dogecoin Core Developers For a long time, Dogecoin has struggled with a lack of use cases. To attract more Ethereum Consultant Explains How $ETH Price Could Reach $100K Within 5 In #Ethereum On Saturday March 27, Ethereum engineering and strategy consultant Ryan Berckmans explained hw the price of Etheruem ETH could reach $100,000 within the next five years. Berckmans, formerly a Senior Engineer at Augur, explained why $100k is a realistic price target: chainlink vrf coordinator Web3 Tutorial Project Build a web3js dApp with a Solidity lottery smart contract on Ethereum
chainlink vrf coordinator The State of Ethereum: The... Web3 Tutorial Project Build a web3js dApp with a Solidity lottery smart contract on Ethereum
hey guys hows it going in this tutorial were going to be building a ui or front end for a lottery smart contract using the web3.js library now weve developed the lottery solidity smart contract that well be using in previous videos so if you havent seen those videos first i highly recommend you check those out or you could just download the completed smart contract code from github and proceed with building the ui here that would be totally fine as well the links to both are in the description below at the end of this tutorial well have a fully functioning lottery d-app or decentralized application running on the ethereum rinkeby test network so if that sounds good stick around and lets get right into it all right guys so before we get started on coding lets just go over a quick high level roadmap for this tutorial first well be creating a basic static ui using nexjs react.js and the bulma css library for a bit of styling help then well create a connect wallet button and add functionality to connect to the site using our metamask wallets after that well deploy the lottery smart contract to the ethereum test network using truffle finally well come back to our lottery front end application and build out the functionality needed to interact with the smart contract on ethereum using the web3.js library all right so lets set up the basic structure for our frontend application now the one prerequisite here is that you have to make sure that you have node.js installed on your system i recommend version 16 as thats the latest stable version at the time of this video you could probably get away with 17 or even 14 but id suggest shooting for 16. so you can just download that for your particular system and you may have to restart your machine before we start actually coding right so the next step we want to move into the folder or directory where you want to create your project and lets go ahead and open up a terminal window and the first thing im going to do is to create a new folder for our entire project so im going to say make directory lottery all right now im going to cd into that lottery directory and the next step is going to be to create the scaffolding for our next js application so we can we can say npx create next app at latest to ensure were getting the latest install files go ahead and press enter and it will prompt us for a name for our application so im going to say lottery dash d app there we go and so thats going to go ahead and install all of the dependencies all of the sort of scaffolding for our project and this may take a minute so ill go ahead and pause the video for now all right so once that installation step is complete lets go ahead and cd into our new directory lottery dash d app all right and weve got one more dependency that we want to install and that is for the bulma css library so lets do npm i i for install bulma and again thatll just take a second to install there we go okay lets go ahead and open up our code editor and see what weve got so far so ive been using um visual studio code for quite a while now i definitely recommend that to you guys but you could use of course you could use the editor of your choice all right and im going to go ahead and open up the im going to open folder and im going to open up the lottery directory the top level directory for our project all right and you can go ahead and x out this little get started page here now im going to expand the lottery d app and as you can see weve got the scaffolding for an entire next.js application weve got our package.js with a couple of default scripts there and then the way this is organized is that so next.js comes with routing out of the box and its really pretty convenient youve got this pages directory here and if you expand that basically every js file corresponds to a route here so index.js lets go ahead and pop that open this is just our default route so this correspond this is going to correspond to localhost 3000 dash or just the you know basically no route the default route so this is going to be our home page and well well just use this to develop our lottery application were going to get rid of all this code here and start scrap from scratch but just to kind of see how this is going to work well the first thing lets go ahead and add the import for our bulma library so we dont have to do that later so im going to say import whoops bulma css dash bulma dot css and so thats going to grab the the primary bulma css file from our node modules folder where bulma is installed all right so just to kind of see this working lets go down to our well ill tell you what lets just start the application so go back to your terminal and by the way you can use the code visual code terminal right here im just kind of used to using a separate terminal for some reason so to start the our application we can do npm run dev now we can also do npm run start but in order to do that wed have to actually build the application run a build step so npm run dev lets us sort of run our project directly from our source code so during development thats really convenient go ahead and hit enter and we should see the project open up in a new browser on localhost port 3000 and if you dont see that browser window pop open you could just sort of open up a new window and navigate to localhost 3000 there we go and there is our default application all right so lets see how we can make a quick edit to this and see that reflected on the page so if we go back to our code editor lets scroll down a little bit and lets look at this welcome message on line 17. so lets just replace this whole thing including the anchor tag and lets just write lottery d app all right go ahead and save that and go back to your browser refresh and we should see that reflected great and youre also seeing a sort of shift in the css styles and thats due to our bulma library kicking in all right perfect so lets go ahead and start coding our lottery d app all right so we can now start building out the front end for our application so lets start by just doing a little cleanup here lets get rid of this image on line two and on line seven lets get rid of this class name were not going to be using this you see theres a default container style but that sort of conflicts with the bulma container so were going to delete this lets update the title of the application so were calling this lottery d app you can call it anything you want im going to actually change the name to ether lottery okay and lets update the description here so i just want to say um ethereum lottery d app simple enough for now okay um maybe well update this favicon later so well leave the link for now now lets get rid of everything under this main tag right here so from starting from line 15 im gonna go all the way down to about line 52 and just delete everything were going to start fresh there oops now for the footer im going to get rid of everything inside the footer but im going to leave the actual footer because we do want to have a footer for our website lets just go ahead and do a quick like copyright sort of text here so ill do a paragraph tag and then ill do ill use the copy html entity thatll give us the copyright symbol say 2002. now you can write whatever you want here im just going to do block explorer there we go all right so were starting with empty basically everything the content of our site its going to go within these two main tags here so well start empty there for now lets save that lets go and lets open up our in the styles directory lets open up the home.modules.css so i want to delete everything in here except for the footer styles so lets go all the way from the bottom up to where we start to see some footer kind of styles right about up to line 31 and ill keep main as well all right but im basically going to delete everything inside of it for now all right lets go ahead and save that all right so lets take a quick look at the lottery smart contract and just think about what kind of content we want to show in the main content area of our website so weve got things like a list of players that have entered the lottery weve got a lottery history which is a list of previous games and you know who won them then we got things like the total lottery pot or all the money that the winner is going to get and then weve got functions such as enter to enter the lottery right down here and then pick winner so i think these are some of the things that wed want to show in our ui so the the two functions that enter in the pick winner i think these are going to be buttons that we might want to show in the main sort of viewport and then i could imagine where off to the side and sort of the column we might want to show some information like the list of players the lottery history and the total pot so given that lets sort of create some structure for that i think were going to want to have like a column based structure so well have maybe two columns for the main interface where the buttons are and then maybe a one-third of a column or one-third of a grid to show the sidebar and some information there all right and also the top of the page you know we want to show some sort of logo or you know lottery d app ether lottery some sort of bigger text and then off to the right hand side we might want to show the connect wallet button so to do that we can use the bulma navbar structure so lets lets create a nav wrapper okay and so at the top level we can we can do a class name navbar and this is a bulma convention this will just give us some nice padding and spacing for our nav element and then inside that we can do a container so well do div class name equals container and this is a bulma container again just something to give us some structure and some nice padding default padding out of the box all right so again to lean on bulma we can use something called navbar brand which will give us an area on the left-hand side of our nav bar for a logo or header text or something like that so well say div class name navbar brand there we go lets close that up and so inside of navbar brand we can lets just do a h1 tag for now and ill say ether lottery okay now at the same level as navbar brand we can use another bulma class called navbar end again this is going to be on a div well say class name navbar end and what this does is it positions an element to the right hand side of the nav bar so inside of here we can do a button element for our connect wallet button and well give it some bulma classes to help style it a bit so ill say button is link and so for the text we can say connect wallet now you might be wondering about this button is link and again these just come from the bulma library so ill just kind of show you in the docs what that looks like so this is just a good reference i kind of like to have this open while im developing any bulma based application and i think button is oh its under form elements wheres that there we go button so theres a lot of customizability that you can do with bulma but it gives you a lot of cool default classes and this is what im using right here this sort of purple variant of the button and you can see the reference code button is link and so theres all different kind of styles you have a light version of the buttons that well use later i think on some of them and youve got different button sizes so i just kind of like to have this open as a reference all right lets go back to our code editor all right so underneath sort of the same level as our navigation element we can go right under that and lets create a main wrapper for our the rest of the content for the page so ill say div class name and lets just give this a container and again container is just sort of a generic class that gives us some spacing some structure for our application all right so within the main container element we can just start creating different sections so were going to have two buttons for starters were going to have a enter button to enter the lottery and then well have another one underneath that one for a choose winner or pick winner so well say section and section is just a html element and lets give it some padding we know right off the bat that well need some padding otherwise itll just sort of bump right into the nav bar so i think once i create one of these i can sort of do some copying mt5 is a atomic element that um or an atomic class name that bulma provides margin top five and theres one through six i believe so you can do mt for margin top you could do mb for margin bottom and then sort of choose the level one being the least six being the most so well go for five for now and again all this you can find all this information in the bulma documentation that i was just showing all right so within this section we want to create some further structure by using columns so columns are similar to what you may have seen in other css frameworks as grid and ill show you what i mean in just a second so well do div class name equals column now we can specify the width of the column by using the sort of english very english-like class name is two thirds and for the other one you could probably guess were going to do is one third and so that will give us one full row so ill go ahead and just copy this div right here and paste it right underneath and ill say is one third so what im thinking is in the the two-thirds area well have some buttons for entering the lottery and for choosing the winner and in the one-third thats sort of like the side panel off to the right that will show information about the the lottery pot the list of players and the lottery history so lets just put up some placeholder test um text for now lottery info and then here lets just do lottery buttons all right lets save that and just kind of see what we have for now where were at and go back over to our okay good so we still got a long way to go here but um weve got the basic structure set up buttons and this info should really be over to the right so well figure out how to do that in just a second anyway weve got a basic structure coming into place all right so i think to fix our column issue we can actually need to get rid of this s at the end of is one-third not not one-thirds so that should fix that problem and then were seeing the footer sort of like all the way up to the top of the page so go ahead and save that lets make some style changes here so in our main wrapper we can fix that issue by specifying a minimum height so min dash height and well say 100 vh okay and that should give us a minimum that should sort of push that footer all the way down to the bottom of the page now we can set some styles for our h1 tag inside of the main element so well say dot main h1 and lets um first lets boost the font size font dash size lets say 3m and see how that looks lets give it a bit of a bolder font weight equals bold yeah lets go ahead and make it bold and then whoops and so you may have noticed that it was black before we added bulma and then it sort of turned to this gray color i think i like the original black so this is totally optional of course you can style it however you want but i liked that black that we initially had so im going to change that lets save that and see how things are looking yeah thats much better so im and our footer is at the bottom now so im still not sure why this structure isnt quite working lets go back to the code and see main weve got nav and then weve got a container under that weve got mt5 oh you know what were missing a columns element so weve got to let bulma know that were trying to make columns here so i think i just forgot one level here we go under section lets create another div with a class name of columns that way itll understand this is two thirds you got to give it some context for that so im going to move this over a bit and lets close that div i think that was the missing piece lets save that and check again yeah exactly all right cool so thats basically thats the basic structure that im looking for all right so lets start to kind of flush out these areas the buttons and the lottery info all right so for the buttons uh well get rid of this p tag here now were gonna have two of them so well separate each sort of button area with another section so ill say section oops section and we want to give each one a little bit of top padding so they dont like butt up against each other so say class name equals mt5 for margin top five okay now go ahead and close that up all right so um lets first add some text here so well do the enter lottery button first so ill just put a little preamble here ill say enter the lottery by sending 0.01 ether if you remember our smart contract had a check to make sure that the person was sending in at least point zero one ether okay and underneath underneath that well have our button element so say button class name equals button and well say play now or you can say enter or whatever you want okay lets take a look at how that looks so far all right perfect weve got a little button over here now well um well add some more padding and well give this guy a color we also need some padding above our connect walla button so lets address those issues next go back to our code editor and lets lets see lets go up to our nav bar and lets just put some padding on top of the entire nav bar so ill say margin top four margin bottom four save that and lets go back to the button that we just created and lets give it some additional styling so again we can use the bulma button styling we can say is dot is dash link and lets make sure this is a large button and lets use the light styles is light lets give it a margin top of three lets see how that looks great thats much better okay so were also going to want a choose winner button and remember thats only available to the admin or the owner of the smart contract so you know in a real world application we might want to have this somehow hidden but well just rely on the smart contract logic to reject the transaction if someone other than the owner calls this button and for the sake of simplicity well just add that button right here all right so we can just go ahead and copy this entire section see starting at right here on line 29 just copy the entire thing and well just change the text first of all lets say admin only pick winner and lets just throw a bold tag around this admin only pick winner and well say pick winner for the button text and lets make this one a slightly different color so instead of is link lets make it uh is success or actually lets make it is primary thats a bit of a lighter green tone so lets save that see how that looks all right not bad um id like a little more spacing between these two so lets go back here and for section lets do margin top six so well max it out there and yeah lets see how that works all right great yeah that gives us a little more separation here cool i think thats looking good so far lets go ahead and um lets start to create some structure for the lottery info so if we remembered we had three sections that we wanted to do we have a lottery history lottery players and then lottery pot so what we can do bulma has a component called cards i think thatll work really well for this yeah so card and theres various options but its you know little sort of ui widgets or card elements and i think well just use kind of a plain one more like this without any header or footer you can have headers or footers but this is just kind of the basic structure for this class card card content and content so well just do something basic like this all right so lets go down to our one third column and we can get rid of our sort of placehold holder text here so lets do a section class name lets do a margin top five so similar to what we did before on the other side and so inside here we can create a div with a class name card and that is that bulma class thats going to allow us to style this as a card and then well do a card content and well only have to write this out once because were just going to copy for the other two that was card content i believe yeah card content oops content that up all right and finally weve got a one more div with simply the class name content and again well close that up theres a little bit of typing at this stage just to get things going but it should be a lot less after weve got this basic structure set up all right so lets do a h2 tag inside of here and for the first one lets do lottery history lottery history all right and then lets create another div for the content of this and this is just going to be a custom class name so well say history entry just so we have a little bit of control over this content here and so whats this going to look like we may have like a paragraph tag inside of here or you know what we just have like another div so lets do div lets just put some placeholder text for now well make this dynamic later because this all this information is going to come from the smart contract lottery winner and this is going to display an ethereum address so lets grab an address just from my metamask wallet all right im just going to copy the address here and come back over here and lets paste that in all right and lets put this inside a div as well all right lets just save that and see how that looks so far yeah that looks pretty good okay so we need to widen things a bit just to make sure it can contain that very long address here another thing that might be kind of cool is if we link this to ether scan you know you can go to ether scan and look up any address or token so heres my wallet address and we can look that up so itd be kind of cool if we could have that link to this page so lets grab the url and lets go back and lets create an anchor tag around this okay so im gonna say href equals and im gonna paste in that address and again well make this dynamic a little bit later but for now lets just hard code this in and then another thing we probably want is to make sure this opens in a new window so ill say target equals underscore blank there we go lets check this again yeah so now this is a link and this should take us directly to our ether scan page great okay so far so good all right so lets go ahead and build out our two remaining cards and well save some keystrokes here by copying what we have for the first card so lets see im going to do a copy this whole section right here and lets just go underneath our existing section close tag on line 56 and lets just copy that two more times one and two all right there so now we just need to modify the second two to what we want so for the second one lets say players so well change lottery history to players and this is just going to be a list of players that are currently entered into the lottery so well have a little count right here and again well make this dynamic later and then lets just grab this whole section right here with the div thats containing our anchor tag and well just we need we can remove this history entry we dont need that anymore and lets just paste that directly below our players count all right cool so for the last one lets make this the pot so instead of lottery history well just say pot so this ones going to be real simple well just get rid of the entire history entry which goes down to about line 82 and lets just hard code a value for now so lets use a paragraph tag and lets say 10 ether go ahead and save that great so weve got three cards off to the right-hand side looking good so we still need to fix this where the account numbers sort of running off the edge of the card um you know i really dont want to do any major restructuring so lets just fix the font size for these and so how can we do that we can weve got card class names and so we can sort of target card and then anchor underneath that so lets do that lets make it entry for card and then a and then lets do a font size lets try nine i mean 0.9 em lets see how that looks if thats still too big we can take it down some more not seeing any change did we target that right so weve got card and then anchor underneath card all right so i think what we need to do here is actually make a new module class css module so lets create a new class here and well say instead of card since thats a bulma class lets just do lottery info and then target a underneath that so lets go back over here and well put the lottery info class at the top level so weve got to do something similar to like what we have here styles names lets just copy this whole thing and we need to do styles.lottery info to target our new modules class so lets see we want that right about lets see right about here but weve already got some classes so what were gonna have to do is lets see were gonna have to use some um string literal syntax so if i recall this would go something like this there we go styles main in there and dollar sign styles main and then the rest of the classes i believe thats correct lets try that not yet oh i forgot to change the main okay lottery info there we go try that again info is not defined yeah i dont think it just doesnt like that dash in the class name lets just do lottery info like one word go back to our css lottery info lets try that there we go thats exactly what i wanted cool so now our ethereum addresses are fitting inside our cards and things are looking good all right so at this point um i think weve got a good enough structure to sort of turn our attention to the connect wallet button and lets start to wire up the function the functionality so that this connect button will actually open up our meta mask and ask us to authenticate to the site all right so the first thing we need to do is head on back to the terminal and we need to install the web3 library so im just going to clear this out and im going to type in npm i web3 now remember web3 is a javascript-based library that allows us to interact with smart contracts on the blockchain and it also also has some functions for allowing us to interact with our wallet with metamask in this case and were going to use it to get the list of accounts and to prompt metamask to open up and ask for authentication to the site so ill just pause the video while this is installing all right great so our installation is complete so lets go back over to the code editor lets go back to our index.js file all the way up to the top and the first thing we need to do is actually import the web3 library so ill say import web3 capital web3 from lowercase web3 which references the installed module okay so what we want to accomplish here is we want to have something happen when we click on the connect wallet button right we want to prompt metamask to open up so we need a click handler on the connect wallet button which means we need a function that that click handler will call so lets define a new function well go right up here under our default function name and lets say const lets say connect wallet handler okay now this is going to need to be an async function so ill use the async keyword and well use fat arrow syntax here great so weve got an empty function for now and well fill that out in just a second for now lets grab the function name and lets go down and find our button and lets just add an on click handler so on click with a capital c as per the react convention now inside a pair of curly brackets well just enter our connect wallet handler name all right so the first thing we need to do is have a check to make sure that metamask is installed and to make sure that generally that were in a browser environment and the reason for that is because metamask actually injects a wallet provider under the window object which is a global object in javascript and so we just need to make sure thats available for us to use so im going to say if and heres the code to check for that so im going to say type of window not equal to undefined okay and thats just basically a check to make sure that were in a browser environment and we want to make sure that the metamask ethereum object has been injected under the window object so we can do another similar check here type of window dot ethereum is not equal to undefined all right so lets add some curly braces and well have an else statement oops and here well just sort of log an error if i can spell else right there we go so well say console.log please install metamask all right and so i want to comment everything were doing here just so its really clear so ill just add some comments and ill say check if metamask is installed and really were also checking to make sure that were in a browser environment but ill just leave that off for now and then metamax is not installed okay cool so now underneath our if statement so the happy path the green path if everythings going well and i need to close this comment were going to attempt to connect to metamask so well put this all in a try catch clause just so we catch an error in case something goes awry so in our catch well look for an error message and well just console log that out okay so if something goes wrong with opening up metamask or authenticating well catch that error here and log it to the console all right so the first thing were going to do is request wallet connection so well just leave a comment there and for this were going to use a weight because its async function window.ethereum dot request and this is going to take an object a method with the value eth underscore request accounts and this syntax is uh just very specific to metamasks api so were calling a request on the ethereum wallet provider that theyve injected into window so this is whats going to actually cause the metamask application to open all right so the next thing we need to do is create a web3 instance and well pass in that ethereum wallet provider into that constructor for the web3 instance okay so ill say create web3 instance okay and so what we actually need to do here is once we create that instance so lets lets just write out that code first take it one step at a time so im going to say web3 lowercase equals new web3 because its a constructor function and were going to pass in we have we got to pass in a wallet provider so lets say window dot ethereum using that wallet provider that metamask has installed for us now what we want to do were going to use this web3 you know not only for getting the list of accounts which is our next step but were going to also use it later on to invoke methods on our smart contracts so what we need to do is set this into a state variable so we can use the react to use state hook lets go ahead and add that to the top of our page so im going to do import use state from react okay so now we can go ahead and create a state variable for web3 so im going to do const and in array syntax were going to say web3 and the second argument is going to be a setter function so well say set web3 equals use okay and well just pass in and we wont pass in any argument here so itll be set as undefined and so now what we can do here we can set this to state okay so well use our setter function and well send in the web3 instance that weve just created all right perfect so the next thing we want to do is get the list of accounts and similarly what were going to do is were going to leverage react the react use state hook to set the account at zero into our state into our application state okay so lets say get list of accounts okay so well set up a variable for accounts that were going to get back and well say await web3 were using our web3 instance now and we can call ethe.getaccounts perfect so lets uh for now well set account 1 to to our state variable set account one to react state so we can say oh we got to set up that variable first actually so well say const address and well say set address and well say use state so now we can say set address and well say accounts at zero position okay because this is going to give us an array of accounts so were just looking for the first one for now all right well just comment this one as well just so its super clear react state all right perfect so with this lets go ahead and save the file and lets go back to the browser and lets see if this is working at all all right so lets click on connect wallet im going to open up the console just in case we have any errors or anything like that connect wallet and there we go great so ill go ahead and approve the connection for account one and we are now connected i can verify that by opening up again and we see this little connected icon right here so great our connect wallet functionality is working and i think were at a good stopping point for now to sort of turn our attention to deploying our smart contract our lottery smart contract to ethereum rinkeby testnet so weve got to have a working contract out there before we can really go much farther and start to use web3 to interact with that contract all right guys so lets go ahead and deploy our lottery smart contract to ethereum now im going to go through the steps in this section a little bit quickly just because ive covered this before in a couple of previous videos now but if you guys want a more slower paced sort of line by line guide to this process i definitely recommend you check out the smart contract testing and deployment guide and ill add a link to that video in the description of this one so we will cover every step its just we wont go into great detail or depth on each step well just sort of go through the motions here so the first thing im going to do is go into my top level project directory and lets open up a new terminal and im going to create a new folder so ill say make dur and im going to call this lottery okay and this is going to be the folder for our smart contract deployment all right once thats done lets go ahead and cd into lottery oops lottery not lootery lottery there we go okay so step one or step two i guess is to initialize a npm project so im going to do npm init okay and im just going to accept all the defaults great all right so the next thing im going to do is install truffle and this is something where i want to install it globally so if you guys havent used truffle before then you want to do npm i with a g flag for global and truffle and if you already have this installed then you can just skip this step okay and this will take a second so im just going to pause the video alright perfect so next thing we want to do is initialize a truffle project so alls i have to do is type in truffle init and this is going to set up the scaffolding for a new truffle project for us and that was pretty quick so lets we need a couple of things we need to install a few more things while were here so lets just take care of that we need dot env so were going to use env files to hold some of our project variables and then we need something else called hd wallet provider so thats also a truffle package so well do at truffle forward slash hd wallet dash provider and i think those are all the dependencies we need for now if theres something im forgetting well come back later all right so while this is installing lets go back over to our code editor and lets kind of we can close close these ui files for now and lets see what the truffle init scaffolding has given us so let me go ahead and close up lottery d app for now and lets open lottery and uh perfect so we can see weve got a truffle config file this will be pretty important for us and then well need to copy our contract our lottery contract into the contracts folder you can see theres a migrations contract that truffle has given us by default you can pretty much ignore this this is basically just a separate contract to track our deployments so that you know if we try to run our migration and we havent had any changes it will sort of detect that or if weve only changed one contract it will sort of know the status of our deployed contracts and only deploy that one that has the changes so anyway not really much to worry about there lets tell you what lets go ahead and create a new file and well say lottery.sol and this is going to be our lottery smart contract and i keep on misspelling lottery there we go okay and so like ive mentioned before weve already kind of gone through the process of creating the lottery contract in in another video which im linking in the description so for now for the purpose of this video were just gonna sort of grab the code from github and this should be again i will link this in the description so you guys can have access to this contract but its this one right here the lottery with chain link vrf okay and just go into raw mode here and we can literally copy and paste this whole thing all right go ahead and save that perfect okay so one more thing we need to do is under the migrations folder we need to create another migration script for our lottery contract so what i like to do is just copy the first one here thats given to us by default and then well just there are only a very few things we have to modify so first lets change the name and well say two lottery migration go ahead and save that and then we just need to sort of modify some of the keywords here so yeah this should be lottery basically wherever you see migrations you can do a find in place and replace it with lottery there you go and go ahead and save that all right perfect so the next thing were moving along pretty quickly here lets go ahead and create a env file so im going to do env okay perfect and lets go ahead and open up our truffle config file all right so at the very top there are a few things that were going to want to add all right so at the very top there are a few things were going to want to add and the first one is a require statement for our dot env for the env module and so the way this works is you require it and then you do dot config all right next line well set up a variable for our hd wallet provider and well say require at truffle forward slash hd wallet provider all right now were going to be reading the private key from our env file to keep it safe and well make sure it doesnt get you know checked into github or anything like that so well actually write the reference to that right now even though we dont have it yet so ill say private underscore keys and the reason why i say keys is because this is uh basically an array okay and so inside here we can just have an array of one item so ill say process dot env dot private underscore key underscore one and i believe thats all we need one private key so lets save that now back to our env file what we want to do is basically set up an environment variable that matches this right here so im going to go ahead and copy private key one im going to go back here and lets save that for now now what i want to do is export the private key from my my metamask wallet so by the way i should have mentioned this before but um one of the requirements for this project is to have metamask installed so if you dont its really easy just you know google it and go to click on the download link right here its just a browser extension so all you have to do is choose your operating system install metamask for chrome and sort of follow the prompts from there all right so since i already have it installed and ill close a couple of these for now ill close this for now what i want to do is open metamask and i want to make sure that im on account number one this is the one im going to use for deployment ring could be test network okay and if you click on this colorful icon or sorry its not the colorful icon its the uh the three dot menu and account details thats what i want theres an option called export private key so click on that and definitely this warning is pretty important never to close this key um this is the key to your wallet so anyone who has access to the private key can basically you know basically has access to all the funds in your wallet so not something you want to share keep it in a safe place okay and im copying it right here and im going to go back to the code editor and go ahead and copy that into my.env file okay so it doesnt look like we have a git ignore but im going to create one real quick just because its good practice because you never ever want to you know check in your env file that contains your private key anywhere so well say env save that okay back to truffle config so if we scroll down a bit not that fast scroll down a bit theres a networks property on line 44 and everythings sort of commented out but heres where you can sort of tell truffle which test environment youre targeting for deployment so what im going to do is im going to create a new entry im actually going to im going to select ropesteen and im just going to uncomment that okay and were going to repurpose this for rinkaby so there we go so im just going to rename this rinkeby it could be test network okay and lets go ahead and get this filled out okay so lets see new hd wallet provider um we can delete everything inside of the curly braces okay so were going to do this by private key not by new mnemonic which was the default as you saw there so im going to say private keys and again we can reference the variable that we created up at the top which was called private keys so im going to copy that im going to paste it down here okay place a comma right after that and what doesnt it like here comma expected oh this is an object yeah inside hd wallet provider that should be an object since were passing in a config object here with multiple properties okay so provider or url just do an empty string for now well come back and fill that in in a second number of addresses well just do one all right so network id lets change it from three to four for rinkaby and you can im not going to bother with changing all these comments well just leave that for now and everything else we can just leave as is okay so for the wallet provider were going to use something called infura which ive described in more detail in previous videos but basically it is a service that allows us to interact with nodes on the ethereum blockchain so if you dont have an account you can go to infura dot io i believe thats what it is yeah and you can sign up here go through the process itll collect a email and ask you to create a password and things like that but its a pretty simple sign up process so once youve signed up for an account and itll let you you know use a certain amount of requests for free so the free tier should be more than enough for this video and what im going to do is im going to create a new project product select ethereum a name im going to say lottery lottery d app maybe okay and im gonna do create over project allotment uh okay so um it will only let me create three projects so im gonna delete this one since im not using it anymore there we go so lets try this again ethereum and lets just call it lottery cool okay so in the project settings or the project details its going to give us some information that we want so theres a drop down called endpoints and we want to make sure we change this to rinkaby now all we have to do is copy the url for this first endpoint there we go copy it to your clipboard and lets go back into our code editor and lets go ahead and just paste that right here where it says provider or url and what we can do is we can actually make this an environment variable so the very last part of the url is your api key so go ahead and cut that lets go back to env and lets create one more new variable infera api key equals and then just paste that and go ahead and grab this key here save the file back to config and so well make well use a string literal here so we can use this variable whoops back tick and this will be dollar sign curly braces and and curly braces there we go okay so far so good all right so now our configuration is done and we can go ahead and attempt to deploy this thing to the rinkeby test network so lets go ahead and open up our terminal and im gonna go ahead and close this out for now make sure its the right terminal the one that is in the lottery directory there we go okay so what im gonna do is type in our deploy command which is truffle migrate and migrate is synonymous for deploy basically in truffle speak so well set a network flag and well say rinkaby and lets go ahead and try this out go ahead and hit enter and if somethings incorrectly configured then well get an error message and deal with it but lets see how it goes command failed uh okay ive seen this one before so uh consumer base sold i see okay so we were using chain link to get a verified verifiable random number in our lottery contract and so we need to actually install chain link contracts all right so lets do npm i at chain link forward slash contracts and thatll go ahead and install those dependencies for us and again if you guys want to hear more about how chain link works and how it helps us get a verifiable random number definitely check out the first two lottery smart contract videos all right thats installed one other thing that i just thought of we need to make sure that our compiler version is correct yeah it looks like it is in my case but um make sure that the version is set to 0.8.11 because that will match whats in our smart contract all right so lets give the deployment another try there we go reference error infira api key is not defined infira api key lets check the spelling in our env file looks correct to me infira api key lets go back to truffle config not sure what its not liking about that um inferior api key so i wonder why its saying thats undefined oh process.env yeah ive made that mistake before make sure you got process.emv so it knows to find this variable in the env file all right and lets try it again third times a charm okay excellent so our migrations were a big success everything went smoothly now what i want to do is make sure that youre under the number two lottery migrations sort of block here i want to grab the contract address okay because well use this in our front end code all right so for now just go ahead and copy this and just paste it somewhere safe in a notepad or something like that for now and well come back and grab this in a minute and actually one more thing we can do is we can grab this contract address and plug it into ether scan and just get further confirmation that our deployment went through so if i just plug that in here and then hover over this little click over this little icon here and we can see theres a wrinkly test net entry for this address and this is our contract see six minutes ago thats about when we deployed it and we can see the transaction hash the block number contract creation and all the other details about our contract okay so now that our contract is deployed to rank a b test net lets go back to our code editor and lets continue to work on our front end app and use the web3 library to interact with that deployed contract okay so im going to close up lottery for now im going to reopen lottery d app and the first thing im going to do is create a new folder and lets call this blockchain okay and so what were going to use this folder for is we are actually going to um copy and paste uh our lottery solidity contract in here and were going to use that to generate something called an abi an application binary interface now the abi is something that well have to feed into web 3 in order to create a new contract instance or a local copy of our deployed contract in our front-end application in order to use to basically call methods on that deployed application and you can sort of think of the abi as the glue between between the front end and the back end or the passport if you will between the javascript world and the solidity ethereum world and what it is its basically a json representation of all of the methods and inputs and outputs in the solidity smart contract so that the javascript web 3 sort of knows in advance what methods are available on that smart contract for it to invoke all right so under blockchain lets create another new folder and lets call it build okay and this is where the output of our or basically our abi our generated abi is going to go into the build folder so again lets create another new folder under blockchain and lets call it contracts okay and lets create one file under blockchain and well call it lottery.js and so this is going to be the file that actually creates that local copy that local instance of our solidity smart contract all right so the first thing we need to do is go back into our lottery directory directory for just a second and we need to copy and paste the lottery.sol file so im going to copy that and then close this back up and im going to paste that into the contracts folder there we go so now we can target this to generate an abi and the way were gonna do that is were gonna open up package.json and create a new script so theres a couple of things we need to do here so were gonna first of all were going to use something called solc js which is a solidity compiler command line compiler that were going to use to generate the abs so well need to install that but before we install it lets write the command to use it makes sense right compile okay we wont actually invoke it until we install it so ill say solc for solidity compiler js now theres a little bit of typing here so bear with me flag abi flag include dash path and then node underscore modules forward slash another flag base dash path all right dot space block chain to reference that new folder that we just created contracts and here were telling it where the contract is that we want to generate an abi from so well say lottery.sol okay another flag well say output dash dr dir output directory and then well say blockchain forward slash build okay got all that good now next thing lets go ahead and install the solc js all right so i need to find a terminal ive got too many open so let me close a couple of these real quick all right so basically we want to make sure that were back in our d lottery directory so im going to clear that im going to go back up a level and yep im in the right place so lottery dash d app the app okay great so n-p-m-i-s-o-l-c-j-s i believe thats the correct command oh i think its solc without the js part sorry about that try that again okay great so now we can try to go ahead and run our compile script so im going to do npm run compile and with any luck this will create an api missing script compile compile what doesnt it like about my compile script missing script compile did i forget a comma somewhere i you know i may have to just close i think what i have to do is just close and reopen and make sure i save this file i wonder if that was it oh no okay ive done something weird here so let me copy this line just in case i lose it here okay over right okay no were still good all right just a little hookup here we need to just reopen the terminal under lottery d app because i guess it wasnt aware of that compile script since i had written it at the time when the window was open npm run compile come on there we go cool so hmm oh you know what it looks like i need to include the uh chain link vrf stuff here all right so lets go ahead and try to install the chain link contracts so at chain link dash contracts and hopefully itll be able to read these from the node modules folder all right so lets try to run that compile script again lets see if this helps at all okay so it looks like we have a mismatch between the solidity version of the compiler that we just installed and our contract so lets uh go ahead and npm uninstall soul c and lets go to our package json and lets just see go right underneath our react stuff and lets just install it manually c and well say carrot 0.8.11 okay save that back to the terminal npm i this way were sure that weve got the right version all right now lets rerun our compile step again all right great looks like it was successful this time we can ignore this error for now its just an unused parameter so lets see what weve got here under our build folder heres what were looking for the very last one that says lottery abi so go ahead and open that and basically we heres our abi its a little bit hard to read because its all on one line but you know its just a json object copy the whole thing lets go ahead and copy that and go back to our lottery.js and so were going to create a variable to hold this abi and so well say lottery abi equals and just go ahead and copy that whole thing right there then hit enter all right so basically the way this is going to work this is going to be a callable function or i guess all functions are callable a car a callable export rather um thats going to take in a web3 instance that weve already gotten sort of on the front end and saved into react state if you remember that step and so this is going to return a working lottery local contract instance so lets go ahead and code that up im going to say lottery contract okay and this is going to be a function its going to take in a web 3 object okay which is in our react state and then were going to return from this a new web3 instance so new web3.eth.contract with a capital c now this is going to take as a parameter the abi and the contract address so here we can reference the variable that we created above lottery abi comma and then if you remember we copy and pasted the contract address to a notepad so go ahead and grab that heres where were going to use that and in quotes its going to be a string just go ahead and paste that contract address now finally we just need to export this so well say export default lottery contract just like that all right cool so lets go ahead and save that all right we can go ahead and close up our build folder and our contracts folder and in fact we can close up the entire blockchain folder all right so now that weve set that up lets go back to our main page here our index.js page and we can now use this new function to create a local contract instance so what im going to do lets go ahead and first of all lets import that file so ill go right underneath web3 and ill say import lottery contract i think thats what we called it right yeah lottery contract from um well have to go up one level and then into blockchain and then lottery okay great so now we can scroll back down to our lottery handler function and right underneath where we set address we can create our new contract instance so ill say create local contract copy okay so ill say lc for lottery contract and then ill say lottery contract the file that we just imported remember we said thats a callable export so then well we need to pass in a web3 instance okay so well just say web3 since weve set that variable right here okay now what we want to do once we have this contract instance we also want to set that into a react state variable so we can use it in various places so lets do that lets set that up first so back up to our state variables well say const lc contract and then well say set lc contract use state equals use state okay so lets copy the setter function and well come back down here and then well just pass in our lottery contract instance so that is now set in react state and we can kind of use it anywhere we want to now all right ill tell you what lets go ahead and run our application real quick and take a look at what weve got again so ill do npm run dev and so lets think about the first sort of bit of code that we hard coded previously and which one that we want to actually unhard code and um you know fetch the data from the blockchain first all right so weve got lets see lottery history well we wont we wont really have any data here until we play a couple of games at least one game and so to do that we need to enable these two kind of the same with players so um pot thats an easy one that we can grab so if you remember when we did our lottery function we have a getter function to get balance so this returns the balance of the contract which essentially is the pot so lets use this function in our front end first okay so what were going to do were going to call this function were going to use the use effect hook to call this function once the react components are loaded so well say use effect ill pull that in and then use effect well just set up sort of a placeholder for this right now because what we want to do is we dont want to call the code directly we want to create another handler so ill say const get pot not that kind of pot um equals lets see this will be async as will all of the functions that were sort of calling from our contract all right so what i want to do here ill create a variable for the result that were going to get so well say pot equals await so well say lc contract right because thats the the contract instance that were that weve got saved in react state okay and now on this there should be something called methods available and this will hold you know as you can probably guess all the methods on the smart contract so we can say get balance okay and so get balance you know its a read-only function as you can see by the view modifier here its returning a uint and so its its not modifying the blockchain in any way which means we can run a call function as opposed to a send where wed actually if were modifying some information on the blockchain wed actually have to send in some ether to run that function to pay for it but in this case its pretty easy pretty straightforward we just have to do a call right for read only all right now lets create another state variable for the pot so ill say lottery pot oops i forgot my square bracket lottery pot and set lottery pot so kind of a lot of boilerplate code here just to get things up and running state all right and now we can actually say set lottery pot and pass in the result from our smart contract so this pot value this is actually coming from the blockchain from our deployed contract on ethereum okay so next thing we can do in use effect well actually invoke this function but before we do that we just want to check and make sure that there is a local instance of the contract available otherwise itll throw an error so ill say if lc contract get pot and well invoke that with no arguments and then as the second parameter of our use effect well pass in lc contract because wed want this to rerun if any of these variables change and well say lottery pot okay now we can use this variable lottery pot and remove our hard-coded value down in the actual card so down here where we said 10 ether well just remove that and well do some curly braces and add our lottery pot there so all right that was a lot of coding um im totally not expecting this to work the first time but lets save it and see what were getting here lets go back up here lets refresh the page oh is our is our thing even running yeah it is okay so were getting nothing i was sort of expecting something like that so lets see whats going on here weve got lottery pot there was a lot of wiring up of things so we may have to start console logging some stuff to figure out whats going on here um all right so were setting lottery contract web3 set lc contract that sits our local instance right right here and then what else are we missing were saying if lc contract get pot you know what lets just log something to see if this is even getting called i think thats a good starting point all right so ill just say get pot lets save that and lets open up our console ctrl shift i if youre on windows the page is refreshing reloading all right so thats not even getting called here oh you know what i havent connected my wallet i think thats the problem oh there we go zero okay that was weird i think maybe um the page needed to refresh or i needed to connect my wallet oh i see whats happening so we had never we just clicked this to trigger the on click for it um okay you know lets do a fresh test im just gonna um disconnect and were gonna do this from the very beginning oops not that one connected disconnect okay good yeah we just need to run this test like from a clean slate here so im going to refresh the page refresh so we should see nothing here right so were not getting anything back were not okay so i need to do connect wall at first and thats whats going to start to set some of the stuff in motion right set all these react variables so ill say connect yeah then we saw getpock being called and then we got zero down here okay great so thats working as expected all right so next lets look at wiring up our enter lottery functionality all right so actually you know what we might want to do before we even set up the get or the enter lottery function we might want to um just retrieve the list of players so that when we do set up sort of wire up this button um thatll be a good test for us to see if its working because we could well be able to see that address here so lets do that first this is going to be pretty similar to the one we just did ill get rid of this console log so yeah were basically going to do a couple of things pretty much the same including setting up a state variable okay so were going to say lets see players and set players use state and lets just pass in an empty array to initialize this one and then well set up a function in fact we can just copy this one save us a few keystrokes and im going to say get players and then down here ill say const players what i do there players okay and now lets check our contract what to see what function we need to call here and weve got a get players function right here perfect so lets utilize that get players and again this function is simply reading and retrieving back a list so we can use call and we can say set players and pass in players i always capitalize the second letter there we go all right now finally we can again we can copy this statement on line 16 and lets do oh whoops now this will stay the same so if lc contract get players and i guess we could move this all into one if statement but lets just let it be for now and ill say players so that if the players is ever you know augmented with a new value then this should run again all right um am i missing anything get players call okay oops spelling mistake there we go all right lets try that oh yeah we got a hard code or we gotta unhardcode the value so players players lets go down and its this one right here about line 115 or so all right so what were going to want to do is iterate over this players array all right so were getting this from state well say map and then well say player and then for every player well want to you know output one of these things right here so lets copy and paste that whole link element okay and this is going to become player because i believe thats just an address and then were going to want to use string literal syntax here and lets do player dollar sign oh oh this needs uh outer curly brackets thats the problem there we go and outside of this yep all right and its going to want this in curly braces um whats wrong with my map syntax here oh you know what this whole thing needs to be in curly braces so lets just do that and close it right here all right and close up our our map as well so thatll be curly brace and then and then um parentheses there we go okay um and then well well have to do the count as well so how is that going to work all right lets worry about that in a minute lets just save this and see if this much works all right so im going to refresh the page and im gonna have to sign in again so im just gonna go ahead and disconnect yep refresh the page all right connect wallet players okay i think thats correct because there are no players right now i was kind of looking at this one and um instead of this one by accident but yeah i think thats looking good so okay lets work on the play now or the enter lottery button next and then we would hope to see a new address pop up here if that parts working correctly all right so lets go back to our code editor and lets wire up a enter lottery function so im going to go right down here on line 30. im going to say const and lets say what are we going to call this lets call it play now just to match what our button says so its going to be async you know i dont really dont like that lets say enter lottery its a little bit more descriptive all right so im going to do a wait lc contract dot methods dot enter because remember enter is the name of the function to actually enter into the lottery and that doesnt take any arguments right all right so this time instead of call we want to do a send transaction since were actually adding some data to the blockchain and actually sending in some ether remember theres a minimum of 0.01 ether to enter the lottery so were just going to make that sort of the the required amount here or the only amount thats possible to send in here okay so from is going to be address and that reference is the currently active address in metamask okay and then were going to do a value value and lets we could either enter the value way is the default um but ether is a little bit more readable so lets go ahead and do it in ether weve got a little handy little util function that we can use its under web3.utils its called two-way because whey is a subset of ether and so you know youre dealing with a lot of zeros if you specify the value in way so what lets try this im going to say 0.01 im not 100 sure thatll work with fractional amounts like this but well see and if this doesnt work then we can just use um way okay and what is this comma expected oh again this needs to be an object yeah sorry about that and close this up here okay now lets do a gas im gonna say 30 300 000 see if that works sometimes you got to play around with these numbers a bit and well just do a null for gas price well let metamask estimate that for us all right so i think what we want to do is um wrap this whole thing in a try catch you know we should always wrap any sort of async function in a try catch so im just going to copy this whole thing right here put this in the try clause and then ill do catch error and well just console log the error actually in a minute were going to set up some actual um error messaging like a area on the website where we can display error messages but well just do this for now enter lottery okay and finally lets call this entry enter lottery handler since technically were going to call this from the click handler on our play now button so well go down here where is it right here okay so well do on click equals curly brackets and well paste in our handler name there okay cool so i think thats everything all right lets see if this works so go ahead and make sure thats saved go back to the ui and again im going to disconnect and reconnect my wallet just to make sure were running a clean test here disconnect okay and refresh the page all right oh yeah thats a little bit better actually you know what i can move this to the bottom now maybe thats better all right all right so ill connect my wallet next connect okay so far so good getting some data from blockchain here now lets try our play now and if everythings working correctly this should open up the wallet and it should specify the value yep there we go and so now we just have to sign this transaction by clicking confirm transaction has been reverted okay that could be the problem there okay its not really giving me any useful information i can guess though that maybe the um the gas price we set isnt enough i can open up metamask and see if its giving us any more you know useful information transaction encountered an error transaction data okay its not really giving me anything useful here lets see yeah so im not seeing much useful information here in terms of error messaging but one thing that i could sort of guess that might be the problem is that were maybe were not sending in enough ether so were sending in the exact amount needed to enter the lottery but theres really nothing left over for gas fees so one thing we can try to do is just slightly increase the amount of ether were sending in and so i think were going to need to switch to whey instead of specifying that send amount in ether so all right lets figure out how to send in the value as way first of all so im going to do ether to way and to just search for a little calculator that we can use all right so 0.01 and you know what lets actually just make it slightly higher than that in case theres any gas fees or anything that you know we need to cover that could be the problem too as well lets just change this the to 0.015 all right so grab that value and lets go back to our code and instead of doing all this lets just send the value in as way and lets go ahead and try it again yeah theres a little bit of trial and error here so i wish i was getting some more helpful error messages okay so yeah that was successful looks like that was the problem we just werent sending in quite enough i think we were sending in the exact amount required to enter the lottery but not enough to cover gas fees so that makes sense oh and then weve got the pot um listed in way so we can actually convert that to ether just to make it more readable so our player still isnt working a couple of things to fix still here but i think were on our way all right so lets go ahead and fix the pot formatting first we saw that output is way but we want to see it as ether so lets go back up to line 22 and again we can use a web3 util function to reformat that and well say utils from way okay and so this takes um two arguments the second one is optional the first one being the value that we want to convert which is pot and the second one is the target denomination but it defaults to ether so you dont actually have to specify this i just like to be a little explicit so and then well come down to where were actually outputting that in the ui and lets just type in ether so that its clear all right lets try that so im gonna go ahead and connect wallet all right and there we go were already seeing the output of 0.045 ether which is the current pot since ive now you know entered into the lottery a couple of times alright so thats much more readable all right now lets go ahead and fix our players array that wasnt showing up so lets see if we can figure out whats going on here so were calling this in use effect first of all i think we we need to back out of this here we dont need these because this will cause an update to these two variables which will cause use effect to run again and thats going to lead to an infinite loop so we dont want to do that the second thing im noticing here is that we sort of have a doubly named variable i mean were using players internally here and were using players here i think we should change that im not sure if thats a problem per se but its just good practice so and i say that because players is internal to this function and it might not conflict with this one out here but you know i think its just good measure to keep these named separately and so weve got get players and were fetching the list of players from the smart contract then were using that temporary internal variable to set this one right here okay all right i think thats fine now lets go back down to our render area where is it okay so we need to update this name now lottery players and we need to check to make sure that this actually exists first of all so lets check for the existence of that array or i mean not the existence but you know its a null check so were making sure its defined first of all and then well just make sure its got some length so length is greater than zero and then if thats all true well go ahead and render this render map players and then we actually need to return this and so another thing we might want to do here we might this is going to be a list right so lets make this an unordered list just so that all of these dont sort of run into each other okay so well do li well indent a little bit here and well close that so lets see if this works so far all right so lets just hit on the connect walla button lets open up our console here and lets disconnect disconnect this account okay fine and connect wallet all right so im still not seeing anything rendering so weve got a problem somewhere lottery players and lottery players oh dot length there we go lets try that again there we go all right we got our list there um now i dont necessarily want to see these bullets what can we do about that and also we need a key property so lets fix that first each lil it should have a key equals and i guess we could just send this or we could just um this takes index as a second argument so well just use lets see what do we want to do here lets say player plus index all right so this is going to be player dash index lets see if that works so well refresh and well hit connect wallet again great and that error message is gone okay um you know what lets get rid of these uh lets see how do you get rid of a bullet point this style type equals none i believe is what it is so lets go back to our styles folder and lets say lets lets uh leverage our lottery info class again i think this is on the ul level if i might be wrong about that but list style type is none see if that works still there hmm i wonder if this is on the li type lets try that yeah there we go all right and we can also do like a negative margin or something lets see what do we have going on here margin left is 2 em so if we get rid of that yeah thats kind of what im looking for so well do a margin left to zero so let me just copy this entire thing ill get rid of the li you know what i could actually just use bulma to put this directly on the html lets do that so right here i can say class name equals margin left zero lets see if that works connect wallet yeah perfect all right that is what im looking for and finally the last thing i think i want to do here is update the count here so lets unhard code that and lets say lotteryplayers.length and lets see if that works yep there we go so were seeing r3 perfect all right so we said a little bit earlier that we wanted to find a better way to handle errors were just sort of console logging them for now but i think what were going to do is lets just set up a dedicated sort of ui area to to view errors so lets see where do we want to do this i think lets kind of go right underneath the second button which is our pick winner button so under here about line 102 lets create a new section okay and then inside that lets create a new div element and well give it a class class name equals well say container container and then we can use some special bulma classes um for error messaging and this is called i love this name has text danger all right dangerous stuff here so we will use this for our error message whenever we have one so lets say error and now this is going to refer of course to a react state variable which weve got to create so lets scroll all the way back up to the top and lets say const error and set error equals use state and well initialize that to an empty string okay so we can copy this set error and wherever previously we were console logging errors we can use this instead so enter a library handler just replace console.log with set error and this is one thats going to be easier for us to test right here in our connect wallet handler well set that error message all right so lets give this a quick test lets go back to the site and lets first i got to disconnect and what well do is well try to reconnect but well reject well reject the request and we should see that error message at that point so there we go get rid of this get rid of that refresh the page and well see if our error message is showing up im going to do connect wallet and then im going to choose reject or cancel and there we go user rejected the request so i wonder why were not seeing it this is supposed to be red first of all and uh while were at it lets give it a little bit more upper padding there where is it i may have had like misspelling on the class name or something like that yep never fails so lets also add some margin top ill say mt-6 all right and lets try that again yeah and we need to reset this right so well lets just try to connect again cancel now lets refresh the page okay connect wallet and cancel and were still not getting that red text has text danger oh my god ridiculous okay and there we go thank god i dont have to go through that again so there we go thats kind of what i was looking for perfect weve got our error messaging what we can do is we can actually clear this when we get into the connect wallet handler again so we could sort of just do set error and set it to an empty string so that disappears as soon as we you know try again all right perfect yeah i think thats the behavior i want great all right so lets move on to the pick winner function all right so once we pick a winner were going to want to display some sort of message confirming who the winner is so similarly to how we set up the set error functionality lets do a set success message all right so ill just copy and paste the error one and lets do success and set success we call this message success message all right and again well initialize that to an empty string and we can just sort of come down and well just copy and paste the error section and repurpose it for our success and i believe if im not mistaken this is has text success there we go and well set this to success message okay okay well lets just output this as it is and just make sure that that styling works real quick there we go perfect all right so we can go back to brackets now okay so um when we did the lottery smart contract and again if um you know if youre not familiar with this you may have to go back to that video and take a look but were using something called the chain link verifiable random number which is a additional contract that were inheriting and basically chain link is an uh an oracle a service that provides secured data such as random numbers in this case and then feeds that back to ethereum to our smart contract and so that costs a little bit of gas so just as you know any sort of code execution on the ethereum blockchain costs ether anything on the chain link oracle costs link which is their native token so what we need to do is we actually need to send a little bit of link to our smart contract before we can invoke the pick winner function since its using that random number functionality so there is a faucet at and all we have to do first of all lets set the network to ethereum rinkaby and then we want to grab our wallet address so go ahead and pop open meta mask and lets cancel this go ahead and make sure youre on account one and go ahead and copy your wallet address and you can paste it in right here and so as you can see this is going to send us 10 link and its also going to send us a tenth of an ether which is convenient to have that done as well and so im going to go ahead and send the request and you know just like anything else it takes a few seconds for the confirmations to come through all right we can close this window and then what we can do is we can display the link in our wallet so its not going to be displayed by default what we need is the chain link link chain like there we go chain link link ring could be token address okay link tokens contracts i believe it might be under here somewhere yeah covan rinkaby yeah this is what im looking for so we need the address of the link token on the rinkeby test net so now if we go back to metamask what we can do is go over to the assets tab and go ahead and import tokens and paste in that address and you can see it recognizes it immediately as a link token and so add custom token import tokens and great so now we can see that we have 10 link in our account so now what we want to do is we want to actually send this to our smart contract all right so how do we do that weve got the smart contract address back over in our yeah in our lottery.js so go ahead and copy that well go back over to metamask and well click on send go ahead and type in that address of the smart contract and we need to change this over to link and lets see if we can send all of it well just do 10 link might as well okay and go ahead and confirm that transaction and that is pending great so we are now sending that link over to our smart contract so that it can pay for the chain link random number functionality and if we hadnt done this then when we went to invoke the pick winner functionality we would get an error message saying you know something like you dont have enough link to cover this transaction so now weve pre-empt weve preemptively made sure that were not going to run into that problem all right excellent so lets go back over to our index file and so were going to need to create a new function and lets see how is this going to work this we got a button for this so again were going to do a handler so lets say const pick winner handler again this is going to be an async function okay no arguments and this is going to look very similar to the transaction that were executing for enter lottery handler so you know im tempted just to copy and paste this lets just do that weve had a lot of typing in this video so anything to save us a few keystrokes is good at this point okay so this time i just need to check the lottery contract and make sure ive got the function name correct and pick winner yeah so pick winder is going to in turn invoke get random number and that sort of starts a chain reaction thats gonna invoke the fill fulfill randomness um callback which is then going to invoke pay winner so by choosing pick winner it should result in the winner being chosen and paid so im going to going to go ahead and copy that and im going to paste that back right here so were doing lc contract methods pay winner this time okay so well need to send in some value but not that much lets try just two see if that works okay so weve got the pay lets go ahead and copy the handler name and add an on click to our button or is it right down here so well say on click equals curly brackets and go ahead and paste in that handler okay great all right so lets run a test of this and see if this is working so far now weve only entered one account number into the lottery so were pretty sure that ones going to win but this is just a sort of preliminary test to see if its working at all and then after that you know if it works then well have a clean slate with our you know well have one entry in the history and then i think what well do is well set up a success message and well look at um like the history to get the the person who just won the last lottery and display that on the screen but for now were just going to kind of have to look at the balance to see if anythings been deposited and you know look at the transactions here so lets just take a note of the account balance 2.5088 eth okay so if this if this works basically and we know account one is going to win since theyre the only entrant we should hope to see this number incremented you know by point zero four five right so point zero four five so well see point five five something 2.55 all right so lets give this a try you know i think we just need to like connect the wallet and maybe start fresh here so lets do that yeah thats exactly what it was so connect first otherwise we dont have a web3 instance to work with you know we should probably have some sort of custom error message if thats the case in the future so lets try this again pick winner and this is going to ask me to confirm the transaction all right and lets uh monitor the wallet here to see if we see any activity because we havent really hooked up a way for that to work on the site yet so we say pay winner pending thats good failed thats bad so what happened here all right guys so um sorry about this but i just got it to work after i pressed pause on the video uh because i was trying to experiment and figure out whats going on without wasting too much time but basically what i did was i just removed the value field totally from this transaction and basically that means im not specifying the value because i dont know in advance you know obviously we tried to guess how much the gas would be twice and it didnt work so if you leave this off then it just allows metamask to um you know estimate the gas for you and and take care of it and so as long as you have enough in your wallet in general then itll itll cover the cost so as you can see ive got a success message here and weve been incremented to 2.55 ether so yeah thats an old error message so if i so we the smart contract should have restarted the game yep and so were seeing zero players and um nothing in the ether pot so that is perfect all right so lets lets were going to test again and this time lets set up a success message once the pick winner goes through and the winner is paid so that we know who actually won all right so in order to show the lottery winner were actually going to need the lottery history information so were back in the smart contract now and as you can see lottery history is a mapping of uints which is the lottery id to the address and that address represents the winner and we can see if we go down to lets see the pay winner i believe it is yeah the pay winner function so were transferring the funds and then we are saying okay lottery history of the current lottery id now assign that to players index which is the winner you know were transferring this to the winner so players of index is the winner so were setting that into history and then were incrementing the lottery id so basically we need to use the lottery history of lottery id minus one to get the address of the winner for the game and you might take notice here that were doing something that i should i said that you should never do in my security uh re-entrance the attack video which notice were doing the transfer and then were updating state so i would probably reorder this if i hadnt already deployed it but in this case its actually not a security risk since were transferring the entire balance of the smart contract so whoever wins the lottery every time gets the entire balance of the contract since thats the sum of all of the contributions from the players whove entered the game so in this case its really not a problem this would be it would be a problem if we were transferring part of the entire balance because then someone via re-entrance the attack could you know call pay winner over and over again so so anyway its not a big deal for this particular example but just keep in mind in general that you want to do the state updating before you transfer the funds all right so with that lets go ahead and get our lottery history into our front end so we can both display the winner and show the lottery history in the card on the right-hand side of the page all right so were back in our index.js and the first thing we know were going to need is a state variable to hold the history information so lets do something similar to what weve done before and lets say lottery history and then set lottery history use date okay now lets see were going to want to fetch this and display it sort of at the beginning of the page load cycle so again well make another entry in our use effect hook well check for lc contract and then well say get history just do re all right and then we need to actually create that function so well say get history equals async function no arguments and then history equals await lc contract dot methods now we dont have a specific method to get history but we do know that for state variables we we get a automatic getter under the covers so we can call this as if it were a function right so we can say methods.lottery history and this is a call since were just reading information from the blockchain and oops i forgot to see async okay and finally we can set this in react state so ill say set history and well pass in history all right so before we try to do anything else with this lets just go ahead and log it and see what we get back so im gonna do console log and im gonna say jason parse because its probably gonna be uh an object here so ill pass it in history all right so lets see what we get here okay so were not going to see anything since we havent unhard-coded our ui yet but im just going to refresh the page and then hit connect oops invalid number of parameters for lottery history got zero expected one oh i see this is a mapping so its wanting us to its wanting us to pass in a key and get a value back so its not going to give us the entire data structure thats the problem here all right so since we cant get the entire data structure back from the smart contract i think what were going to have to do is use the lottery id right so we can the lottery id will basically implicitly tell us the length of that data structure so then we can use it and create a loop in our front end code to know how many times to look up in the mapping so weve got lottery id great so lets go back to our index.js file and so were going to sort of do the same exercise here for lottery id so im going to create a new state variable im going to say lottery id and i keep on misspelling lottery for some reason i think i would have done it enough times already lottery id and then set lottery id okay use state and well set that to well well just use nothing here which will make it undefined until we set it okay so well copy line 22 and lets do so how are we going to do this were not going to do get history for now were going to do get lottery id okay and lets copy our get history function because its almost going to be identical so well say get lottery id and then this will be lottery id and then this will be also lottery id because again we have an ex an implicit lottery id getter so lets say set lottery id lottery id and i guess lets just go ahead and print this out to the console lets see if this much is working so far all right so lets clear that out connect wallet okay to perfect thats just what we expected because we played one game and so now were on lottery number two right all right so now that weve got the lottery id working we need to come back and restructure our get history function because basically the main problem that were trying to solve here is that we have a mapping in solidity and so we need to translate that to something a little more useful in the javascript world which would be probably like an array of objects for this so since were going to do an array of objects lets go back to our lottery history and well make sure well initialize it with an empty array okay and so what were going to do is were going to come back here and were going to create a for loop and were going to use the lottery id to know how many iterations of the loop to do so im going to say 4 let i equals and so well have that lottery id here but i think we need to do parse parse int first because im pretty sure this is coming back as a string okay semicolon and then well say i is greater than zero so by the time we reach zero well stop this so well do two one stop the loop and then i we want to decrement it every time through the loop you know with a traditional javascript loop you would start at zero and count up but here were sort of doing the opposite all right so weve got our loop set up now for each iteration ill tell you what lets just console log something just to make sure this much is correct console.log and then well say get history history right now lets figure out where were going to call this from so lets comment this out temporarily get history and so since we have a dependency on lottery id i think we should call it from here and we should probably pass in the lottery id directly from here since we cant rely on the state to have been updated necessarily that soon so well say id here and then well just switch this to id there we go all right lets see if this much works get history okay connect wallet wait what were we logging get history okay cool yeah it looks like that loop is working um so lets go ahead and continue all right so lets attempt to now put some of this data inside so what do we want to do here we want to reference that mapping each time for the current id that we have in context so lets uncomment this and so we got to change this a little bit so lets do this one line at a time so first were going to call lottery history right but we this time we got to pass in the id okay and thats going to correspond to the uint right here okay this is going to be a required parameter for this getter so then this is going to pass back an address right winner address so now we have to do is construct an object that we can then push into our history array so lets do it like this lets say const um history object im sure i can think of a better name for that but you know for now lets just do this history object dot id equals id and then history object dot address equals winner address all right so then we just need to see set lottery history and we need to push this into our state array all right so to update this array um well lets see whats it called lottery history right so we would normally do push but here we need to do do it a little bit differently lottery history okay and then and the reason were doing it this way is because we never want to mutate state directly okay to prevent errors and side effects and things like that so were going to basically copy the existing array and then add a new element to it which is going to be our history object all right so hopefully thatll its the id history object okay history object dot now what is this oops i think this there we go id there we go i just forgot us return there okay that looks good all right so lets just check and console log the object just to make sure everything is working up to this point so im going to say json.stringify since its an array of objects we wont be able to see that by default and im going to say lottery history all right so lets go ahead and save that and see if were seeing anything in the console oops json stringlife stringify there we go all right lets do connect wallet empty object hmm okay why would we be getting an empty object here console log four oh okay i think this is running before were getting all of our async await methods to return thats the problem thats why its empty so how do we fix that all right lets just try moving our console log back into the get lottery id function below our git history and lets just put an await keyword here so that were ensured this runs once this is completed lets see if we get any better results from this oops okay oh yeah there we go perfect thats exactly what we wanted okay so now weve got oh why is this id2 and address zero oh interesting i guess thats correct for id2 since we havent played the game and we havent entered anyone into the game for id2 but i wonder why were not getting id1 here um maybe were lets see lets look at our loop again let i equal parseint id okay i is greater than zero thats correct i or d incrementing it every time so we start with two right but i equals parson okay so thats an integer so were able to decrement it maybe theres something wrong with this line here um console ill get history oh i see where this needs to be i not id right because weve assigned id to i and thats what were actually decrementing so that really represents the lottery id at this point in the code so lets save that lets try it again no i dont want that connect wallet okay there we go thats better but um address did we do the same thing for address probably yeah we need to reference i instead of id here lets try that again uh nope still getting a zero address there we go thats what were looking for right because this was the winner the first time that should correspond with my wallet address one yeah c143 okay great so thats finally working okay so weve got a reliable history right now so lets set a success message using that history and so what do we want to do here we want to basically right now were on id 2 right and as soon as the winner is paid it increments the id of the lottery so we actually want to look at the last one and get the address from that so lets go to our pick winner function our handler here all right so once this is done so well go under here on line 73 we want to set a success message but lets first create a variable well say const and well say winner address equals now at this point we should be able to reference our state object our our state object directly so lets say lottery history now remember this is an array so what position are we looking for lottery history at lottery id minus one right since thats already been incremented lottery id minus one okay so history lottery history at lottery id minus one and then dot address that should give us the winner address right so lets set our oops we want to set our success message says success message and well say the winner is and well reference that winner address above okay great so we could go ahead and test this right now but lets just go a little bit further and try to get some lottery history going in our right side panel here like we still this is the last thing that weve got hard-coded so lets try to fix that and then well test everything together okay so what do we need here lets go down to our lottery history code and take a look um lottery number one winner all right so what i guess were gonna have a different entry for each history entry so basically what well need to do is create a loop and loop over the lottery history array and then output one of these elements for each entry so lets try to do that so were going to say first we need some curly braces here so we can write javascript inside our jsx all right so this is the array right lottery history so well want to do a check similar to what we did down here lottery history lets put this in a parenthesis lottery history and lottery history history dot length is greater than zero and now we can start our loop lottery history and so inside here lets just say item okay does that look correct yep all right so inside of this one for every item were going to return one of these entire objects here so lets copy that and paste it into here whoa all right ill just fix the formatting a bit this needs to be tabbed over because were going to do a return so were going to return one of these for each one so lets just uh see if this much is working see its good to check its small increments here um what does it like here lottery history oh i forgot the map all right map there we go lets see if it likes that any better okay lets just clear that out and lets do connect wallet cool so were getting at least were getting two entries so now we just have to add the values in there and you know what lets add some padding i saw that looked a little bit tight there margin top three maybe lets try that yeah that looks better okay okay so the first thing we want to do is create a variable here right so lets see can we do item dot what do we call it id or lottery id forget now i think lottery id right just id so id lets see if that much is working perfect now we got two in one okay so the only thing left to do is the address so lets start here and well do item dot address i believe thats right lets just check that real quick cool okay and then well sort of do the same thing right here in our url so well have to do some refactoring here and well make this a string template literal lets see how is this going to work so we delete the actual hard-coded id we paste in our item.address closing quote and closing curly bracket oh whoops we lost something here didnt we lets put that back in all right lets check that so lets see if this takes us to the correct address here oh no something went wrong there oh i think i need a dollar sign here right i always get the the temp the template a string literal and the react syntax mixed up so lets try that again yep thats more like it cool all right so you know the other thing is we dont really want to show the current lottery right so how can we fix that how can we fix that lets say if is not equal to lets see how is that going to work is not equal to lottery id right so if well say if lottery id is not equal to so in other words as long as were not talking about the current lottery lets go ahead and display it lets see if this works okay something wrong with that no lottery id is not equal to uh you know what maybe we dont need to check for type because one of them is probably a string and the other ones probably an integer yeah exactly cool so now were just showing the previous winner and were showing it multiple times here which i guess is another thing to figure out all right cool so our our history our lottery history ui is in a good place seems to be outputting the history correctly and weve also got it wired up to output a winner so lets do another test and lets like enter a few of our wallet addresses into the lottery lets do pick a winner and see if were getting that success message now so this is basically the final test just to make sure everything is working correctly so im gonna disconnect my wallet and start fresh here disconnect yep go ahead and refresh the page all right so lets go ahead and connect our wallet and so well sign this transaction to connect us to the site all right and so that triggers our usefx hook and were seeing the ether were seeing zero players which is correct and were seeing the lottery history so far so good so uh lets go ahead and play so were were still set to address number one so well enter him in and weve got our minimum amount there lets confirm that and well monitor and metamask to make sure that transaction goes through its still pending all right that succeeded so lets go ahead and choose another account oh it looks like were low on ether so what im gonna have to do is send my accounts two and three some ether all right lets do that first so im gonna copy account number two i go back to account number one and im going to do send lets send him like half a ether confirm and lets do the same for account number three oh account number okay so yeah its called attacker but thats just because i was doing another video um no malicious code in this this one so well copy that go back to account 1 and well do send and well send him 0.5 ether as well hes an ethical hacker in this video hes helping us test the lottery contract all right so thats pending while thats pending lets okay we can see that account 2 is now loaded with some ether so while were still waiting for the attacker account lets go ahead and so well connect account 2 to our lottery application all right now we can go to play now must provide an ethereum address good were seeing one player entered all right so were now connected all right lets go ahead and confirm and hopefully we should see the players card incremented in just a few seconds all right great that went through successfully and now well lets see lets switch to account three which is the quote unquote hacker account and great now hes got point five ether so well connect him all right lets do play now well thats weird were getting this error like the first time must provide an ethereum address okay i think we have to hit connect there we go lets try it again yeah thats right because were not setting the account zero as address until we actually hit connect wallet there we go so lets try play now again all right confirm and that transaction is pending looks like its successful and so we have to kind of hit connect wallet to get this players to update so thats maybe another thing that we could think about fixing all right so lets try pick a winner now remember were still on the third account so this should fail lets try that failure pick winner now hopefully our smart contracts going to recognize that this is not the owner so well confirm thats pending hopefully itll get rejected if not then weve got a major problem all right so the good news is that our success message is working and were outputting the winner the bad news is that we were successfully able to pick winner with um an account other than the owner so i dont think its a smart contract problem i think its a problem with how were storing the address and as you can see sometimes we only saw updates when we connected the wallet so i think what we need to do is um sort of update all of these variables history players when we when we invoke play now and pick winner as well as the current address so lets see how we can actually do that so looking at the behavior here the fact that account number one was the winner again and the fact that despite switching to account three we were able able to invoke pick winner sort of leads us to suspect that probably you know despite changing our accounts in metamask its not syncing properly with the site and the site still sees account one as the current account so if we look at the metamask docs it looks like there is an account changed event here that we can use so we can do ethereum on accounts change to detect whenever a new account is set as primary in metamask so lets go ahead and try to use this so we can lets see well go somewhere closer to the top i guess underneath use effect we can say window.ethereum dot on and lets see what was the event accounts changed right and then we pass in a handler as the second function all right so here what well want to do is sort of replicate the code that we had in the connect wallet handler to set that new account okay so yeah we want this code right here accounts so im not sure about this syntax accounts at zero im not sure if this will still point to the main account or the one thats actually in focus so to speak i wonder if the docs say anything about that all right lets try this and see ill tell you what lets just output account zero at this point and see what it is accounts zero there we go lets go ahead and save that lets go back to our site oops oh async function all right so this needs to be async right here there we go save that lets try again okay so lets try to change our accounts in metamask and well switch it to account two this time account two okay perfect that is outputting the correct one oba okay thats good so lets get rid of our console log and so were now setting account one in this case thats the account that we changed to so we just verified that so now well have the correct account so another thing i think we should do because we were sort of having to click on connect wallet when we shouldnt really have to after some things like enter lottery and pick winner so what if we take all these and extract these to a common function lets go right underneath here and lets just call it update state and so well gather all of these sort of together and so now well say update state inside of here and now we can also kind of have some more leverage to call it from other places as well so lets do it right after our enter lottery right after the success anyway and lets do it in our pick winner lets see where do we want to do this i guess we can do it right at the end here all right so lets with that with those changes lets try our test again okay so im going to go ahead and disconnect were going to change back to account number one and were just going to disconnect i guess weve got to disconnect all of these huh okay just connect disconnect disconnect good lets clear that and lets refresh uh oh window is not defined why is window not defined all right well i guess were going to need that same check that we had in connect wallet handler lets just copy this real quick yeah make sure the object window object exists you know we could probably just put this all into use effect couldnt we because we just kind of want this to run one time to set that handler lets try that and that way we shouldnt need this check right lets get rid of that lets see if this works better save that all right lets reload all right so hopefully thats going to work the way we expect so lets do our experiment here from scratch connect wallet all right so well connect wallet number one oh no okay whip 3.8 okay so web3 is not available here so were kind of in a chicken egg in egg scenario so we cant run this in use effect because weve got to make sure that we have a web 3 instance all right so i think this code is actually going to go in our in our wallet handler we should have foreseen this so where can we put this lets just put this sort of at the end here all right i think this should work here lets try again each child on the list should have a unique key property where is this coming from index 87. this is probably referring to the lottery history yeah yeah so we need a key property here and lets see lets say i think thatll be good enough for now okay lets start our test over lets disconnect here all right starting fresh connect wallet great so far no errors and well go ahead and connect account number one all right now well do play now okay well sign this transaction okay players are still at zero hmm we want that to update as soon as we enter into the game so lets go back to our code enter lottery handler okay update state so i guess this just hasnt incremented at the time that were calling it lets just try to continue our test here oh there it goes i guess i was maybe just waiting for the confirmations to go through okay so lets heres the real test were gonna see if our on change handler is working lets go to account 2 and well do connect ok play now confirm all right and lets open metamask to monitor that pending okay great so thats been incremented i was just impatient the first time all right lets switch to our third account okay so im gonna go to my friendly attacker account and well say connect good lets do play now and confirm that transaction monitor rinse and repeat so yeah it takes just a while for things to go through and get confirmed into the blockchain so weve got to be a little bit more patient than normal with a centralized model you know wed get an answer right away but hey i think its worth it for decentralization there we go three players okay so now note that were still on account three and so lets try to pick winner and hopefully well see this rejected this time if our on event handler is working correctly okay confirm well it looks like thats not working because were still getting the same result here darn it well at least we fixed some of the things were seeing over here lottery history we got a new entry our players are you know being incremented our pot is being everythings being sort of incremented and updated in real time so weve still got the issue of you know our wallet provider or our you know web3 instance is not detecting our account changes all right so theres one improvement or correction that we need to make in the pick winner handler and that is that we cant really rely on this lottery history react state variable because it will not have been updated by the time we reference it here so lets get rid of that and what we want to do is actually call history from the smart contract so were going to want to do something similar to this that we have on line 42 so im actually just going to grab this right here and were going to go back down to line 77 and paste that in so i can say lottery id call okay and that should give us the winner address and so one other thing we can do is we can reset the error messaging any time we call pick winner handler or enter lottery handler okay and then the one other thing that we were seeing is that for some reason we were allowed to invoke pick winner even when we werent on the owner account so lets just console log our address at this point okay and lets just say address from pick winner and lets just make sure that its actually reflecting the correct address all right so with those changes lets do one more pass through our testing routine and see if we see some improvements here all right so ive created a couple of new accounts for this test and the reason i did that was just because wed seen account one win like a lot of times so i just want to make sure that you know we exclude that from the test and make sure theres nothing hard coded or anything weird going on with you know the xero position account so with that said im gonna go ahead and click on connect and this time weve got accounts four through six available so im gonna start with the count four and well well add four five and six okay so were connecting and lets do play now and well go ahead and accept that and enter ourselves into the lottery here all right oh we dont need to connect we need to actually switch accounts so we will switch to lets see well do it manually here well go to account number five there we go and we want to connect great lets enter him in all right well accept and then lets just make sure we got a couple of entries here great still waiting for that second one in the meantime well go ahead and enter account number six count number six connect all right and lets do play now okay and well accept that entry all right so weve got everyone entered in were still waiting for the some confirmations on that last one there but what we can do is start to record the balances i mean the actual balances in the wallet just so we can really tell who the actual winner is so im gonna grab the balance for account six and well go ahead and update these to reflect our new accounts so well have four five and six all right so lets check the balance on account five all right and then well do the same for four theyre all pretty similar so well make sure we note these here yeah theyre almost the same so thats good it should be easy to tell whos the winner and so with account 4 still selected i will go ahead and invoke pick winner okay well confirm that and lets see what happens here all right that transaction is still pending all right so our winner is 302c which is looks like its the fourth account and we can see that that balance has been incremented all right so the problem that im seeing here is that so far every test that weve done the first account that weve entered has been the winner so that definitely raises a red flag and um if i think back to our lottery contract lets see what exactly happens when the winner is being determined right so we we do pick winner we get a random number and so that sort of kicks off the call to the chain link oracle so thats some off chain processing and i think whats happening is were actually not getting the result before pay winner is invoked so were doing get random number were calling that function right that comes back uh where is it get random number get random number um and then theres a call to request randomness thats in the chain link contract eventually fulfill randomness thats a callback that gets called with the result of the random number and so then were setting random result which is a state variable from our contract up here right so i have a feeling that whats happening is by the time we get into pay winner we dont actually have the result back from the randomness and so this is always equaling zero i dont know if this is undefined or if its zero or what i think zero is what it initializes to zero divided by by players length so were getting a zero index every time thats why the first player entered into the lottery is always winning so unfortunately i think were gonna have to make a change to our smart contract and were just gonna have to decouple the randomness from the paying of the winner if you know what i mean and if you think about it thats okay because in a lottery you know wed have players entering the system and during our testing were entering people into the lottery and then were trying to get the results immediately after that so you know in a real lottery youve got people entering in and then some time elapses and then sort of the winner is chosen so its okay if theres some time between those two events so i think what were going to have to do is decouple this pay winner and thats going to be pretty easy to do i think all we have to do is remove pay winner from here and then well just have to invoke that as a separate function call and then one more thing we can do which we probably should have done at the onset is to just have a require statement and just check and make sure that that random result is greater than zero so ill say require random result greater than zero and then lets say must have a source of randomness before paying before choosing winner okay semicolon okay so um lets go ahead and we need to copy this entire thing because remember were still in our front end app yeah so lets go back up to our contracts folder and we can just replace all the code in here with our updated code all right so lets open our terminal again from our lottery folder and rerun our migration so ill say truffle migrate network rinkaby and hit enter all right and so for some reason its not really detecting a change because the migration should be run whenever code is changed in one or more contracts but for some reason so we saved our file yeah so what we can do is rerun this with the reset flag which will just push all the contracts regardless so lets do that and im going to add a reset flag and lets try that again alright this will take a few minutes so ill go ahead and pause the video here alright and that deployment succeeded that time so again well go back up here and lets go ahead and grab the contract address go ahead and copy that now were going to need to go back into our front end project and we need to go to our lottery.js and just replace the contract address right here with the new one it is actually good practice because it kind of shows what what you need to do if you find a mistake in a smart contract and you need to redeploy it to a new one okay so lets go back to our front end terminal clear this out and so what we want to do is rerun our compile command to generate a new api so npm run compile all right and once thats done i should have cleared the build folder first but uh well just wait for this to complete and then well grab that new abi and paste it into our right up here actually in our lottery.js file so well just pause the video alright great so that compile step is complete so we can go back up into our build folder and again we can open up our lottery.soul abi and just go ahead and copy everything bring it back over to our lottery.js file and everything starting from about here well replace okay perfect great so now our front end will be pointing to our or well generate a new contract instance with those updates okay so lets think about what we need to do for our front end code all right so lets look back at our contract smart contract so now were going to break this into two parts right we have pick a winner which is going to really now end with the generating of that new number so well do pick winner and then with pay winner well have to have that as a separate function so lets go ahead and build that out so lets go right underneath our pick winner handler and lets create a pay winner handler async its going to be pretty much the same as our other handler functions here you sync all right so again well clear all of our messaging error and success then well do a try catch clause here as were doing with most of our async contract calls catch error okay and we can sort of borrow some code from up here well say set error error message and then down here well say await lc contract dot methods dot pay winner okay now lets see this ones going to be ascend as well so we could just copy everything up until here paste it right down here there we go all right what else do we need here so actually what we need to do is sort of move this code down into pay winner right because previously the pay stub was happening here so we can just copy everything from there and well paste it right down below here all right so one thing we want to do is actually check to make sure the random result so this pick winner handler how is this going to work now so i dont think we need any variable to check our result here i think we can just do that in the pay winner handler so um the first thing we need to do is do we need another await this can just be a call so im just going to copy about this much and methods im going to say random result actually we have this check in pay winner dont we all right so yeah thats right our smart smart contract should be thats right our smart contract should be taking care of this um of this check for us so okay so i think we just need a pay winner handler button so lets go down in our code to where we have our first two buttons and were just going to copy a section from the last one because its going to look very much the same its also going to be admin only so we can leave that text well say pay winner and well say well choose the pay winner handler so really we just have to change one word here pay winner handler um you know lets just change the color a bit so well say success is success button and well change this to pay winner okay oh and one last thing we need to do is change the function in our click handler so lets go back up to um where is it pick winner right and we forgot to change this to pick winner there we go all right go ahead and save the file i think this looks looks good so lets go ahead and do one more test all right so this is our final test and hopefully with all the improvements weve made everything will be working flawlessly this time all right so dont forget since weve deployed a new contract we need to send it some new link okay so again you can come back to the and request some test link i think ive still got some so im just going to send some to my contract and ive gone ahead and pasted the contract address right here to notepad so i can go ahead and just click on send i want to change this to link and lets go ahead and send 20 link okay and well go ahead and confirm that 20 should be more than enough by the way i think 10 would be fine as well so okay once that is we can go ahead and start testing in the meantime while thats sending were waiting for that transaction so okay lets start fresh here were going to connect a wallet and well use account number one well go ahead and connect all right and well go ahead and enter him into the lottery confirm all right lets enter in account number two so well switch over to two well click connect and well click play now and well go ahead and confirm for account two all right lets switch over to the friendly attacker account ethical hacker and lets click play now and go ahead and enter that one in and ill tell you what lets go ahead and just enter in the remaining account so we have a really good test here so im going to switch down to four connect play now confirm rinse and repeat we will select account five okay connect play now and confirm one more time with feeling so well go to uh cow six there we go connect play now and i said and where are you here we go confirm okay cool so we should have like five and we should soon have six players in the game and well just wait for that final player to appear and there we go okay so we got we got six now so were still on account six lets go ahead and attempt to pick winner now if you remember before this should be a owner only function but we were able to do it earlier with other functions so lets see if our refactoring has made a difference okay that pick winner is still pending so well see what happens here and we got a failure okay thats actually a good sign so with any luck that problem has been fixed with our refactor so lets go ahead and switch back to account one and try the same thing to test that theory all right so back on one and again well do pick winner okay and its going to ask us to confirm and our error messages been cleared excellent so weve got a success there okay so lets try to immediately pay winner and my theory is that this should not work immediately because you know as we saw it takes a couple of minutes and we have that check for the random number so lets see what happens here yep and theres our error message okay so far this is looking great so im just gonna pause for like five minutes here because i remember in the past it took up to five minutes for that random number to actually get generated we could add another button here to check it and periodically sort of press that button and see if were getting a random number but i really dont want that in my lottery interface so im just going to wait im going to pause the video here and well come back in five minutes and try this again all right guys so um it has been more than a couple of minutes so lets go ahead and try again so well do pay winner still on account one great go ahead and confirm all right and weve got a winner so that means our random number is in place and its been successfully used to randomly pick a winner and weve got zero ba if i remember correctly i think thats account two yep zero ba there we go all right so it looks like up to this point everything is working correctly and um everythings cleared out here weve got a winner for lottery number one so everything is working great at this point so it took us a little bit of work and some experimentation and some refactoring and stuff to get this all working but hopefully you guys got something out of it and sort of saw what it looks like to debug these things and even have to make changes to the solidity contract itself and redeploy so all right guys so that is all ive got for today um hope you enjoyed it and uh a couple of people specifically requested this video so you know i want to thank them for that great idea i think this was a pretty good exercise to go through so yeah um if you guys are enjoying the content on this channel i definitely encourage you to subscribe and other than that i hope to see you in the next video and until then take care bye now you In this project-based web3 tutorial we build a completed lottery dApp with a focus on how to build a UI for a lottery smart contract, using the web3js library.Topics covered include: the web3js library, connecting a Metamask wallet, application binary interface abi, NextJS, Truffle, Ethereum Rinkeby testnet, Chainlink VRN, deploying a Solidity smart contract to Ethereum and more. Completed project code: Lottery Smart Contract Part I HR679xTt8tg Lottery Smart Contract Part II _aXumgdpnPU Ether faucet on Rinkeby testnet: LINK faucet on Rinkeby testnet: Address to LINK token on Rinkeby testnet: Blockchain,