chainlink casinosBuild a CoinFlip Lottery Game for Ethereum using Chainlink VRF V2 and Hardhat - Solidity Projects

Liquity LQTYBinance Research Liquity is a decentralized stablecoin protocol that allows users to mint stablecoin LUSD by depositing ETH as collateral. LQTY is the native token of the project. The current use case for LQTY include: Staking: Earn the fees generated from borrowing and redemption fees in LUSD and ETH. Dogecoin Fiyatı 1 DOGE Fiyatı Kaç TL? Eder Piyasa Değeri Ve Anlık Bu Sayfada 1 Dogecoin DOGE fiyatı ne kadar, 1 Dogecoin DOGE fiyatı kaç TL oldu?1 DOGE fiyatı kaç TL Eder, Online ve Anlık Dogecoin DOGE Fiyatlara detaylı grafiklere market hacminine son 24 saatteki değişimine bakabilirsiniz.. Bugün 1 Dogecoin DOGE fiyatı 1.61 ₺ TL dir. Ve 1 Dogecoin DOGE Fiyatı 0.083594 $ Dolar dır. 1 Dogecoin DOGE ile 1.61 ₺ Türk Lirası chainlink casinos Build a CoinFlip Lottery Game for Ethereum using Chainlink VRF V2 and Hardhat - Solidity Projects
chainlink casinos Sudden crypto drop sends bitcoin to... Build a CoinFlip Lottery Game for Ethereum using Chainlink VRF V2 and Hardhat - Solidity Projects
Randomness a decently hard problem in computer science ever since computer science existed and its fairly important in lottery games or any sort of games of chance today were going to build a coin flip smart contract on the ethereum network where users can place a bid predict whether theyre going to get a heads or tails and then win a prize if its correct unfortunately its not easy to get Randomness on a public blockchain network like ethereum any sources of Randomness you take from the blockchain are also public to other people and its fairly easy to game that and to predict what your so-called Randomness is going to be so to solve for this were going to use chain link vrf chain link vrf is this service by the chain link Network called the verifiable random function that can provide provably fair and verifiable random number generation to your smart contracts the random number they generate are associated with a cryptographic proof on how it was generated and ensures that those numbers those results could not have been tampered with or manipulated by any single entity it allows us to build like lottery games games of chance and other non-gaming use cases as well so to get this going I created a folder on my computer for this project and set up a hard hat project in it if you dont know what hard hat is or how to set up a hard hat project go check out my video on hard hat best practices its going to be linked in the video right now but Ive set up a basic hard hat project over here and Im gonna open this up in vs code and youll see that Ive deleted the default log dot solve smart contract because were going to start writing our own so lets name it coinflip.solve all right and lets do the basic stuff uh were just going to do pragma solidity 0.8.17 which is the latest version at the time of writing and lets just Define a simple contract block called coin flip now to use chain links vrf we have to use the we have to use their given base smart contract its called the vrf V2 wrapper consumer base and to get this installed it ships as a npm library so in your terminal type in npm install add the rate chain link slash contracts this will install the npm package that contains their base contracts for vrf as well as some other things that chain link provides once this is installed well go back to vs code and import the contract we need so import at the rate chain link slash contracts slash SRC slash version 0.8 slash vrf V2 wrapper consumer base thats all all right once weve imported this Well Inherit this into our own contract so well say contract coin flip is a vrf V2 wrapper consumer base and then we can get started with writing the rest of the contract now for a coin flip lets lets think about lets think about what we need right so for sure we need a function uh where the user can make a prediction and the user can sort of predict whether its going to be a heads or a tails and thats something that the absolute basic thing that we need now the choices for heads or tails theres only two choices so we can make it a little bit easier to read um by defining an enum for it so well say enum coin flip selection and give it two options heads and tails all right and you can the user can pass this option in as coin flip selection choice and well do something with this choice the second thing we need is we want the user to be able to bet I want them to be able to bet some money on the coin flip and for that well mark this as a payable function the external means that external users can call it and the payable means that they can attach some ease along with this flip lastly we want to return the request ID so when the user calls flip were going to send a request to chain link to return us that require a random number back and when you do that it doesnt respond immediately it takes a little while for a chain link to generate and send you back the random number instead it gives you a request ID that you can later use to check for the random value that came back so were going to return that request ID back to the user so they can keep an eye on the results of whether the prediction was correct or not and this creates the basic function signature for a flip function now to were also going to just create a couple of events that we will emit for when the user requests a coin flip and when the user gets the result back so were gonna say event coin flip request and were gonna just pass in the request ID were gonna emit the request ID and well do a second event coin flip result where well give back again the same request ID along with a Boolean saying dead win so this can either be true or false depending on the result of the number did the user win or not finally to will create a struct to kind of track some data about the coin flip status so create a struct called coin flip status this will track different information so basically the basic things we want here at least are the random word um so chain link returns back random numbers the terminology for it is a random word word is a way of representing is is computer science terminology for a certain group of bits of a fixed length so we get back a random word but its not like an English word and get back a random word from chain link and then well also track the address of the player well track whether or not they won will track whether or not chain link has fulfilled a Randomness request yet and well track uh what choice that the user originally make and theres actually one more thing we want to track is the fees that was paid so chain link doesnt offer this service for free it costs the money to run all the infrastructure and the entire decentralized network of operators that are giving you back your random numbers so as payment you need to have the chain link token the link token and you pay them in the link token to request random numbers from them so depending on how complex your request is how many random numbers youre requesting and things like that your fees can vary a little bit but were just going to keep track of how much fees did we end up paying for the randomness request now that we have this struct lets finally just create a mapping from U and 256 to a struct instance and this will be a mapping that we can publicly use the users can publicly use to check up on the status of their coin flip and this will be a mapping from the request ID to the status structure um all right so weve set up like the basic skeleton of the contract now to get this actually working what needs to happen is you need a few different things so first of all if you go to the chain link viewer of website and go down to supported networks youll see that chain link is available on a variety of different evm networks what were interested in for now is the girly test net if youre building this for the ethereum mainnet or the polygon chain BNB chain or anything like that choose the correct values from in there in this tutorial well just use the girly test net for the early test net specifically what we need are these two addresses the address of the link token and the address of the vrf wrapper so this tells us the link token we need this because were going to be making payments uh in the link token to the vrf coordinator actually which is responsible for kind of sending out requests to the chain link Network so were going to be paying them with the link token and the vrf wrapper is the sort of easy to use Smart contract that well be talking to to request Randomness which further forwards the request to the coordinator um cool so take these addresses copy the link token address and were going to save it as a constant in the contract so were going to say address constant link address equals this and were also going to take note of the vrf wrapper address over here so save it as an address constant vrf wrapper address awesome okay now that we have that um theres a little bit more configuration we have to do were almost done I promise a little bit more configuration we have to do first of all we need to define a lets lets set a price like how much money should does the user need to bet to do a coin flip so lets define an entry fees and for the purposes of this tutorial Im going to keep it fairly cheap at 0.001 ether so they pay this money when they make the prediction if they lose they dont get anything back if they win they get twice this money back and then well also do we also need to define a oh let me also Mark this as a constant variable and the other thing were going to Define another constant quality callback gas limit and this is something thats required by chain link this is basically saying up to how much gas are they willing to spend for you when they send you back the result because the way they send you back the result is they actually call a function in your smart contract and they need to pay gas on the ethereum network to call that function in your smart contract of course so you need to Define like how much what is the upper limit how much gas can will that function be using in the worst case um if it costs more gas than that youll just simply never get a response back from chain link because they wont be willing to pay that much gas um if its within that gas limit theyll send you your result back and the value of this uh affects how much your request is going to cost so how much fees youre going to have to pay depends on how much gas they predict theyre going to have to pay when they send you back your result so in this case Im just going to put it down as one million guess limit um then we need to Define how many random numbers do we want we want like one random number five random numbers Etc at the maximum you can get is 10 random numbers in a single request um in our case we just want to one so well just say number of words equals one and finally we need to Define how many confirmations do we want chain link to wait for before generating a random number so basically when you request Randomness how many blocks should it wait before trying to send you back the result and this is done so that nothing can be manipulated on the Chain the more blocks you wait the more the higher guarantee there is that your transaction is perfectly safe and fine wont we reverted and wont be rolled back the minimum number you can use for this is three blocks you can increase it up to 200 but anything less than three will not work cool so now that weve defined these things the only step left for setting up the vrf contract is setting up a Constructor and in the Constructor initializing the vrf V2 wrapper consumer based contract and you need to give it the link address and the vrf wrapper address that youre using again this varies chain to chain so you just give it the ones we are using the ones for the girly test net amazing once this is all done we can now start writing our flip function and get into the actual meat of this game so the first thing we want to ensure is that the user should have paid the entry fees that was expected of him so were just going to do a require statement saying were going to require that the message.value is equal to the entry fees and if it is not we give an error the entry fees not sent or it may be incorrect um so well check for that once assuming they sent the entry fees now were gonna make the request for a random number so were gonna say even 256 request ID equals request randomness and this function is coming because we inherited the consumer based contract so this function is present inside there and it takes in three arguments it takes in the Callback gas limit for sending back the result it takes in the number of confirmations or the number of blocks to wait for before attempting to send back the result and it takes in how many random numbers do you want to get back so this will give us a request ID instantly and submit the request so now lets create a status struct to store certain information about this request um so were just going to do statuses and map it with the request ID index the request ID and were going to make it equal to this coin flip status struct where the fees we can calculate the fees by doing vrf underscore V2 underscore wrapper dot calculate request price and it needs the Callback gas limit to calculate that this function again its coming from the uh well its not really coming from this contract but the vrf V2 wrapper this is basically just an interface around the vrf wrapper address and when we provide this address to the parent contract here it creates this interface around that address so this function exists on this smart contract basically so were going to call that function and calculate the request price and store that in the struct were also going to store the value of the random word right now we havent received one so were just going to default it to zero were going to keep a track of the player address so that will be the person who sent this transaction call this function so thats message dot sender then were going to keep track of did they win yet so far if we dont even have a result so we cant say so were just gonna say did win false and has this request been fulfilled yet no the chain link hasnt gotten back with the response we just sent out the request so false and then finally what was the prediction they made what was the choice they made and weve keep weve kept track of all of this and the mapping weve created this struct um the last thing to do in this function now is to just emit the coin flip coin flip request event and it just takes the request ID and lastly we just returned the request ID to the user so thats it for the flip function now after you send in the request Ive said that chain link needs a function chain link calls back a function on your contract to send you back the result so this function we need to write that as like what happens when we get back the result it needs to be a specific type of function so it must be named fulfill random words and it takes in two arguments U and 256 request ID and a un256 array containing all the random words in our case were only getting back one random word so the array will only have one item if you request more words the there will be more items in this array and this is an internal function um because this is called by the vrf coordinator uh external users such as you and me cannot directly call this function and basically Whats Happening Here is here you send out the request to chain link right they wait for three blocks they generate the random number they generate the proof for it later on they come back and they call this function on your contract and they give you these two values they give you the request ID and they give you the random words now all the complicated cryptography stuff like verifying that the random number was fair um the provably fair and it was verifiable and ensuring that the cryptographic proof is legit that is all taken care of us by the base contracts the base vrf contracts and the wrapper the coordinator and things like that for now like as for our us and developers we just trust these values that are coming through us if something was wrong if the proof was wrong or something was manipulated chain link will automatically throw an error before we even get to this point so now uh Team links basically called back to us theyre saying for this request ID were giving you these random words do what you want with it right so we need to do a few things we need to make sure that this request ID actually exists and its not something that maybe could have sent by mistake or something like that so to do that we can just check that the fees is greater than zero so we paid a certain amount of link for this request at some point and that guarantees that we sent out a request at some point if its not greater than zero can throw an error saying this request was not found assuming that is okay assuming we did make this request we can update the struct the coin flip status struct and say that this request has now been fulfilled so fulfill this true and then we can say that the random word we got back is equal to random words zero because we only have one item in the array were only requesting one random number so its just going to be the first number in the array with that in mind now lets try to figure out um whether it was a heads or a tails the coin chain link will give you a really large random number like a huge huge huge random number so since were kind of won a 50 50 chance between heads and tails what we can just do is we can see if the number is even or if its odd right and if its even if its odd well say its heads if its even well say its tails so lets define the result so well say coin flip selection result and well start it off with a value of heads right but if the number was even if random words zero was perfectly divisible by two I.E the number was even then well update the result to be Tails instead and if it was odd then it just continues to stay heads so we have the result and now we need to check if the players prediction was correct or not so we can just do that by checking if the choice they made is equal to the result we got then they they won right so request ID that date win equals true and well also send them their money back so well send back so to the payable player address request ID dot player will transfer them the entry fees multiplied by two so twice the entry fees uh they double their money and if they didnt win then none of this will happen and the money stays within the contract and finally we will emit the coin flip result um we will emit the coin flip result and we will say that for this request ID the player did win or not they give it back the value of deadwind which is false by default but is that too true if the choice was equal to the result amazing so this basic stuff is done um one more function I would like to add just for keeping an eye on things is the view only function called get status which will just take in a request ID itll be a public view function that will return the struct back to us so the coin flip status in memory and it just gets Returns the status for that request ID Ill use this to keep an eye on things great okay with all of this in mind one more things is the absolute final thing we need to do is Im just going to Mark The Constructor as payable as well so well start off the contract with a small amount of ether and then well try playing the game so since if you win the game pays you back twice your entry fees if the contract doesnt begin with any balance and we happen to win when we do the coin flip it wont be able to transfer the money to our account and the transaction will fail um this can obviously make this a little more sophisticated by having a separate sort of redeem price function and you can track whether the person has redeemed their price yet or not so just in case the contract was out of balance at some point and fulfilled random words failed they can come back and kind of like withdraw their money at a later Point once the contract has some balance in it so but this is just a basic example and were assuming the contract does have balance to pay the user um with this in mind lets lets deploy this contract so I have a basic script hard hat script written again uh if you dont know how to what this is or what this is doing go check out the hard hat video and how to set it up uh but basically were just deploying the coin flip contract were starting it off with 0.001 East as part of the deployment then were going to wait a little bit 45 seconds and then verify the smart contract on etherscan so we can play with it and have it available there with all of this setup Ive also set up my configuration file with all the necessary deployment configuration for the early test net uh with that in mind lets run the deployment script and this will take a while as it sleeps for 45 seconds and stuff so well be back once this is done all right were back and the contract was deployed and it was verified on etherscan so lets open up this link and youll see the contract was deployed over here now before we start playing with it before we start calling the flip function I said we need to pay for the randomness requests using the link token right so if we just call the flip function right now the smart contract doesnt have any link tokens um to pay with so the first thing you actually need to do is go to the chain link faucet the links in the description go to the chain link faucet and request some test link on the girly Network once youve gotten that test link you can send it to the smart contract and we can start playing also if the link doesnt show up in your metamask um go back to the supported networks documentation on the chain link website and click link token add to wallet and this should pop open metamask and ask you to add a link to your wallet so it will Now display the balance of link and you can easily transfer it so I already claimed some link tokens I have 16 link on me you should be able to get it from the faucet once you do that go to your contract copy your contract address and send it some link so you can pay for Randomness for now were gonna send it one link send it whatever your heart desires send it one link its a at least send it half a link just to make sure everythings good um and while we wait for this to happen well see that the contract code is all here we have the read functions the get status and the status is mapping and we have the right functions flip and draw fulfill random words this is coming from the parent contract the vrf contract however we cannot actually call this function because if you look at this file over here this file actually uh I cant open it yeah so if we look at this file over here we are refv to wrapper consumer base dot Sol well see that the raw fulfill random words can only be called by the vrfv2 wrapper address so even if if we call it the transaction will just fail so you cant actually call it but its there um so my link transfer has succeeded if I refresh this page now etherscan shows this contract has one link and Im going to connect my wallet to etherscan over here go to the flip function give it the entry fees which is 0.001 eth and input at choice so the way enums work if youre not familiar uh the way enums work in solidity is since we defined two values heads and tails heads is equal to zero and Hills is equal to one so it just goes in order so here in Choice its asking me to input a number Im going to predict heads and click right this will pop up and metamask to do a transaction and confirm all right so were gonna wait for this transaction to be mined by the network and well be back once its done mining awesome so the transaction has now been included on the blockchain I realized I said mining before its not actually mining Gurley is no longer a proof of work network but anyway so within this transaction youll see that our contract actually paid the vrf wrapper 0.44 link this was for the randomness request and if you look at the logs over here well see that our coin flip request event was emitted and this is the request ID that we got back so Im just going to copy this request ID and head over to read contract and try to fetch the status for this and it will give me back this Tuple that has a bunch of information this is in order of how we defined things in the struct so this is the fees paid this is the random word right now its zero and this is the player address which is my address this is the did win Boolean so its false I havent won yet and then this is fulfilled so the request hasnt been fulfilled yet so its false and finally this is my choice so zero means heads since we set request confirmations to three its going to take at least three blocks before chain link gets back to us with the response we will see the contract balance right now is 0.002 so 001 from when we deployed it I know one that I paid when I called the flip function so were going to wait a little bit and we should have um after like a minute or so chain link should send us back a response and we can look at it in the internal transactions tab over here or you can just look at the status of the request ID and check if fulfilled becomes true so right now oh there we go so fulfill this true now uh we see that this is the random number huge random number we got back from chain link it is an even number it ends with a zero and I chose heads so I didnt actually end up winning so the money is now with the contract I failed my prediction was wrong and we can verify that going to the events tab and on the events tab youll see the coin flip result was emitted which gives gives us back a request ID which you can look at in number form with a huge huge number as the same number as the request and then it gives the Boolean dead win which again in number four and zero is false and one is true so we didnt end up winning unfortunately but at least we know it was fair and it wasnt rigged so this is how you create a lottery game using chain link vrf V2 um thank you for more such videos stay subscribed and check out learn web3 well see you in the next one Chainlink VRF is a provably fair and verifiable random number generator. In this video, we use VRF V2 to build a CoinFlip Lottery Game on the Ethereum blockchain.web3 ethereum hardhat solidity blockchain chainlink Links Chainlink VRF: Supported Networks Configuration: Chainlink Faucet: Resources LearnWeb3: Discord: Twitter: Attribution Thumbnail CoinFlip Icon by Freepik ️ My Setup Terminal: zsh with ohmyzsh Theme: Solidity Visual Developer Dark Formatter: Prettier ethereum,web3,solidity,