chainlink town crierFunding Contracts and Accessing Chainlink Oracles freeCodeCamp — Lesson 3

Cardano ADA Price Prediction , 2024, 2025 - TradingBeasts The Cardano price is forecasted to reach $NA by the beginning of September . The expected maximum price is $NA, minimum price $NA. The Cardano price Does Cardano Have a Future or Will it Die? – Decentralization is a major point of crypto. Instead of 1 person controlling everything, the network is controlled by many people and this helps the network become more secure. When the Shelley update happens on Cardano there will be thousands of staking pools and this will decentralize the network. chainlink town crier Funding Contracts and Accessing Chainlink Oracles freeCodeCamp — Lesson 3
chainlink town crier What is the lowest Dogecoin has ever... Funding Contracts and Accessing Chainlink Oracles freeCodeCamp — Lesson 3
all right hello and welcome to lesson three the fund me lesson this is one of the most important lessons in the entire course and if youre successful here youll have the majority of the tools you need to be a successful smart contract developer now just because you have all the tools though doesnt necessarily mean that you know how to use them all so be sure to watch the subsequent lessons as well to get even better but in this video were going to learn about sending money and working with ethereum and working with the ethereum tokens in our smart contract application additionally this is going to be the first lesson that will work with a chain link oracle to empower our smart contract to be a hybrid smart contract this way our smart contract actually knows things about the real world empowering it to have even more features well also learn how to import packages from npm import other peoples code into our code base so we dont always have to start from scratch well learn about the chain link data feeds and how these data feeds are one of the most important pieces in d5 and how we can use it to make our applications some of the most important applications in d5 well learn a lot more low-level solidity pieces including safe math which were actually not going to use because in version 0.8 of solidity and on its built-in so with that best of luck and looking forward to seeing you on the other side of this lesson the github repository associated with this course also has all the code for this lesson so lets jump into it so were back in remix now and were going to go to contracts and same as before were going to create a new file were going to call this fundme.sol now same as last time were actually going to add this spdx license identifier mit right at the top and then were going to choose our solidity version so were going to go pragma solidity and for this were just going to do greater than equals to 0.6.6 and less than 0.9.0 and great this should look pretty familiar now were going to do contract fund me and were going to start working so what again do we want this contract to do we want this contract to be able to accept some type of payment so lets create a new function that can accept payment well call it fund so well do function fund public and well add a new keyword in here called payable when we define a function as payable were saying hey this function can be used to pay for things when you call a function every single function call has an associated value with it whenever you make a transaction you can always append a value this value is how much whey or gway or fini or ether youre going to send with your function call or your transaction as we mentioned before wei gway and ether are just different ways to talk about how much ether youre going to send so if we look at a way to ethereum converter one each is this much way one way is the smallest denomination of ether you cant break up ethereum into anything smaller than one way this is why when youre talking about how much something costs everything always defaults to whey or the smallest unit of measure in ethereum so again for us to test were going to stick with the javascript vm for now if we hit deploy we get a new contract and this button is now red its red because it is a payable function so now if i hit this fun button i can add a value associated with it so what do we want to do with this funding what do we want to do when people send us something well lets keep track of who sent us some funding so what we can do is we can create a new mapping between addresses and value so lets do a mapping of address to uin256 which will represent the value well make this a public mapping and well call it address to amount funded now in this fun function lets keep track of all the people who sent us money or all the addresses that sent us some value to do this we can use some keywords that go along with every transaction so well say address to amount funded of message.sender equals or plus equals message.value message.sender and message.value are keywords in every contract call and every transaction message.sender is the sender of the function call and message.value is how much they sent so whenever we call fund now somebody can send some value because its payable and were going to save everything in this address to amount funded mapping so if we deploy this now in our javascript vm we now have again a new view function called address to amount funded and we can even hit the drop down to see the full name now if i hit fund nothings going to happen right because my address is going to be sending zero in order for me to send something i have to add some value along with my transaction so lets send for example one gray which is going to be equal to one one two three four five six seven eight nine this much way so before i hit fund here if i copy this fake account which is up here and i put it in this address to amount funded its going to return 0. but now if i add 1 1 2 3 4 5 6 7 8 9 in here and we go ahead and hit fund now weve now just called this fund function with a value of one gray associated with it so if i call this address to amount funded now with the same address i can now see how much weve funded this smart contract and we can even add more gway well add well add 11gway for example well call fund and if we call this now we can see that even more has been added when we send our funds to a contract this actually means that this contract wherever this is deployed now is the owner of this amount of ether so this is fantastic we now have a way to fund our smart contracts now heres the thing in this smart contract in this funding that were doing we want to create a minimum value for people to be able to fund our endeavors which whatever they may be we want to set some minimum value here and ether is great but for whatever reason we want to work in usd or maybe we want to work in some other token so how are we going to get the conversion rate from that currency to a currency that we can use in this smart contract well the first thing that were going to need to do to set this value is were going to need to know what the eth to usd conversion rate is because if i want to accept ethereum as the token but i want it in its usd currency well then im going to need to know what that conversion rate is so how are we going to get this data into our smart contract where are we going to get this data from now remember how we talked about blockchains being deterministic systems and and oracles being the bridge between blockchains and the real world well this is exactly where oracles come in when were talking about these systems you know these blockchains they cant connect to real-world events they cant connect to external systems they cant do external computation theyre intentionally these deterministic systems these walled gardens so in order for us to make this connection we need a blockchain oracle we need some type of network here now just to get a little bit more technical for you if we look at a blockchain a blockchain can easily say one plus one equals two and every other node can easily verify this however a blockchain cant easily say okay lets all grab the same random number because each node is going to get a different random number they also cant say hey lets make an api call because if one node calls the api at a different time another node calls it or specifically an http get there could potentially get very very different results and if another node tries to replay these transactions by calling these apis again maybe 10 years in the future theres a good chance that that api is going to be depreciated and they could be hacked they could be malicious et cetera et cetera the other reason that blockchains intentionally cant make api calls is because then they would be making assumptions about the real world and layer ones typically dont want to have an opinion on any political or geopolitical issue whereas an oracle network on the other hand can make those assumptions the other main thing we need to talk about here is centralized oracles being main points of failures if you or i say hey im just going to be the oracle im going to be the one to put this data on chain we now have this massive centralized point of failure weve done all this work to make our decentralized computation decentralized and on chain but we ruin all the decentrality by having a single point of failure remember one of the whole purposes of blockchain is so that not a single entity can flip a switch and restrict our freedom to interact with a centralized oracle a single entity can flip a switch and restrict our freedom to interact with each other we also need to get data from many different decentralized sources or do any type of computation in a decentralized manner this is where chain link really shines chain link is a modular decentralized oracle infrastructure and oracle network that allows us to get data and do external computation in a highly civil resistant decentralized manner it can be as customizable as you want as you can run with one node or many nodes or do as many nodes as you like now currently one of the most popular features of chain link is their data feeds or their price feeds we can even go check them out over at data dot chain dot link we can see a number of different price feeds and the networks that are providing the prices for these specific pricing parts we can see here by looking at the ui there is a whole number of decentralized different oracles returning data for different price feeds this one for example is fusd and its also exactly the price fee that were looking for having a decentralized network bring this data on chain and have it as a reference point of definitive truth allows users to all collaborate and use this common good and it will be cheaper more secure more efficient than anybody even running their own centralized oracle so these price feeds are incredibly powerful additionally theyre being used by some of the top protocols in the defy system right now like synthetics which at the time of recording is securing around 2 billion sushi swap for leveraging trades set protocol commodity money ave for understanding the price of an underlying collateral now this is an example of an out of the box decentralized solution thats already been packaged in a decentralized manner for you to consume and for you to use this makes going to production a thousand times easier than building everything yourself however if you want to make api calls and build your own decentralized network you absolutely can with the chainlink api calls were not going to go into that here because using the chainlink price feeds chainlifevrf keeper network all these other pre-box decentralized services are going to make going live and going mainnet a lot easier you can always make a chain link http get call as well were not going to go over this though because putting this into production is a little bit trickier and working with chainlink vrf if you ever want to try them out by themselves you can always head over to and head over to get the latest price feed theres usually a remix button actually that we can click and it will kick us out to a remix edition with all the code already ready to go for us if we just hit this just right here this will include all of our code which well go into in a second but lets go ahead and compile it were going to deploy it to a real network here this one looks like its actually for coven so were going to go ahead and switch to coven looks like i dont have any covent ethereum so were going to grab a coven faucet we can usually find different faucets in the chain link documentation lets look up coven here there is a coven faucet here it looks like in order for us to get some covenant ethereum here we have to log in with github then we can add our address in here and get the ethereum in the interest of time im going to skip ahead for me doing that great it looks like ive got some cove that now being able to switch between test nets is going to make you a lot more effective as an engineer as well because youre going to be able to understand how each network actually works so now weve compiled this lets deploy this metamask is going to pop up and lets go ahead and click to get the latest price and we can see that this function does indeed return the latest price of ethereum now you might be asking why does this number look so big well remember how we talked about whey and gray and ether well the reason that those exist is because decimals dont work in solidity so we actually have to return a value thats multiplied by 10 to some number so this value is actually 2 614 times 10 raised to the eighth now the next question you might ask is well why did we work with this on a test net why cant we do this on a local network and the answer to this is because there is a network of nodes looking at this test net and delivering data onto this test stand when you spin up a local network or do a simulated vm there are no nodes actually doing that well learn later how to actually mock these interactions and mock a chain link node returning data onto our blockchain but for now lets head back over to the contract that were working on so we can learn how to implement this in any contract that we ever want to another contract called in this case called price feed has a function called latest round data which returns a lot of data it returns a round id which defines how many times this price feed has been updated it returns a price which is the actual conversion rate between the two assets it returns a started at which defines when this was last updated it returns a time stamp and it returns an answer in round dont worry about answered in round for now if you want to dive a little bit deeper into what these rounds mean and what answered in round means you can definitely check out the chain link documentation and some of the faqs to learn more now how do we implement this data feed into our fundme application well the first thing were actually going to need to do is were going to need to import the chain link code so were going to do import at chain link slash contracts slash source slash v0.6 interfaces slash aggregator v3 interface dot soul now lets talk about what this is actually doing oops looks like i spelt aggregator v3 interface wrong all right great now its actually compiling so lets talk about what imports actually do as we know an import will take whatever code youre importing and stick it at the top of your project so when we import from at chainlink contracts were actually importing from the at chainlink contracts npm package we can look up at chain link slash contracts in npm and we can see and read more about this repository this links us back to the github which will tell us a little bit more about whats really going on if we follow that import path that we got from the documentation will end up on this file in front of me now we have whats called an interface you can see these contracts dont start with the contract keyword but they start with the interface keyword they have the exact same pragma solidity at the top but the main difference is that you can see that their functions arent completed they just have the function name and its return type now just to be a little bit more explicit here im actually going to go ahead and delete this import statement on the top and replace it with that interface code from github just to show you exactly whats going on however if youve already typed that at import syntax feel free to leave it in there and just remember that its going to be the exact same as me copy pasting the interface code in in our code here solidity doesnt natively understand how to interact with another contract we have to tell solidity what functions can be called on another contract this is where interfaces are actually going to come in similar to structs what we can do with interfaces to find a new type so if we copy all this code from this section and place it at the top of our code here above where were declaring a contract we can actually then interact with contracts that have these functions if we go ahead and even compile this we can see this does indeed compile correctly remember how we said before we talked a little bit about abis well interfaces actually compile down to whats called the abi or the application binary interface the application binary interface tells solidity what functions can be called on another contract we need solidity to know what functions it can use and what functions it can call other contracts with and if that was a little bit confusing just know anytime youre going to interact with another contract in solidity or smart contract programming in general youre going to need that contracts abi well go into what these apis look like a little bit later anyways to simplify it interface compiles down to an api we always need an abi to interact with the contract so how do we actually work with this contract here to interact with an interface contract its going to work the exact same way is interacting with a struct or a variable lets define a new function called version and were going to call this version function on this other contract so well start out doing function get version public remember it needs to be a view since were just going to be reading this state and even in the interface it even defines it as a view returns so well even grab this whole bit right here view returns unit 256. now the exact same way we define variables and structs we define working with other contracts and interfaces so the first thing is we name the type which in this case is aggregator v3 interface then wed name the visibility but since again were inside of this contract were going to skip it then lets give it a name well call it price feed since this aggregator v3 interface is going to be giving us a price fee then we can do equals and this is where were going to initialize the contract so how do we actually choose where to interact with this contract well we just type aggregator v3 interface and then we put in here the address of where this contract is located in order to find where this fusd price feed contract is located on the rink b chain we can look at the ethereum price feeds chain link documentation it has a ton of different price feeds and even more not price related data lets scroll down to rink b because again on each different chain the contract address that has all this price feed information is going to be different lets scroll down and find fusd which is right here and well copy it and well paste it into here now what is this line saying its saying that we have a contract that has these functions defined in the interface located at this address if thats true then we should be able to call pricefeed.version and we should be able to return it whoops looks like we forgot to add those here and we need a semicolon here i hit control s or command s compiled looks like were compiling successfully and we do need to deploy this on a test net remember this address here is located on an actual test tent its located on an actual network its not going to be located on our simulated chain here so we do need to deploy this to injected web 3. we do need to deploy our contract to rink b because the rink b chain has this address well learn later on how we actually can work with a simulated chain and work with these price feeds but thats much later in this course so lets go ahead and save well deploy make sure were on injected web 3. now we can go ahead and hit deploy metamask is going to pop up per usual confirm were going to get a transaction link to etherscan showing us our contract and once it actually is confirmed we can see we have our contract right here now we have our familiar functions with one additional function we have our fund button which is red because its payable we have our address to amount funded mapping which is blue because its a view and we also have this get version button thats also blue if we go ahead and click it we can see that the version of our aggregator v3 interface is version 3. this is the third version of the aggregator interfaces hence the name aggregator v3 interface so we just made a contract call to another contract from our contract using an interface this is why interfaces are so powerful because theyre a minimalistic view into another contract so this is great we have a get version function but this still isnt the function that we want we want to call the getprice function which if we look at our interface we can see theres a latest round data function that returns an answer this is the function that were going to want to call on this contract so lets go ahead and make a function that calls that instead so were going to do function get price public view returns you went 256. uh-oh this latest round data function though returns five variables so how do we actually work with that well lets find out to work with this contract were gonna do the exact same thing were gonna do aggregator v3 interface because this is the type of the contract price feed equals aggregator v3 interface well do this same address in here because this is the fusd address then well do price feed dot latest round data now since this is going to return five different values we can actually have our contract also return these five different values we can copy paste like this and literally do this these five values equal price feed that latest round data and you can see that even compiles correctly lets adjust the formatting a little bit here so it looks a little bit nicer a tuple is a list of objects of potentially different types this is the syntax for getting a tuple we can define several variables inside one of these tuples although our compiler is going to give us some warnings its saying unused local variable because were not actually using these for anything well come back to this now we can go ahead and do return and we can pick one of these variables that we want to return answer is going to be the price so were going to do return answer but uh-oh were going to run into an error return type argument int 256 is not implicitly convertible to expected type answer is an int256 and we want to return a uint256 so how do we rectify this we can fix this by using whats called type casting if we just return answer were going to be returning the wrong type however integers and solidity are really easy to cast into each other so we can just do uint 256 and wrap it around this answer and then compile and save that instead as you can see now our compiler is happy because weve changed this answer into a unit 256. awesome so now this get price should return the latest price of ethereum in terms of usd lets go ahead and deploy this new contract with this new function so same thing were going to come to our deploy section hit the deploy button up remember we got to go to thefundme.sol lets deploy it confirm with metamask here and lets scroll down to our newly deployed contract as you can see we have our getversion function which still works exactly the same but we have a new function too called getprice and this should return a uint256 answer lets go ahead and click it amazing weve actually returned an answer now again if youre a little confused on why this number looks so big you have to remember that this actually has eight decimals we could call this decimals function on the contract to learn that one two three four five six seven eight and we know that the current price of ethereum in terms of usd is two thousand four hundred and eighty-two awesome so now that we have the price we can actually get the conversion rate but lets clean up this function a little bit before we go on up there as you can see one thing that the compiler is complaining about is we have a lot of unused local variables but latest round data returns five different variables so how do we actually return the five variables but make our compiler happy with us well we can actually just return blanks for each one of these sections with commas in between each other to say hey there is a variable here but were not going to use it this will also make our code look a lot cleaner because now this functions a lot smaller we say somethings here were ignoring it in 256 answer were going to use some things here ignore it something here ignore it and ignore this too and we can even test this out by compiling it deploying it checking on rank b scrolling down hitting this and hitting get price and you can see indeed its the exact same as before awesome so now were all done cleaning things up right not quite yet see the other thing thats really annoying here we have this massive chunk of code at the top that is probably a little redundant theres a good chance that a lot of our contracts are going to want to use this aggregator v3 interface so lets just go ahead and add that at chain link contract syntax back in because its going to look a lot cleaner here and do at chain link slash contracts if you ever get a little bit confused with what you should be importing to work with their contracts we can see right in the documentation at the top this at syntax is what this is going to use now you can also go ahead and browse that npm package of at chainlink contracts see what other applications are in there and what other files are in there or you can just peruse around the github now the third way we can actually do imports is we can import from contracts that are in the same file system as our contracts well awesome our contract is starting to look more and more put together now one other thing that i usually like to do with these is i usually like to put everything into the way way standard so as we saw this get price had eight decimal places however the smallest unit of measure aka whey if we look at it has 18 one two three four five six seven eight nine ten one two three four five six seven eight so typically in these i like to try to make everything have 18 decimals as well you dont have to do this and itll save some gas if you dont but i usually like to multiply everything so that everything has 18 decimal places so since i know this has eight i can just do one two three four five six seven eight nine ten and now this will return the price with 18 decimal places instead of 10. now we have the price of ethereum in u.s dollar which is fantastic so we could set the price of our funding function to anything that we want here for example lets say fifty dollars we could convert whatever value that they send us to its us dollar equivalent and see if its greater than or less than fifty dollars all we have to do is make a new function that converts that value that they send to its us dollar equivalent so we could do function get conver generate and it will take a u and 256 f amount lets get this out of the way for the rest of this itll be a public view function since again were not actually going to have it make any state change well do returns you went 256 and then in this function we can do uint256 fprice equals getprice and we can call this getprice function up here now we have the price in here what we want to do is we want to convert whatever value that they send as f amount lets say they send one way or again thats going to be this much way what how do we convert this to fusd well we can now do unit 256 s amount in usd equals this f price times the f amount that they sent this is actually going to result in a much bigger number than were looking for and then of course were going to return it lets test this out and see why we have to do one more thing here so lets again fund me well deploy rank b and well scroll down and we have this new function called get conversion rate lets grab this one way and put it in here whoa this seems like its a really big number were saying that one gray is equal to one two three four five six seven eight one two three four five six seven eight nine ten this many dollars now i dont know about you but i dont think the price of union one ethereum is that many dollars maybe in the distant future but definitely not right now the reason that its off is we have to then actually divide by this number the reason that we have to do this is because both f price and f amount have an additional 10 raised to the 18th tacked on to them so now we have to divide it out in order to get the right number so were going to compile compile deploy confirm we can scroll down and now lets try this one way well get the conversion right here and we can see we get a number that makes a little bit more sense now remember this has 18 decimals as well so the real number is 1 2 3 4 5 6 7 one two three four five six seven eight nine ten and we know that this number is actually accurate because we can go ahead and pull up a calculator pop that into here and we know that this is one way in us dollar if we get the conversion rate were saying that this many way equals one eth so we can check it back by multiplying this number by that and we see that we do actually get the price of one ethereum in us dollar so our math here checks out awesome now since were on the topic of math i do want to talk briefly about some of the pitfalls of solidity especially when it comes to math prior to solidity 0.8 if you added to the maximum size a uint number could be it would actually wrap around to the lowest number that it would be and in fact you can even demo this with a contract here now you dont have to follow along with this contract but just watch to see the example were going to call this overflow dot soul now in here were going to add all kind of the normal stuff contract overflow and were going to add a function called overflow well make a public view and well have it return a uint 8. ill show you why in just a minute a uint256 is a really really big number and its hard to kind of imagine going over the maximum cap of a u and 256 but a uint eight is a lot smaller with the maximum number actually being 255. so if we create a uint eight and we call it big equals 255 and then we just do return big what do we think were going to get here for this we can go ahead and use javascript vm because were not interacting with any other contracts lets deploy this and well see in our contract if we call overflow now were just going to get 255. however what happens if we add 1 to this number or try to add 1 to this number if we do it just like this solidity actually knows that theres an issue here and says hey try not to do this but if we typecast this as a uint 8 solidity gets a little bit more confused and goes ahead and lets us do this now what do we think big is going to be it should be 256 right but big is the uint 8 and this is the maximum size that it could be so what happens when we deploy this we look down we actually get zero what happens if we do 100 and we deploy that we actually get 99 and this is because integers can actually wrap around once you reach their maximum cap they basically reset this is something we need to watch out for when working with solidity if were doing multiplication on really big numbers we can accidentally pass this cap luckily as a version 0.8 of solidity it actually checks for overflow and it defaults to check for overflow to increase readability of code even if that comes a slight increase of gas costs you can use this unchecked if you want to have it keep that wrapping functionality so just be aware if youre using a lower version than 0.8 youre going to have to do something to make up for this and we could write a whole bunch of code here basically to check all of our math or we just import something called safe math from another package similar to how we imported chain link we can go ahead and import a package called safe math from a tool called open zeppelin now open zeppelin is an open source tool that allows us to use a lot of already pre-built contracts we can go ahead to the documentation and go to their utilities and see safe math and they even have a little sticker here saying safe math is no longer needed started with solidity 0.8 safe math is a tool and a way for us to avoid some of these problems with doing math and solidity now im not going to spend too much time on the contracts that actually fix this but we can actually import right from the chain link directory as well a solidity file called safe math chain link and what we can do is right after our contract we can do using safe math chain link for uint256 and what this will do is itll use safe math chain link for all of our you and 256 and safe math chain link doesnt allow for that overflow to occur libraries are really similar to contracts except that theyre isolated code that can be run in a reusable context in this case were attaching the safe math chain link library to uint256 so that these overflows are automatically checked for just keep in mind if youre using anything less than 0.8 youre going to want to use some type of safe math just to check for your overflows now this is for those of you who are familiar with safe math and integer overflows and underflows we are not going to be calling the functions that safe math provides us like div add mole you know all those functions simply because in 0.8 moving forward we no longer have to use those and we can just use our regular operators like plus and minus so this is great our contract is coming along really well we now have a way to get the conversion rate of whatever f is sent and turn it into us dollar now we can set a threshold in terms of u.s dollar but how do we guarantee that whatever amount that the users send when they call fund is going to be at least 50 well first we might want to set a minimum value so we can do u and 256 minimum usd equals lets say 50 dollars and again since were using everything in way terms we want to then multiply this by 10 raised to the 18th and just want to take a pause for a second because this line is actually wrong this should be raised to the 18th so this line should really look like this where it has the double star so apologies the rest of this has that single star but it should be the double star here if you do have the single star though the rest of the contract will still work fine so this will be the minimum value itll be 50 times 10 raised to the 18th so that everything has 18 decimals now that we have a minimum amount how do we actually make sure that this minimum amount is met in the value that they send us well if youre familiar with if statements we could do something like if message.value is less than minimum usd then revert or we could do something a lot easier and better practice and much cleaner we could do whats called a require statement when a function call reaches a require statement itll check the truthiness of whatever require youve asked so in our case the converted rate of message.value needs to be greater than or equal to our minimum usd this line says that if the conversion rate of message on value to usd if they didnt send us enough ether then we are going to stop executing were going to kick it out were going to say hey this doesnt count and were going to do whats called a revert were going to revert the transaction this means that the user is going to get their money back as well as any unspent gas and this is highly recommended we can also then additionally add a revert error message something like you need to spend more eth so now lets try this out as we saw one gray is going to be way less than 50 so if we send one way along with this fun contract call it should kick out and say you need to spend more eth so lets actually try this lets go to the deploy tab well get rid of our overflow we use injected web3 because again we are working with the chain link aggregated contracts that are on chain were going to move to fund me and were going to hit deploy metamaths going to pop up and were going to hit confirm now if i try to hit fund lets see what happens were getting a gas estimation failed it says gas estimation error failed with the following message execution reverted you need to spend more eth so the contract isnt even letting us make the transaction we can go ahead and try to send the transaction but heres whats going to happen on etherscan once this goes through you can see that once this transaction finished we got this status fail with error you need to spend more eth we dont want to force these transactions to go through if we look at our metamask we can even see this failed bit here so whenever you see these gas estimation failed errors usually that means something reverted or you didnt do something that was required however if we go to value here and we spend a lot more lets say 0.1 ether which if we take out our calculator 2500 times 0.1 is going to be 250 this should easily be well and beyond past our fifty dollar threshold so lets add point one ether remember we got point one by adding it in the converter and grabbing the way again the way is the smallest denomination now if we change this to way and hit fund this should go through we going hit from now youll see metamask pops up because metamask goes oh yeah this transaction isnt going to revert and thats what we want so we can go ahead and hit confirm and now well finally have sent some funding to our contract now that this is confirmed we go ahead and grab our address here pop it into our address to amount and we can see that indeed our funding has gone through now we can be part of this crowdsourcing application with our minimum value which is fantastic awesome great job awesome so now we can fund this contract with a certain minimum usd value in this case its going to be 50 now youll notice though that right now we dont do anything with this money so were going to fund this contract however thats it and we dont have a function in here to actually withdraw the money so theres no way that even though we just sent this contract some money theres no way for us to get it back so how do we fix this well we can add a withdraw function in here so lets go ahead and add that function withdraw and this is also going to be a payable function because were going to be transferring eth well make this public and we can do message dot sender dot transfer transfer is a function that we can call on any address to send eth from one address to another this transfer function sends some amount of ethereum to whoever its being called on in this case were transferring ethereum to message.sender so all we need to do now is define how much we want to send well were going to send all the money thats been funded so to get all the money thats been funded in this contract we can do address this dot balance now theres a couple of special things going on with this line first were saying address of this this is a key word in solidity whenever you refer to this youre talking about the contract that youre currently in and when we add address of this were saying we want the address of the contract that were currently in whenever you call an address and then the balance attribute you can see the balance in ether of a contract so with this line were saying whoever called the withdraw function because whoever calls the function is going to be the message.sender transfer them all of our money so lets go ahead and try this lets deploy fund me and now lets fund this with a lot of ether so that we can see it well fund it with one whole ether so that we can see it go into the contract and get pulled out of the contract well hit the fund button and youll see were sending one whole ether into this contract now if we look at our balance its gone down from 17 to 16 or if youre still at 18 it went down from 18. so lets try to get it back if we call this withdraw function now confirm once this transaction goes through we should get all of our ether back lets look at our metamask and boom indeed we have got all of our eth back however looking at this contract we can see that hmm well maybe we dont want anybody to be able to withdraw all the funds in this contract that seems like it might be a really bad idea maybe we only want the funding admin to be able to withdraw funds so how do we set this up in a way that only the contract owner can actually withdraw funds well we learned before that the require function can actually stop contracts from executing unless some certain parameters are met we can do the same thing here with require message.sender equals the owner but we dont have an owner to this contract yet so how do we get an owner to this contract the instant that we deploy it well we could have a function called create owner but what happens if somebody calls this function right after we deploy it well then we wouldnt be the owner anymore so we actually need a function to get called the instant we deploy this smart contract and thats actually exactly what the constructor does so typically at the top of your smart contracts youll see a constructor and this is a function that gets called the instant your contract gets deployed you dont even need to do add function here we can literally just call it constructor because its what constructs the smart contract so well make constructor public and whatever we add in here will be immediately executed whenever we deploy this contract so one thing that we could do is we could have an owner be set the instant we deploy the smart contract so in the top we could add address owner and in our constructor we could say owner equals message.sender because the sender of this message is going to be us its going to be whoever deploys this smart contract we can even test this out in the javascript vm to be a little bit quicker because were not actually going to be calling the fund or the getprice function for now oops lets also make this public so that we can interact and see this owner variable so now if we go to fundme we deploy this in the javascript vm we should be able to see who the owner of this contract is and it should be our address because this constructor function should have been immediately called the instant that we deployed the smart contract awesome we can see the owner of this smart contract is indeed our wallet because remember were working with the javascript vm our wallet is these fake wallets that they kind of give us we can even try this with an injected web 3 with deploying this and the owner should be this ox 757 etc address lets go ahead and look at fundme see the owner and we do indeed see the owner is us okay great now we have an owner we can go down to our withdraw function and use that same require so we can call acquire message.sender equals equals owner equals equals is the way that solidity understands true false were saying that message.sender has to equal owner now lets go ahead and try this and well try with the javascript vm again for speed reasons lets deploy this funding and if we go down here we try to call the withdraw function and it looks like it is successful because currently this is the address that deployed the contract and its also the address that is calling withdraw however if we switch to a different account in call withdraw youll see that remix actually freaks out down here it says uh-oh something wrong happened and this is essentially the require statement kicking out if you want to try it with injected web 3 as well we can absolutely do that too and remember the way to switch accounts in metamask is to either create a count right here or just switch like this and then well connect with account two so if i try to withdraw from this second account that didnt call the contract and i hit withdraw now its going to give us gas estimation failed because the required statement is going to kick out but again if we switch back to account 1 and we call withdraw metamask is going to pop up and its going to allow us to withdraw now obviously theres nothing in this contract right now so were going to withdraw nothing but we can still call it its going to do message.transfer 0. so this is great we can now require this withdraw function is only callable by the owner now what if we have a ton of contracts that want to use something like this they require the message.sender to be some owner or maybe its more complicated than this is there an easier way to wrap our functions in some require or some other executable well this is where modifiers come in we can use a modifier to write in the definition of our function add some parameter that allows it to only be called by our admin contract modifiers are used to change the behavior of functions in a declarative way lets create our first modifier well call it modifier which is a keyword onlyowner and well add this require statement in here require message.sender equals owner then after this we just add an underscore in a semicolon what a modifier is going to do is its going to say hey before you run this function do this require statement first and then wherever your underscore is in the modifier run the rest of the code so we could also do a modifier where the underscore is up here and then this is afterwards but but we want to run the require first so now what we can do is we can make this function withdraw payable only owner public and whats going to happen is before we do this transfer were actually going to check this modifier were actually going to run this require message.sender equals owner and then again where this underscore is thats where well add the rest of the function so again for speed reasons and since were not actually going to be interacting with the chain link data contract we can go to javascript vm switch to funding deploy and we can call withdraw obviously we can call withdraw from our account but if we switch accounts and try to call withdraw were going to get an error which is perfect because that means our modifier is working correctly awesome now we have a fantastically succinct fund me contract here the only thing that were really missing is that when we withdraw from this contract were actually not updating our balances of people who funded this so even after we withdraw this is always going to be the same so we need to go through all the funders in this mapping and reset their balances to zero but how do we actually do that we cant actually loop through all the keys in a mapping when a mapping is initialized every single key is essentially initialized now we obviously cant go through every single possible key on the planet however what we can do is create another data structure an array something were already familiar with so lets go ahead and create a new funders array that way we can loop through them and reset everyones balance to zero well do an address array because its going to be an array of all the funders addresses well make it public and well call it funders now when somebody funds a contract what were going to do is were going to do funders now whenever a funder funds this contract we can go ahead and push them onto our funders array so we can do funders dot push message dot sender now if somebody funds multiple times the funders array is going to be a little bit redundant but were going to ignore that for now now that we have an array of funders when we withdraw everything were going to want to reset this to zero when we withdraw everything we want to reset everyones balance in that mapping to zero so were going to do whats called a for loop a for loop is a way to loop through a range of numbers to do something so were going to say for unit 256 funder index equals zero because we want to start with the zeroth index were going to give it a max size to go to were going to say the funder index has to be less than length dot length is how we get the length of our array and then were going to say funders index plus plus this means that we have an index variable called funder index and its going to start from zero this loop is going to finish whenever a funder index is greater than the length of the funders every time we finish a loop were going to add one to the funder index thats what that funder index plus plus does it adds one to the funder index and every time whatever code is in this for loop executes were going to restart at the top and all were going to do in here is were going to grab the address of the funder from our funders array funders so the funder at the index in our funders array were going to use this as the key in our mapping so were going to take address to amount funded of funder and were going to set it equal to zero so now our mapping is going to be all updated to people having xero funded in there we do have to do one more thing as well we have to reset our funder array as well now theres a couple ways to do this but a really easy way is just to set funders equal to a new array so we could do funders equals a new blank address array so all right it looks like weve got everything in here we need right away when we deploy this we are set as the owner we can allow anybody to fund whatever public good that were doing and they have to fund it with the minimum usd value that we actually set whenever they fund well keep track of how much theyre funding and whos been funding us we can get the price of the ethereum that they send in the terms of usd and we can convert it to check to see if theyre sending us the right amount we have our only owner modifier so that were the only ones who can withdraw from the contract and when we do withdraw everything from the contract we reset all the funders who have currently participated in our crowdsourcing application awesome lets see if everything works end to end so were going to go to fundme were going to deploy it were going to confirm from metamask and remember if youre ever confused about whats going on or or something weird is happening in your transactions or your deployments you can always go into etherscan and read more about your transaction and whats going on now that our transaction has been deployed lets go ahead and just take inventory as whats going on we have our owner which is our address right here we have the aggregator v3 interface version which is version 3 which we can kind of ignore we have the price of ethereum in terms of usd with 18 decimals instead of eight we have a function that allows us to get the conversion rate of any ethereum amount to its us dollar equivalent we have an array of funders which right now starts out as empty we have a mapping of addresses which also right now starts out as empty lets go ahead and try to fund this contract well use way just that were always on the same page and well fund it with 0.1 whey remember everything has 18 decimal places so if we want to do 0.1 we just do 17. so we can do 1 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 nine and thatll be 0.1 ethereum now we can go ahead and hit fund and were going to send 0.1 eth to this contract great so if we look at the zeroth index of funders we can see that indeed we have funded this contract lets even have our second account fund this contract so all we got to do is switch to this contract in metamask we can go ahead and put 0.1 eth back in here for value and hit fund now as you can see were deploying this from account 2. lets go ahead and hit confirm funder at index 0 is going to be our admin and the funder at index 1 is going to be our second account and if we go ahead and we add this funder in here we can see weve indeed sent point one ether with this account if we go back to our count one and put this in here we can see that that address also has point one ether fantastic so lets try to be malicious lets try to have account number two actually withdraw all the funds in here lets hit this withdraw function uh-oh the transaction has failed were relentlessly malicious we want to send this transaction regardless so even though im not the admin of this contract ive gone ahead and still tried to send its withdraw so what happens now we can see that remix is saying hey something went wrong and again if we look at ether scan we can see that there was a fail here since in our modifier we didnt give a reason here nothing shows up but we could have always put a reason in there and something would show up so all right lets go ahead back to the actual admin and now lets try to withdraw everything so if we hit withdraw now we can go ahead and confirm what should happen is everything in here should be back to zero and this array should be back to 0 as well and if we watch our address we can see it literally just went from 0.4 to 0.6 because it got 0.1 from the original funding that this account put in and the 0.1 that our second account put in so now if we look at funder zero we can see it actually errored because it is now a brand new array and there is nothing at index zero if we try to see how much this address now is funded its back down to zero awesome youve now learned how to deploy a relatively simple yet effective crowdsourcing application where users can fund and an admin can withdraw those funds to go spend them on things all right you did it lesson three in the books congratulations that is absolutely massive here youve just learned how to use one of the most powerful tools in all the smart contract world which is these chain-link data feeds as of right now which itll probably change depending on when you watch this video the chain link data feeds are securing something like 80 billion dollars in the define network an absolutely massive battle tested application here now were going to start moving into the python portion of this course and were going to introduce you web3.pi which is an incredibly powerful python package thats going to help us deploy our smart contracts test our smart contracts and interact with blockchain applications in a programmatic way making us incredibly powerful developers here so with that ill leave you to the next lesson good luck have fun and remember to take a breather to take it all in see you in the next lesson you Follow along with Chainlink Labs Patrick Collins for a step-by-step tutorial on how to send funds to a smart contract and use Chainlink oracles to securely access off-chain data and begin building market-ready contracts. Github link: Helpful resources: - Github repo for this episode: - Github repo for the whole course: - The full Solidity, Blockchain, and Smart Contract course: Explore the full suite of Chainlink decentralized oracle solutions, from Data Feeds and VRF to Automation formerly known as Chainlink Keepers: Chainlink is the industry standard for building, accessing, and selling oracle services needed to power hybrid smart contracts on any blockchain. Chainlink oracle networks provide smart contracts with a way to reliably connect to any external API and leverage secure off-chain computations for enabling feature-rich applications. Chainlink currently secures tens of billions of dollars across DeFi, insurance, gaming, and other major industries, and offers global enterprises and leading data providers a universal gateway to all blockchains. Learn more about Chainlink: Website: Docs: Twitter: Chainlink Remix smartcontracts freeCodeCampS01,