Ethereum Programming Tutorial - DeFi, Solidity, Truffle, Web3.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today i'm going to show you how to build a full blockchain application step by step a decentralized finance or defy app this is one of the hottest trends in blockchain right now i'm going to show you how to create your own defy app a decentralized bank where users can deposit cryptocurrency and earn a competitive interest rate on their funds that's much higher than their traditional bank account and i'll even show you how to extend their project where they can take out loans against the money just like all the other hot defy apps out there right now i'll walk you through everything from start to finish setting up the app on your computer creating the smart contract the solidity programming language deploying your smart contracts to a blockchain and then also creating a website so that people can connect to the application and use it and don't worry you don't have to be an expert to get started today you don't have to know anything about blockchain you really don't even have anything about coding i can show you everything as we go along in this tutorial so before we get into that you know if you're new around here hey i'm gregory and on this channel i turn you into a blockchain master and i put a lot of time and effort into this particular tutorial and the only thing that i ask in return is that you like this video and subscribe to this channel that really helps these videos out so that more people can learn about blockchain and if you like this video and you want to take the next step or hey maybe you just want to take a master shortcut entirely right now i could should become a blockchain master step by step from start to finish over at dap university.com forward slash bootcamp here's a quick preview of the application we're going to build together in this tutorial this is a blockchain based bank where you can deposit cryptocurrency into it and whenever you do you earn interest that's one of the cool things about blockchain technology is you can become your own bank with cryptocurrency and you can incentivize other people to use your application by giving them higher interest rates than they could in their own traditional bank accounts this is part of a larger trend in blockchain technology called decentralized finance or d5 for short which is basically taking traditional financial products and porting them over to the blockchain things like savings loans derivatives trading and in this video we're going to build a defi app on the blockchain that is this digital bank and you'll see how all this works step by step so let's first look at a diagram about how the application works let's look at how the application will work so we'll use our web browser and we'll connect to a website that we will create in html css and javascript and that's pretty typical if you're going to follow some other development tutorial maybe like a website coding tutorial you would build a website that is coded in html and css and javascript but a lot here's where it differs a lot of times those applications will talk to a back-end server where all the code and the data will live for the application but this is different instead of talking to a backend web server we're going to talk directly to a blockchain and this is a blockchain that we'll install on our computer and run locally it'll be a development blockchain and we'll create all the code for the block all the code for the bank inside of smart contracts so smart contracts are immutable pieces of code that are deployed to the blockchain they are the building blocks of blockchain based applications we're going to write them in solidity the coding language for writing ethereum smart contracts and ethereum is the blockchain that we'll use in this tutorial and one other big way this is different from web development is in order to talk to the blockchain we need a special browser extension that will be our cryptocurrency wallet because we must have this wallet installed into our browser in order to turn this web browser into a blockchain browser and then we'll use a special library to turn our website into a blockchain website in order to speak to the blockchain and interact with the bank that we'll create in this tutorial so if you're brand new around here let's clear up one last question which is what is a blockchain well it's a global computer but in order to understand exactly you know what it is and how it works let's answer the question why we need a blockchain in the first place so why would we just build a regular web application with a back-end web server and a database well in order to create a money we're actually going to create a cryptocurrency in this tutorial in order to create a cryptocurrency we don't want a single individual to have full control over that cryptocurrency we want it to be deployed to a decentralized network that's exactly what a blockchain does so you can see this diagram here these are all nodes that are on the blockchain that talk to one another each of these nodes is a computer that shares a copy of the code and the data on the blockchain so the code for the cryptocurrency itself and also the data on the blockchain how much cryptocurrency you know each person has it also facilitates the transfer of cryptocurrency because anytime cryptocurrency changes hands the nodes on the network must come to consensus about that transaction before adding it to the blockchain so all these transactions on the blockchain that make up account balances that uh you know are responsible for verifying cryptocurrency when it's transferred all these transactions are contained in bundles of records called blocks which are chained together to make up this public ledger hence blockchain all right i know that's a really quick explanation but i think it'll all become a lot clearer as we jump in and start coding so let's go ahead and do that but before we can do that we need to install some dependencies on our computer first the first dependency is nodejs this is going to give us a way to run javascript on our computer and it's also going to give us mpm so we can install all the packages for our project so you can see if you have node already installed by going to your terminal and typing node v i'm currently using version 10.19.0 for this particular tutorial and i highly recommend that you use the exact same one to follow along if you're an advanced developer already you understand how to use node versions you can use whatever version you want to as long as it works but if you're a total beginner i highly recommend using this exact version to guarantee that your code will work so you can download node directly from the node.js website or you can use a package manager like homebrew on a mac to do brew install node the next impedance you need is the truffle framework this is a suite of tools it's going to allow us to create smart contracts on our computer with the solidity programming language we'll be able to write tests for them deploy them to a blockchain and connect to our development blockchain ganache which we'll install here in a minute you can see if you have truffle already installed by going to your computer and typing truffle that version or sorry truffle version and if you do you'll see some information here i highly recommend using the same version of truffle as me which is version 5.1.39 so if you're not if you don't see anything there you can install truffle like this npm install dash dash g or global truffle at version 5.1.39 the next dependency is the ganache personal blockchain so this is a development blockchain that we can download and install on our computer so go ahead and head over to the ganache website download this and open it and whenever you do you'll have a local blockchain running so you'll see you have 10 accounts here they're all credited with 100 fake ether don't get excited this ether isn't actually worth anything in the real world but this will give us some money to play with uh while we're building our bank and it'll give us some accounts that we can use to connect to the network finally we need to install the meta mask extension for google chrome so what is this well most web browsers do not support a connection to the blockchain out of the box so we need to install a special browser extension to do that that's what metamask is so go to google chrome web store search for metamask install it i've already got it installed so you don't see an install button here but you'll see an install button here uh and whenever you finished you'll see a fox icon here up in the top right hand corner of your browser so just walk through the setup steps on metamask whenever that's set up and you'll have a wallet installed so that will also allow you to hold cryptocurrency so you can pay for transactions on the blockchain and also deposit money into the bank long story short is anytime you use the blockchain you need a blockchain wallet that's what metamask is it's a browser extension it lets you use blockchain-based applications and you can install it like this and so let's go ahead and uh start building out the project so i'm gonna go to github.com forward slash dappy diversity forward slash d bank all right i'll put a link to this description below and this is where we're gonna get all the starter code for the project itself so if you're brand new to coding this is just a website where all the code for the project lives uh you can download it like with git like i'm gonna show you my terminal here or you can just download the code right here if you do that highly recommend going to the branches here finding the starter kit branch and downloading the code that way because that's how we're going to get started okay so if you're going to use the zip way that's it if you're going to use the get way then copy this url here go to your terminal and type in git clone paste in the url here actually we're going to do dash dash branch starter kit all right and then actually let's do take off the tree part here okay so now we can enter into the newly created directory like this okay and there we go we're on the starter cube branch so if you download with a zip file uh you'll just open it in your terminal manually and you should see all the code here so now we can do ls-l to ensure that we are in uh our project and that the files look the same so it looks looks good to me okay i can also do al see the dot files and such so now let's um install all the packages with node so we're gonna use npm we'll say npm install and we'll wait for it to finish all right so now that's finished so let's go ahead and open up the project in our text editor i'm personally using sublime text you can use whatever text editor you like and i'm going to open my project like this so simple dot that's my shortcut that i have configured to open sublime text so we can take a look at what we have here we have a truffle project so truffle again is the framework for writing ethereum smart contracts we can also do a lot more like with truffle we can write the source code for the smart contracts in here go to sort of source contracts and we can see a few files here already so dbank.sol will be the smart contract where we actually create the bank we've got a token inside of here okay we also can write tests for the smart contracts which we have inside of here so this test file okay we have um a way to put the smart contracts in the blockchain and we also have a front-end website so you can see this source components here this is where the front-end application will live so let's take a look at everything that we're going to create so if you think about this in terms of other application development we have the backend all right so the back end is going to be uh blockchain so we're running a blockchain so whenever you start ganache which will go into that now make sure you have ganache running you should see your blockchain here running with uh you know 10 accounts and they're all pre-funded with some ether so i've been using my ganache already so i've got a little bit less you throw in this account that's okay so i have a back end this will be the blockchain but all the code for the backend is gonna be created with smart contracts okay so we're gonna write two different smart contracts in this tutorial one for a cryptocurrency so a token and then one for the actual bank itself so what this bank's gonna let us do is deposit cryptocurrency okay and then earn a brand new token with interest okay and it's going to use the blockchain to calculate that all intelligently so this will be the back end portion of the application so now this back end is going to talk to a front end all right so this front end is going to be here and this is going to be react.js so react is a javascript framework for creating user interfaces and we will have a web3.js that will turn our application into a blockchain application so it'll talk to the blockchain interact with our smart contracts and let you know users uh interact with the front end part okay so we're gonna build this in a few phases we're gonna start off with the back end part so we're gonna code the smart contracts first and then we'll move on to the front end so we're gonna do is uh create this token smart contract this bank contract and then we're gonna you know interact with those in the console run the tests and then create this front-end application to uh you know talk to this would be the last thing we do so that being said there's a lot to do here and the reason we started with the starter kit branch is a lot of this stuff is kind of already set up we're just gonna fill in the gaps okay because i'm trying to make this a quicker tutorial so that you can get this introduction faster all right so we're not going to code like every single tiny detail from scratch step by step like set up the project you know create this file just create this file all the files are created for us we're going to hit the important parts so you can see like how does solidity work how does a smart contract work how do you interact with the blockchain how you create this behavior to make a decentralized bank i want you to see the bigger picture important stuff which you'll get without getting bogged down by all the details of creating every single file etc etc etc okay so that's why if you open this project you'll see this you know you'll see uh we have some contracts in here already for the token okay and then also the bank as well all right all right so let's start off with the token contract because like i said there's two smart contracts in this tutorial the token and the bank itself so let's explain what this contract does and then we'll add some code to it to make it work okay so uh let's see here in this scenario how the bank will work is there will be two cryptocurrencies involved so ether this is the native cryptocurrency of the ethereum blockchain so when you uh see this on ganache this person has like a hundred eighth balance this is the native cryptocurrency on ethereum all right ether so what's gonna happen is people are gonna deposit ether into this bank okay and then over time they'll earn interest and that will be paid in a brand new uh token like this all right so this brand new token is a cryptocurrency that will create and it works very differently from ethereum or ether okay so like i said this is ether this is the native cryptocurrency ethereum blockchain it's just built into the protocol but what's cool about ethereum is you can create your own cryptocurrency without creating a brand new blockchain with smart contracts okay so that's exactly what i'm doing this tutorial we're going to create a smart contract that powers a brand new cryptocurrency this token right here okay and we're going to use something called an erc20 token which is just a description for how tokens should work on top of ethereum so you go to ethereum.org and look at the erc20 token standard this basically just says if you want to create a cryptocurrency with a smart contract it needs to have a certain set of behavior so you can see that it specifies which functions that the smart contract should have so it has to have a name a symbol has to have total supply you have to be able to transfer tokens with the transfer function uh you have to be able to you know approve look for events all this kind of stuff okay so the whole idea is that if you create a smart contract then it needs to be compatible with cryptocurrency exchanges it needs to be compatible with wallets it needs to be compatible with d5 applications and this standard uh specifies all that as long as you satisfy the standard then your token should work so that being said the erc20 standard uh if you're gonna create a basic erc20 token then a lot of the uh behavior is a solved problem okay because you know there's no need to reinvent the wheel on how the transfer function works for erc20 tokens because we know how it's supposed to work there's no reason to reinvent the wheel on the approve function because we know how it's supposed to work so for that reason you can use a library to get a lot of the basic functionality of an erc20 token off the shelf without having to code everything yourself and then just customize it for your project okay that's what a lot of you know production cryptocurrencies do so you can use that with the open zeppelin library all right and open zeppelin is just a open source library of uh community vetted contracts cryptocurrencies etc etc etc okay and they have an erc20 contract that we can just pull into our project so i've already added the open zeppelin package to the package.json file here you can see open zeppelin contracts okay and inside this token file we've already imported this opens up and contracts token erc 20 token into our project and we're going to create an ethereum smart contract with the solidity programming language that is based upon the open zeppelin contract okay so uh it's pretty straightforward it's pretty simple basically this this is how a solidity file works so if you go here you see token.sol so capital t token.sol is just how you create a new solidity file um at the top you have to specify the version of the programming language so that's what you see here next we import the library with this import statement it's pretty straightforward and then we declare the contract here so contract keyword so capital t token uh is erc20 okay so that's just and that's how we inherit in smart contracts we inherit from this erc20 so that basically says we absorb all the behavior of this erc20 token here in this current contract so this is now a child of this parent when we say token is erc20 it's just the same here here right so then inside these curly braces we add all the code all right so really i can show you like this if you're gonna create a smart contract this is all you need and then you could say like you know uh we could create a variable here like string public name equals my token essentially what you're doing here is you're just creating a basic contract contract token and then you put all the code inside of here and then you create a variable with a string type set it publicly visible so you can read it outside the smart contract and you assign a name and then you sign it here equals my token all right so that would be what a simple contract looks like if you want to you know inherit from the erc20 standard the import of the project like this and then you say token is erc20 and then now you add all this functionality below so the first thing that we want to do uh with this is actually create a variable so like i showed you a minute ago you could do string public name we can do address that's a data type that's just an ethereum address so if you look at you know ganache uh these are addresses okay so you can do an address data type so solidity is a statically typed programming language so you have to declare the type before you declare the variable and so we say address mentor so mentor is just the name of the variable this is the person who's going to actually mint tokens all right and then we can say public mentor all right and then whenever we deploy the contract we want to say mentor equals message sender okay so message uh msg stands for message so this is a global variable inside of ethereum or inside of solidity where we can get sender is the person who called this function so whenever we deploy the contract uh we run this constructor function this is the function that gets called whenever this contract is created and put on the blockchain and the mentor is going to we're going to set this mentor value to the person who deployed it right here all right so we call this public uh you must call it public in order to deploy the contract payable uh so we can send you know funds and then uh erc20 so this is how we actually get the this is how we run the constructor function of the erc20 token that we inherit from so we'll say name and then symbol okay so let's just call this decentralized bank currency and then decentralized bank currency dcb for a symbol okay so now let's wire up token minting so let me explain what that is and why it's important so whenever we uh issue tokens here in terms of interest paid we're gonna create the tokens on the fly okay so basically uh we're gonna start from zero and create tokens as people earn interest on the deposits in this bank okay so essentially the token total supply is gonna start from zero and then uh whenever we create the token we're gonna give it to the bank so the bank controls it and it will issue brand new tokens so let's look at what i mean by total supply so if you go to ether scan and you look at a cryptocurrency like ave so you just look for ether scan go to etherscan.io search for ave and you'll probably see the ave token come up so you can see the max total supply here is uh 16 million ave so this basically means that 16 million ave tokens will only ever exist so um ave is an erc20 token and this is the total supply that's what i mean by total supply is the total number of tokens so our token is going to start with total supply of zero and then we'll create new tokens as people earn interest in the bank okay so that's going to happen with a minting function so whenever tokens are created a new function called mint will take place and this will uh this this 1000 tokens will get created okay so we can wire up the mint function like this um we use the mint function supplied by the erc20 standard so when we inherit this there's underscore mint that already has this wired up so this will just create tokens behind the scene so if you want to like dig into the code and read how that works erc20 soul you can look at the uh min function inside of here from the load node modules and you can see like all the crazy complex logic that happens if you want to if you're if your code are already advanced coder you can go read through all that step by step but for now just know that this is what creates tokens behind the scenes so we wrap it in our own mint function and one of the biggest reasons we want to do that is uh to ensure that the mentor this person right here is the only person that can mint tokens we don't want some random person being able to do that so inside of solidity we can use a require function so we say require and then whatever it is inside this function if it evaluates to true uh then it will allow this function to be called if it evaluates to false then this function will halt execution and it won't work so basically we want to say msg.sender which we saw a minute ago msusender they must equal the mentor okay so if you're not the mentor then this function won't get called and we can even give this an error message to say that you know if if they they're not this then you know they don't have the mental role we can display this error message on the screen okay so that's our mint function and uh what we also want to do is be able to change who the mentor is because whenever whenever we deploy the contract we will be the person who puts the contract on the blockchain but we want to give like like basically whenever we create this token we will create it so we will be the mentor so it will be the deployer will will be the account that deploys it so inside of ganache this is us right here whenever we deploy the contract in a minute we'll be the mentor but eventually we want to give the con we want to be let the bank be the mentor so we need a function that lets us transfer that mentor role so i'll just uh go ahead and show you that here okay so we'll create this function called past mentor role and what we'll do is give us the address of the new mentor which will be the bank in this case so this has some logic inside of it and make sure that we are the mentor just like we do here okay uh and then we let the new mentor be the d bank that we pass in here this will be this will be the second smart contract that we create we haven't created it yet and then we'll create a new uh we'll emit an event so solidity lets you uh have events in your smart contracts which will define like this so event equals mentor changed so basically what this does uh smart contracts have events so you can subscribe to these from a front-end application from the blockchain like if you go to uh etherscan here and you look at events let's see here let's go to the actual contract so go to contract on a token any token you want to you should be able to see the events here so you can see events right here you can click on that and you can see all the events that have happened here so you can see a transfer event so this is a part of the rc20 standard it requires that you do transfer events you can see approval event also part of the erc20 standard so we're gonna um create our own event here called mentor changed okay so basically like i said smart contracts will have event logs and we want to log every time a mentor has changed and that's exactly what this is for we can also subscribe to this in our frontend application to get like a notification you can configure this to be like a push notification on your phone or something like that if a particular event ever happened um so that's what events are generally used for and that's why we have this mentor change event here all right so let's save this and let's compile it let's go to our terminal here and do truffle compile all right so it worked so what did we just do well we compiled the smart contract so essentially what we did was we created a human readable copy here with this code this is all human readable code and solidity and we took all that code and compiled it down into code that a computer understands so specifically the ethereum virtual machine or the evm so if you look at your um project here you go to let's see here source abis and you'll see the erc let's see here you'll see token.json here so what this file does is uh it does a couple things it creates an api which is just a javascript or a json representation of your smart contract so it describes like the type of functions that are inside of their uh their basic interface that's what api stands for abstract binary interface and you can also see this byte code here so this is the byte code that actually gets put on the ethereum virtual machine that ethereum a computer understands so whereas you know a human can read and change this code a computer needs to understand this code all right so uh you'll see more about this later how we use this when we create client-side applications we'll revisit apis but now what i want to do is actually put this contract on a blockchain so how do we do that well we can go to uh our top level here and go to migrations and look at this deploy script so inside of here we can actually write a migration script that puts the smart contract on the blockchain so essentially what a migration does is it moves the smart contract from our computer to a blockchain it migrates it from one place to another you could also think about it like migrating the blockchain's state from one state to another because it changes the blockchain whenever you put a smart contract on there either way you want to think about fine but you need a migration file to do that so this is standard practice for truffle basically to create a script inside this migrations directory when you have these numbered scripts here so shuffle knows which order to run them in so number one number two okay so number two is the one that we've created number one is initial migration that always exists number two is when we created to deploy the contracts so at the top we import the smart contracts here in javascript so these are these are called artifacts so you see this uh source abis here these are technically the artifact files this is probably better named artifacts but that's okay um you know like these artifacts files contain the abis but anyways truffle uses the idea of artifacts to help create javascript versions of the contracts inside the framework so we can import the token contract we just created like this uh just const token so this is all in javascript here if you're brand new we were writing solidity over here now we're writing javascript that's the whole idea you have the smart contracts and solidity you write pretty much everything else in javascript so uh we import a javascript version of the token like this artifacts require token we assign it to a new variable with const token like this all right and we'll deploy the token so we'll just go in here deploy it like this we use the truffle deployer uh we just say await deployer dot deploy and we pass in this token that we imported here um and then what we can do well yeah let's just do that for now actually let's just do a really simple migration we'll we'll fill up out the rest of this later uh whenever we create the bank itself these are more to do items but first i just want to get it on the blockchain show you how it works show you how to deploy contracts so we can interact within the console so you go to your terminal and just type truffle migrate so migrations run the migration files so whatever you tell shuffle to do inside of here it will do behind the scenes and you can see here uh it worked so you can see the steps it's compiling the contracts so everything's already up to date we already did that step starts the migrations it runs the first one initial migrations which we didn't touch and then number two deploy.js so it worked you can see the transaction hash here okay you can see uh the account that deployed it the balance of the account uh the gas used the gas price and the total cost of deployment here all right and then uh yeah there you go final cost so now we can actually interact with the the with with the token in the console like this say truffle console so this will open a javascript runtime environment where we can execute commands and interact with the blockchain interact with the token that we just deployed so what i'm going to do is say const token equals await token.deployed all right so this confuses a lot of people whenever we get here they see this undefined that's just the logged value that's not actually the value of the token itself you can do token and you can see the javascript version of the token here so uh what does this mean const token equals await token.deployed well again this is javascript so we said const token we create a variable here and then we assign it to the token that gets fetched from the blockchain so what is this await keyword well some function calls in javascript are asynchronous which basically means the function doesn't actually return the value by default so if we said like cos token equals token.deployed this wouldn't work because this is an asynchronous function so blockchains are slow and by nature we want to interact with them in an asynchronous manner which basically means we wouldn't always assign this to a variable we could just call token.deployed wait for it to load the token um and because it's slow we can handle we can handle the return value of an async function in a variety of ways so you can look this up more on the internet if you want to read about this but uh what we'll do mostly in this tutorial is use the async await pattern so we'll just say await when we put this keyword in front of it we're basically just saying we want to wait for this function to finish and whenever it does we want to get the return value uh and assign it to a variable okay so if you want to read more about how promises work in javascript you can just google that but that's basically what we're doing here so anyways i already did that you can't assign a const twice so that's why it's blowing up here but anyways so we can see token address so here's the address of the deployed smart contract so just like any other contract on ether scan they have addresses we have an address here you can see the uh token.name okay so the decentralized bank currency token.symbol alright so just like we coded inside of here we can see token.totalsupply all right is is zero all right so now i wanna show you how the mint function works because basically um basically we wanna be able to create tokens on the fly so inside of here uh well first let's look at our accounts so account we can get accounts with web3 like this so web3 is a library that lets us interact with ethereum blockchain we're going to see more about web3 later on in the tutorial when we wire up the client-side application but basically you can uh interact with ethereum through this javascript library called web3 so we can actually get all the accounts that are in our wallet pretty easily and then inspect their balances like hey how much ether do i have etc etc so we can open ganache these are all our accounts in our wallet so we can get the accounts like this uh web3 eth getaccounts okay so these are all the accounts in our wallet so uh we can say accounts equals this all right and then we can say so so const account equals web3 eth get accounts these are all the accounts in ganache so now we can say um account equals accounts zero so what does that mean well accounts is an array so this thing right here is an array basically anything inside this these curly brackets here it's just like a list of information basically a sorted list um and these are strings okay so strings are just like you know characters inside these quotation marks um and then you see there's commas right so basically uh it's a list separated by commas and everything inside of here is a string so it's just like a a string of characters that's contained inside of a uh parentheses sorry parentheses a quotation mark here okay so for brand new people that's what an array is these are strings inside the array that's what it looks like so we can get the first item out of here by doing accounts and then giving a bracket that's how you read information out of array you say if i want the first thing in the array i use this bracket and then i give it the index so arrays are zero based index which basically means the first item is zero the second item is one the third item is four well i think i think i kind of first item is zero uh second item is one the third item is two sorry anyways so that's why you see account equals accounts and then you read zero out of here uh it's undefined that's okay that's because logged value and you just say account uh well actually hold on a second so that didn't work either uh accounts so let me try this again uh cost let's say uh let's try this again accounts equals i think i have to wait yeah sorry everybody and get accounts okay yeah there you go so here's the first account this is the exact same account here in ganache um so what we want to do is we we can we can read information about this account we can get the account balance we can see how much ether it has so we say account uh we do web three eth get balance uh we can say account and you'll see this huge crazy number okay uh let's just do balance okay so bal is just for balance you see this big long crazy number which doesn't make any sense because you see 98.89 here well that's because this isn't actually the ether value it's the way value so what do i mean by that well whey is basically like a penny for ethereum so you can look at like ether versus whey so the reason it's so i think the best way to explain this whey is sort of like a penny so if you look at us dollar for example one dollar has two decimal places after it so one dollar 1.00 inside of solidity and ethereum we don't use decimal places at the smart contract level or the ethereum virtual machine level we don't use decimal places we only use uh you know integers basically so uh you would write a dollar at the ethereum level like this you would always express a dollar as a hundred pennies you'd never express it as one point you'd never express it as one dollar with decimal places after because we don't use decimals so same thing with ether um basically ether has you know smaller resolution as well so basically if you write ether like us dollars it'd be 1 followed by 18 decimal places like 1 2 3 4 5 6 seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen so if you were to write ether without decimal places you would express it in way all right so way would be one followed by one two three four five six seven eight 10 11 12 13 14 15 16 17 18 18 decimal places after the zero this is how you express ether at the smart contract level with zero decimals okay you use this big number like this so that's why you see this big long number um you see 98.89 ether here but it's really this much way all right so that's really important to know the same is true for tokens many tokens so tokens will have decimal places so you'll see this like erc20 token decimals you'll see 18 decimal places a lot of times that means there's 18 zeros after the decimal that's just really standard because ether has 18 decimals after the zero and they make the tokens work like ether so that's why the balance looks like this here and for the same reason one thing i'm going to show you this first is we're going to we're gonna test out this mint function that we created in the smart contract so inside of here um we're gonna call this mint function we're gonna we're gonna mint tokens for our account so first of all let's just check uh the balance of this account show you how the token works again the erc20 standard has a balance of function so let's zoom in on this you know it's got a name symbol decimals which we've seen it's actually to show our decimals in our contract here so token.decimals and let's actually do it like this so let's say a weight decimals equals a weight token.decimals all right and then decimals to string all right so it's 18. so we have 18 decimals after the zero for this token just like ether all right so the reason i want to do this is to now look at the balance of function this will basically tell us how many tokens this person has so we can pass in the owner address which we'll do for uh this account here and it should return zero because no tokens have been created yet okay so we can say uh balance equals await token balance of uh account oops to balance is zero so uh let's mint tokens um so one thing i want to show you actually before we do that is this account here let's let's let's do let's do a count balance here or ether balance okay so ether balance so what we can do is actually convert this to ether i'm going to show this a second ago but i forgot so uh we could do web3 utils so web3 is built in here go through utils from way and then pass in the ether balance oops sorry and there we go we convert it straight to ether like this and now you see the whey balance uh to either we gotta say the reverse we have three utils two way and then say you know 90 gosh sorry uh 98.8 and convert it to way like that okay so this is a nice helper that we can do so the reason i say that is because i want to mint tokens uh so i want to do token mint and then i do it for the account and then i want to do a mount i'm going to say web3 utils to way because remember at the smart contract level we don't do decimals we pass in tokens without decimals i'm going to mint this person 100 tokens all right 102 way and then there we go so mentioning our self tokens all right and it worked so now we can say token to the token balance equals a weight token.balance of account token balance is now this big number so we can say token balance to string convert to a string away from a big number all right and then we can convert it to uh the actual token amount not the way amount like this let's see web 3 utils from way token balance there we go boom 100 tokens and we can also see token total supply like this and then do web three utils from way total supply and there we go that's 100 tokens total so you have just created your first smart contract put it in a blockchain open the console and actually interact with ethereum so congratulations this is the first milestone where we set everything up now we want to go ahead and start creating that second smart contract the actual bank itself so now let's get into coding the actual bank contract itself so go to source contracts i'll collapse some of this so you can see it so go to uh you know source contracts and then dbank.sol so uh inside of here we have some placeholders okay we have a deposit withdrawal function that's essentially what this contract is going to do it's less deposit funds in there and then we can earn interest on it and we will get this interest back whenever we withdraw it okay so uh let's go ahead and and let's take a look here first actually here's our here's our diagram we take ether we deposit into the bank with the deposit function we wait and then uh we withdraw the tokens like this and you know the bank actually mints the tokens for us to pay that interest out whatever we call this withdrawal functions we're gonna cut all this out step by step so let's go ahead and get started so we can go inside here and uh the first thing we want to do is assign the token itself so remember whenever we deploy this we want the bank to control the token because that's who's going to mint the tokens for the depositors we just minted tokens in the console ourselves because we the deployer still had control of the token in that sense or that at that time but what we want to do is actually transfer the ownership of the token to the bank itself and let them meet the tokens so the first thing we want to do inside of here is modify the smart contract to uh control the token so first it needs to know about the token so we've imported the token here all right import token.sol which we created here all right and then now uh we change the constructor function this is again the function that's run whenever the contract is deployed to the network the special constructor keyword and we say token and we pass in the address of the token all right so basically this will um accept the address of the token its location on the network we sell the address the token in the console and we want to store this token inside the smart contract with a variable a state variable like this so token private token this is a state variable its value is actually written in the blockchain but we use a local variable here token and we basically can assign it into this constructor function like this okay so we just say constructor token underscore token equals token which is this token all right so the whole idea is we just want to assign the contract this token is this contract needs to be aware of where the token is all right so we just save that now let's modify our migration file so let's go here the migrations directory go to deploy and then we'll fill in some more information here i'm just going to paste these in here and we'll talk through all the steps so in our initial migration all we did was deploy the token to the network here so deploy our deploy token but then we want to execute several other steps after that right so uh we want to fetch the token token equals await token deployed we saw that in the console it's the exact same code we assign it to a variable then next we deploy the bank to the network just like we deployed the token here okay so we do deploy or deploy a bank but then we pass in the actual token address so that's what you see here for the bank it needs to understand the address of the token in order to keep track of it so that's what we do here all right and then we assign uh this to a variable just like we did so token.deployed so dbank.deployed scientific variable and then the last thing we want to do which is the most important step not most important but a critical step is pass mentor role to the bank address because again we want to take the token and instead of the mentor controlling it we want the bank to control it so we created that uh pass mentor role function here inside the token that transfers the ownership or the minting to a different account and so that's what we do right here we call that function we pass in the d bank address and by default uh it's going to be from the account who deployed the contract um yeah the account who deployed the contract which is that first account in ganache right here okay so we'll save that and that's the first thing basically we just uh keep track of the token inside the smart contract and then we update the migration script to deploy the bank on the network and then transfer the minting to the token itself so that it can pay out the interest to the depositors so let's code out this contract again we got we've got the basic set up here we have the functions um coded out but we want to fill them in we have the instructions here but there's two things we need to write okay so the the code for the actual smart contract itself but also tests for the smart contract so what is that well basically you can write code that checks to make sure that your code actually works that's what a test is so tests are important in many aspects of software development they're particularly important for smart contract development because smart contracts don't change when you put them on the blockchain um well all you can really do is like deploy a new copy of the smart contract if you want to change the code itself so you really want to make sure that smart contract works before you put it on the blockchain now if you're just developing an application with ganache you can put new copies on it all that kind of stuff all day it's okay whenever you go to like make your application work for real you want to write tests and you know make sure the code works the way you want it to before you go live to a blockchain and put it that way so that being said you can write tests in javascript so you can look inside this test directory and you can see the tests already written here so i don't want this turn into an eight-hour tutorial so we're not going to write the tests out step-by-step we're actually just going to leave them in here inside the starter kit but this these are the tests that actually check for the behavior the smart contract and they're going to fail right now because we don't have the code written but what's cool is we can actually write the code to make these tests passed and we'll see what the uh we'll see like what the behavior of the contract actually is supposed to be like whenever we do the tests so i'll talk about the tests here i'll go through the testing framework show you how it works so this is a mocha testing framework in the chai assertion library so mocha comes bundled with truffle and then chai gives us these assertion matchers like so expect all right all that kind of stuff so let's just comment out some of this stuff and and make it pass okay well some of it'll work some of it will work right now already um so basically we have the token test inside of here already and we see the exact same setups so basically we have this contract debank and we get the accounts so the deployer and then the user two different accounts on ganache so this account and this account and then we see uh um you know we basically do like we do the migration we get a token we get the bank and then we pass the mentor role to the bank just like we did in the token setup or just like in the migration setup and we write some tests we say you know testing token contract and then we just check to see the token exists it has a name all right just like we did in the console so you write code that says like it it reads like english so it you know checking token name which you can write that differently and say like it has a name or something like that you know it you know has a symbol or something like that and each inside of those um you say expect and then we just like get the symbol and we say expect it to be equal you know dcb or expect to be equal decentralized bank currency expect the supply to equal zero expect the metro roll to belong to the bank all right same thing here we can also check for failing transactions so we shouldn't be able to pass the mentor role anymore once we've done it so we can see it's ejected with evm revert which is the shortcut that we've saved from here etc etc all right so let's go to run those tests we'll say uh let's exit the console here dot exit and then say truffle test now we're back into our terminal not the truffle console anymore so let's combine the contracts and then boom okay so uh looks like it said expect dcb got dbc all right so i'll change that i actually wrote the code wrong so let's go to token dbc sorry if you saw that earlier i'll so let's let's make the test pass so that's the whole idea the test fails we change the code to make the code work and then the test pass okay all right so now the token works exactly like we want it to has a name has a symbol has a total supply has the mentor role to the bank um all that kind of stuff so boom you can reset this test if you want to now let's let's get into coding the bank itself so we're going to describe testing deposits so um the whole idea is that you can deposit ether into the bank so what it's going to do is check the balance uh it's going to call this deposit function and we're going to deposit 0.01 eth from this user so this second account in the list and then basically whenever that happens it should increase the bank balance so if you go here again this user is going to have an ether balance let's say their ether balance before the deposit is 100 ether okay they're going to deposit you know 0.01 ether into the bank oops sorry 0.01 i believe is the correct amount it has 0.01 ether into the bank okay and then their balance should go down to like after they do that that should be like 99. uh you know 99 ether plus plus a little bit less because they have to pay a gas fee um and then so that's that should be their balance in the bank and then their their ether balance should be less than this slightly less than this because they pay a gas fee let's let's explain that whenever you create transactions on the ethereum network you have to pay gas fees uh to prevent spam on the network to help maintain the security of the blockchain so basically if i send cryptocurrency around from one account to another then i pay a gas fee to do that if i send if i put a smart contract on the network i'm creating a new transaction i have to pay to do that if i'm depositing funds into this d bank here contract that's the new transactions i have to pay to do that so you can think about it this way uh anytime you write new information to the blockchain you have to pay but anytime you read information from the blockchain that's totally free okay so reads are free rights cost gas so let's go back here and look so it should increase the balance to this all right we can see here this is 0.01 eth this is also 0.018 and then so the deposit time should be about zero we'll looks at that look at that in a second deposit status should equal true so they are deposited and then yeah so we'll start off with that so we'll run the tests all right so it's not working um so you see all kinds of failures here that's okay we're gonna make them pass so let's start off with this uh the balance should increase so go back to our bank excuse me and uh we start off with this so we want to go with the core functionality of checking that the deposit exists so we want to track a way to store the ether balance so we're going to use something called the mapping okay so mapping is pretty easy uh we added something else like this we say mapping and we say public ether balance up so mapping is just a key value pair storage mechanism for solidity so they've got like a dictionary where you have a word and then a definition so you have a key and a value in a very similar way with a mapping this is a way that you can store you can use a blockchain like a database you could this could be a number it could be an id like if you want book number one you could have a uint here and then return you know a book so in this case though we're just going to have an address that's going to be the key so the person's uh address who's depositing and the uint is going to be the amount of ether or cryptocurrency and the way value that they've deposited so be like a dictionary so we'll say like here's this person's address how much cryptocurrency do they have deposited into the bank that's this mappings for it's going to be public so we can read that information outside the smart contract in the console in an application and uh we'll call it ether balance of okay that's the variable name for this mapping so uh inside this function we can write new information to this mapping like this we say ether balance of and then the address is going to be msg.sender message.sender okay this is the person who's calling the function again so basically we're going to say this the address is this person message sender and then the balance will be ether balance so we we could just say like one all right so anytime they deposit you know well let's do this that's that's not a good example message dot value so you can basically just say whenever they deposit we take their message they take their account or take their address use it as the key and the amount of cryptocurrency they're getting sent in is message value so where they send ether in the transaction this is the amount of ether that they're sending some message value this is the person who's sending it message sender message value is the ether amount so we can just assign it to mapping like that now we want to take it one step further we want to be able to call this function multiple times so we can just uh add that value to the last value so basically just copy this uh we can we assign values to a mapping like this but we can also read values out of that we can read the value at the mapping like this and say ether balance of message.sender plus message value so we're reading it out here we're adding more to it and then we're assigning it back here okay so that's what we do in every deposit that's the core functionality really of the deposit okay so let's just uh let's just try that and let's try to run the test and see if a new test passes i think the first test should pass i think this balance should increase should pass let's see here yep it works so we got a brand new test to pass so the balance should increase um let's take out token go to the test and see yeah yeah so the balance does increase that worked perfectly so now uh we should do the deposit time should be greater than zero so how do we what's the deposit time for well basically the deposit time is so we can calculate the interest earned so whenever you deposit money to a bank think about your uh apy or your annual percentage yield uh where basically they determine how much money that you'll earn on your deposit over a year so if you have one percent apy you'll take one percent of your funds deposited and give you that amount in interest okay so we can do the same kind of thing inside of our bank so we're going to do we're going to do that inside of our account so how do you do it inside of a bank well oh how do you just have a blockchain base bank how do you determine the time well you can do it from the number of blocks that have passed okay so there's a predict you can always tell the time on the blockchain from the blocks so if you go to ether scan you look at these latest blocks they all have a number okay uh block number one one eight eight two eight seven six and then you see the one before that all right remember that remember that remember that so ethereum has a block time so we can we can predictably say like what block like we can predict like when um you know certain blocks gonna be mined on the blockchain roughly speaking um so we can use the blocks that have passed in time to calculate the interest so that's why we want to and so so we're going to we're going to keep track of that you'll see it be clear in a second but we want to track um basically the deposit start we want to get the time stamp of the current block so we can make the calculation on the actual interest that they're getting paid okay so uh we'll create a new mapping so ether balance of we'll say deposit start so essentially we want to uh we want to basically as i'm trying to best play explain this basically we want to keep track of the time stamp of when their deposit is with the block on the blockchain so we'll do like this we'll update that value like this all right say deposit start for message sender equals deposit start uh plus the block timestamp okay and then save that go back to our terminal run the test some more tests are passing all right so deposit time should be greater than zero that works so now we want to check the next test which is um deposit status should equal true so now we want to keep track that they are actually depositing so we can go inside the test and do that or sorry inside the smart contract and do that we want to uh set the status to true so we want to create a new mapping for that so basically we'll just create a new mapping like this so it is deposited and then we'll add it here okay and so now we can run that test again and there you go the deposit status is equal to true so now uh let's finish off a few more things let's create an event for deposit so again we use events to track that certain activities happen on the blockchain um so we want to trigger a deposit event we create it like this we give it the user the ether amount and the time start and then we can emit it inside the smart contract like this so emit deposit message sender message value block timestamp all right and the last thing we want to do is fix this test so depositing should be rejected under certain conditions so i showed you how require works in that previous section uh but we're going to add some new requirements here so we want to make sure that the deposit is not already active so if they're already deposited we don't want them to call this function again so they got to withdraw before they increase their deposit they want to just for this particular example so that it can support borrowing and lending all right and then um and also make it easy so require message value equals greater than this so we want deposit to be at least 0.01 eth okay so now it's run the test and they should all pass because we have this failure case here we try to deposit with a value less than 0.018 and that should that should not work so for homework you could uh try to call it twice and also get this failure there we go they all pass awesome so again you could you could write a new test here to make sure that you can't deposit when you're already depositing and check for this failure right here okay so now we're officially done with the first part of the smart contract we're getting really close um we're gonna process the withdrawals so um let's do this okay let's just talk about what needs to happen whenever they withdraw this is going to get kind of complicated but i want to show you so whenever we withdraw from the bank let's just do a new drawing here all right so the flow here is the user deposits funds into the bank and then they wait you know let's just say for a while whenever they withdraw they're gonna get two different currencies back they're gonna get their principal back which is the ether but then they're also gonna get this token back based on the interest so let's say they're earning you know 10 percent apy well we're going to take 10 percent over a year and divide it up by the actual amount of time that they deposited and then pay them that amount with a second currency in tokens so for simple math you know if they deposit one ether uh and then their deposit for you know one day then basically we'd take like ten percent and then divide it by 365 and it would be this much all right so it would be pretty small amount but uh so that we're gonna do some math to do that and we determine the amount of time that they deposited again from these blocks on the blockchain and how many blocks have passed okay so that's why we track this block timestamp all right to see when it happened so um yeah yeah so it's kind of complicated but we're gonna walk through all the basics of how this works so let's start off with the core functionality which is just withdrawing the ether itself okay so if you go to the test and then you uncomment this out so distract withdrawals um you know we've got some set up here where basically they're just um they're just basically depositing values in here we just wait for a little bit and then we withdraw so it does a deposit it waits for some actual amount of time so you can see what the weight function does here oh sorry let's go to the top you can look at this helpers file he says wait what it does is it just waits a few seconds basically and then um it does a couple things it checks that the ether balance that it checks that the balances are correct so it takes the uh balance out of the bank and gives it to the user and then it checks that the user should get their ether back and then the user should get the interest paid and then the depositor data should be reset okay so we're going to test these things one at a time we're just going to test first that the ether should come back all right so i'll show you how to do that so you gotta debank and then basically whenever withdraw send ether to the user uh we use the transfer function so message sender the person who is um withdrawing the money we're gonna send ether to them with this function called transfer so this is just a function of the solidity that sends the ether around and we how much do we want to send them well we read their ether balance so ether balance of message sender okay and we send that eth back to the user so either balance of message sender we send it back so that's the first step to sending this ether whenever we withdraw from the bank okay and then after we do that of course we reset their data we say ether balance of message senders now zero because we just took it out um so that's the first thing so let's run the test and see if it passes all right so it works they receive their ether back so next let's reset all the rest of the deposit data uh well before we do that actually let's now look at the uh interest so in order to calculate the interest basically let's do this we first check the user's hold time or huddle time like this so deposit time equals block timestamp minus the deposit start so basically that's why it's saying we determine the amount of time by looking at the top blocked the blocks we look at their time stamps their time stamp comes back in seconds okay so the seconds are based on epic time so you can look at this this epic time right here uh let me just put it up here so if you want to take the cur the current epic time of time recording this video is this so this is just a number of seconds that have passed since like 1969 i think is the day um but you can always express time in seconds since that event as this this is the current epic time so block timestamps have this baked in so you you do time in seconds inside solidity so that's why we started the block time stamp here deposit start was at this time so block time stamp so now we just say how many seconds have they been depositing for take the block time stamp and subtract uh the start time the current block timestamp and subtract the start time okay and then so we can kind of interest like this we can take we basically take an annual interest rate and we calculate how much interest that person would earn per second so for example sanchez 10 apy um or at 10 percent let's just say 10 percent per second or something like that then this is how you do it okay you would divide it and find the interest per second all right and then you get the actual interest and we give them tokens based on the actual interest like this we take the token and remember the bank now controls the token so the bank just creates the tokens from scratch and it sends them to the user with that men function that we played around with in the console earlier so basically just say token dot mint message sender interest all right and then we want to reset the deposit data all right so basically you know we got the ether balance already but we want to reset the deposit like this so deposit start is now zero okay because we don't they've now withdrawn everything ether balance is now zero because they've withdrawn everything so it is deposited they are no longer deposited and the last thing we want to do is uh basically make sure that they have deposited because if they haven't we don't want them to withdraw and we're gonna cash their balance at the top of this so user balance okay and then we can say we want to emit a event at the bottom so withdrawal event like this it's kind of moving kind of fast here but this is the this is the tail end here so withdraw message sender just waited so we did a deposit event here all right pause this and take a look but the last thing we need to do is actually uh create this withdrawal event right here and then we just created it here it's basically the same thing as the deposit event just named differently and we do a new time and we log the interest and let's see here the last thing we want to do is probably change this user balance probably just yeah update that code to use the user balance so we're using the same variable twice all right so let's run the test now let's actually uncomment all the tests and it should all pass it's waiting every time the test run it waits two seconds all right there we go it all passes so that is the complete code uh for the bank and the token so the last thing we want to do is deploy this to the blockchain itself so we can create the front-end application so we can do that like this say truffle migrate dash dash reset okay so the dash dash reset what it does is it it takes a new copy of the smart contract and puts it on the blockchain so this is uh like i said the smart contract code can't change so the best thing you can do is just deploy a new copy of it put on the blockchain and that's exactly what we've done so now let's go ahead and move on to creating the client-side website for the bank and interacting with it all right now let's start coding out the client side portion of the project so we're gonna do now is create a website that talks directly to our blockchain okay it's going to interact with the smart contract that we created okay so um we're going to talk directly to these smart contracts for the bank we can deposit ether into this through this website it's gonna be user interface that will serve as the front end part of our project okay so this is front end and this entire thing here is the back end all right so we finished the back end part effectively now we want to create the front ends people interact with it so if you go to our uh project here um let's just as you can see our smart contracts everything we've done so far you'll want to uh go to source components and you can look at this app.js file so i'm going to minimize everything else for now all right so source components app.js and here uh you can see some code already wired up for you and we're going to fill this out so what is this well this is a react component so we're going to use react.js to create the client-side application this tutorial so react is a javascript library for base for building user interfaces so basically it lets you it lets you write javascript interfaces with less code you get a lot of stuff for free uh you'll see how react works in this video you have to be experienced coder you don't have to you know be an advanced react user in order to follow along with this you'll you'll get the basics as we go the important things to understand is react uses components to organize the code um a component looks like this you see this class you know component name extends react component and then you put html and javascript mixed in together inside these components so html is just like the html markup language that you use for a web page but then you have this other code which is javascript inside of here and then you can use these curly braces to put javascript inside the html code so it's like you know double nesting so like html inside javascript and then javascript inside html okay um so if you go to our app you can see class app extends components all right and then we put all the code for the component inside these curly braces a lot like our smart contract where we put all the code inside those curly braces so uh we have a bunch of important things imported at the top we don't have to worry about that too much we'll just see it all filled in this project okay so other things to know about react is it uses components to manage all the behavior and all the display logic and all that kind of stuff for the app it also uses something called the state object so we'll see the state object um play out in this tutorial so think about state like what should be shown on page you know sometimes today it's hard to describe let's just let's just use this example here we have to do list so what needs to be done you add items to the to-do list item one item two okay so how does this application know how many items are on this to-do list right how do we add new items with something called a state object so the fact that this to-do list has two items on it is a description of the website's state and also the state of this particular component that governs this to-do list okay so um that's that's what it means by state so you manage it with the react state object you can see it here so they have this pattern they give tell us how to do it so constructor props this state equals this big object here and we just put in the items for the to-do list and the text okay so you'll see that inside of our uh app here constructor super props to state and then we have some placeholders that we're going to fill in so we're going to use stake kind of like a front-end database for this application so like we're going to load in our account store it to the state so the account that we're connected to the blockchain with we're going to store the token smart contract to the state we're going to store the bank smart contract at the state the balance the bank address all that kind of stuff okay we're going to use it kind of like a front-end database so now excuse me that's an introduction to react so we're also i don't want to spend much time writing uh css or styling this particular application so we're going to use bootstrap so this is a framework for building websites and user interfaces that look nice without writing a bunch of extra code okay so we're gonna use the react version of bootstrap and you can see that inside this package.json here so react bootstrap right so like if you go to this app you'll see we're gonna import some tabs from react bootstrap we're gonna use some components from react bootstrap we'll get a bunch of freestyle you'll see all that as we go along okay and then the last thing i want to mention is web3js so let me just pull that up so web3js is a javascript library that lets us talk to ethereum we saw web3 in the console we did like web3 you know utils from way web3 git balance all that kind of stuff so web3 is basically going to turn our application into a blockchain application all right it's going to take all this javascript code and connect it to the blockchain itself so if we don't have web3 then we don't have a blockchain application the other thing we need to do is a lot of setup here but i want to get through that before so we can start coding is uh to turn is to basically connect our web browser to the blockchain itself so we do that with metamask so open up meta mask and then go to uh import account all right and then it'll ask you for a private key so we want to do is take our account from ganache here click on show keys copy this of course never use this private key for real because everyone who's watched this video could steal your money so copy that private key put it in here click import and i've already done it so you know it won't do it again but anyways i've changed to this account you should see your account balance here which is the same as ganache right the last thing you want to do is connect to a ganache network so you won't necessarily see it here uh you can do custom rpc and then you can call it ganache you could just say you know ganache you say http localhost port 7545 you can go here and verify that you could just copy it rpc server http colon forward slash forward slash 127.0.0.0.1 colon7545 that's just localhost you can paste that in um all right chain id you can look at that from ganache here as well say eth okay so this already exists so i can't do it again but uh you can name it ganache and just make sure you connect to that network before we get started all right so now we have done a lot of the prerequisites let's go ahead boot up our web server i'm going to open a new tab here uh and say npm npm run start this will start your web server if you ever need to stop your web server just hit control c alright and that will stop it so now this looks like it's got an error that's okay we can fix this so the air went away but now you should see a blank canvas here all right we can see a nav bar at the top here's our uh d bank okay so we're making some good progress here we've actually got some code on the page now let's uh actually wire some of this up so we can make it work so the first thing i want to do is just connect this application to the blockchain so we're gonna do that with the web3 library like i said and it's pretty easy to do it so we'll start with this basically we're going to get a copy of web3 that metamask injects so metamask basically puts a variable in our browser that we can fetch out and it's like a handshake basically metamask gives up something our app can take it and turn it into a blockchain connection so we just do it like this it's pretty easy we say const web 3 equals new web3 window.ethereum so window.ethereum is what metamask gives us and then we can turn that into a new web3 connection like this which we import here from the top of our file and we turn it to a variable called lowercase web3 pretty simple all right now we want to make sure that the user is actually connected to metamask so we can do this basically we can wrap a conditional inside of here if type of window.ethereum is undefined or if it's not undefined then we can you know do this connection and if not then we want to say uh you know hey please install metamask okay so if they access on a different browser doesn't have metamask installed then we want to show that error message so i can open like safari for example i don't have meta mask installed on safari and you can see this error here so please install metamask that's what we want a user to see you can customize this error message and say hey you know you're visiting a blockchain website you need to have a special browser extension blah blah blah blah blah you know have some special instructions be much more helpful link off to the website tell them how to do it maybe show them a video or something but here's the basics like you could just show this alert that says please install metamask okay so now excuse me the next thing we want to do is actually uh fetch some information from our blockchain connection so we have already checked to see if metamask exists uh we want to let's actually just get the network id so what that does is see which network are we connected to so inside metamask we can connect to multiple blockchains here and they all have ids so ethereum mainnet's one covan test network i think is 42. uh and our ganache is 57.77 right yours might be different but that's mine so 57 77. so we want to get that network id to determine which network we're connected to because you always want your app to know like hey are you on the main net are you on a test network are you on ganache so we're going to fetch that id so let's do that and log into the console all right this will just make sure that we can actually get the connection to the blockchain and that our application can detect that we are connected to uh the correct chain all right so yep there we go if you can see on my screen here uh 5777 is logged to the console you can open your console like this you can do inspect go to console if you're in chrome which you should be in chrome for using metamask here and see 5777 here so that works all right we logged the console so now we can uh fetch all the accounts that we're connected to from our metamask just like we did in the truffle console before get the accounts all right and then we can do console log accounts 0 to get our particular account okay so i forgot an s here yep there we go there's our account that we're connected to with metamask you can see here 0x2371 0x271 that matches exactly what's inside of ganache yep awesome so we're making making some way here so let me also explain this low block chain data function so this is inside of react's life cycle method component will mount um so basically we can call this function inside here like this and that's exactly what this does all right so now we want to do is actually fetch our balance we want to check our earth balance like this we can do const balance equals await web3 get balance account zero and then we can log that the console all right there's our eighth balance so instead of just logging into the console let's actually set it to the react state object so remember i said that we're going to treat the state object kind of like a database we have a place for our balance here so we can store our balance inside the reactor object like this so instead of just logging it we'll essentially save it we'll say this dot set state all right and then we'll say uh account accounts zero so we saw a second ago all right we're gonna update the account right here and then we're gonna update the balance balance and we're also going to go ahead and store the web 3 connection here now if you're an advanced javascript developer you probably already know that you can you know shortcut it like this but i'm just gonna leave it longhand especially for beginners watching this video makes it easier to understand okay all right so now what i want to do um is also make sure that the account exists okay so this will also make sure that the meta mask has been connected because sometimes you have to connect metamask when you're loading your application so let's do this i'm gonna wrap it inside this conditional that says basically if type of account you know is not undefined then we'll do that what we just said otherwise we'll show an alert and say please log in with metamask okay so now we want to load the smart contracts into the application we've loaded our account from metamask now we want to get javascript versions of this token and also the bank so we can call those functions with web3.js and create javascript versions of them in the app so let's take a quick look at how web3 uh creates javascript versions of the smart contracts okay so web3 like i said as a javascript library let's interact with ethereum we can create javascript versions of the smart contract so that we can call their functions in javascript inside of our client-side application a lot like we did in the tests like we did the migrations um but we're going to use web3 versions so you create a new web3 contract like this you say new web3 eth contract and then you need two pieces of information you need the json interface which is that abi we saw earlier don't worry i'll show you again in a minute and then the address which is uh the location of the smart contract on the blockchain okay so basically this interface is going to tell you all the functions the smart contract has what their function arguments are all the events all the variables all that kind of stuff okay so essentially we'll create a new contract for the token all right let me kill all these instructions right here we'll basically create new contract for the token and also the bank okay so we need the abi for the token this is the json interface so we're not going to do these options basically we'll just say the address the json interface is the api so we can say like const token okay so where does this information come from well the abi is in here so go to source apis um token you can see here this is this big json object so nested inside of here is the abi key all right so anything under abi is the abi it's this array with all this information inside of it so we can go uh to the top of the file you can see the tokens already imported so token is this json file that's this entire thing so we can take this json file all right and then dig into it and then say token.abi and that's the api so next we can get the network we can get the token address from the network like this we can dig into here and go to networks and then find the current network we're connected to and then find the address here okay so you do that like this you say token dot networks and then you pass in the network id which we saved here all right and then we get the address so this is you could break this up do some more error checking and not you know like read it out so fast like this but i'm just going to leave it that way so it's easier to understand so the same thing is true for the bank d bank and then we're going to change this to d bank all right and then we're going to save the dbank address to a variable like this and then we're going to save all this to the state object like this all right so basically this creates javascript versions of the token and also the bank and then it saves all this stuff to the react state object we want to save the token we want to save the bank we want to save the bank address okay so now like i said this can get a little bit brittle and i don't want to spend like all day trying to do advanced error handling so we're just going to wrap this in a try catch for javascript so basically if this code fails we'll catch it and log it to the console and do a window alert all right so there you go now we've successfully loaded up all the blockchain data to the application so we'll save this we'll go back and look at the app we don't see anything yet that's okay we can tell that our uh information is still there we can you know log the dbank address to the console or something like that say console.log debug address and there you go awesome so it's working so now let's actually fill out some information on the page let's make the front end look nice let people use it let's add a welcome message here at the top so we can edit this html to lay some information out on the page we'll say welcome to dbank so there you go awesome welcome to d bank and then again so all the steps in bootstrap so bootstrap gives us these nice classes so that we don't have to write a bunch of styles for ourself um yeah some people don't like it they like to write their own style sheets but i'm a coder not a designer especially for these tutorials it's so much easier just to have you know this stuff in here so um we're gonna add the user address so we'll say this dot state account so basically like saying you know welcome to dbank here's your address okay we know welcome to d bank and then they're they're saying it's you right um so the next thing we want to do is add the functionality to where they can deposit into the bank and then wait and also withdraw okay so we can add some instructions on the page um like this we can say like you know how much do you want to deposit you know the minimum is this what we're going to do is actually uh use tabs inside of bootstrap so you can see these tabs already here we have this tabs thing this is comes from react bootstrap so this is an intelligent component uh that's imported at the top so you see tabs you already have a tab available okay so we're gonna do is create a new tab here i'm just gonna remove this and say you know tab like this so tab event key equals deposit uh title deposit okay so we're going to create a new tab like this with this information so you want to make sure this works exactly like that before we do it i'll create a new div here for my tab completion is not working in react right now i'm not sure why sorry everybody normally i have emmet configured to do tap to completion and it's not working like i expect so we'll do this hmm i'm not sure why that broke i changed my sublime text settings okay so we can say uh you know how much do you want to deposit let me see on the page here all right see deposit tab here we can copy this and also make a withdrawal tab just copy this say withdrawal all right and you can say something like uh instead of how much do you want to deposit you could say you know do you want to withdraw plus take interest all right so there we go so you have like a deposit tab you know how much do you want to deposit withdraw you know do you want to withdraw plus take interest so there's the tabs that's how they work now we're going to add information to these tabs to actually uh deposit funds into the bank and withdrawal so let's go ahead and do that now all right so now i've pulled some code in here inside this tab so say how much do you want to deposit you know the minimum amount is 0.01 eth one deposit possible at a time and then we have a form here to actually do the deposit on the page all right so let's just refresh the page here click on deposit and you'll see this come up how much you want to deposit this is the minimum and then you can put in an amount here you know this et cetera et cetera so this won't work yet click deposit like nothing happens sketch refreshes the page but i want to lay that out on the page if you want to copy some of that code from the final code solution you can do that if you want to pause the video and look and see what i've written you can look at that as well okay you want to kind of go through this a little faster because i went to the important part which is actually wiring up the form so i'll just pause and we'll continue so there's going to be three major steps here we need to configure this input to handle the input from the user and then we want to wire up this button whenever the deposit is clicked so we'll we'll configure this on submit right here you'll see that in a second and then finally we'll take that information and uh update this function to actually call the deposit to the smart contract inside the smart control of the blockchain okay so uh let's do this first so let's go to the input we're gonna update these one by one so we got to give it an id first okay so i'm doing this on multiple lines so ib is going to be deposit amount so step is going to be 0.01 all right so the input type's going to be a number so that it knows that you can be a number and you'll see how this works in a second so actually let's go ahead and save it take a look here so now if you get a deposit it's a number and you can just do boom boom boom boom and it steps by 0.01 so knows the number input of course you don't want to be negative it'll fail if you do that and then next uh we want to give it a class name so that it can look nice all right now it looks better it's actually the full width and next we want to give it a placeholder so you can see that it says you know hey what amount yep oh nicey amount and then you can just do up down or you can you know 0.05 whatever all right and then go up down from there um next we want to make sure people are filling this so we'll say required all right and the last thing we want to do is give it a ref so we're going to do it like this basically we want to keep track of whatever information the user has put in so react does that have something called a ref we basically give it this function we said this deposit amount equals this so basically what's happening here is it's storing uh the information from the depositor and saving it to this deposit amount this is a function uh that gets called it's getting passed into this rep you'll see you'll see in a second whenever we read it out up here okay so deposit 0.01 okay so nothing happens when we click it we want to make that happen so the first thing we're going to do is uh update this on submit handler so this is a function that gets called whenever this submit button is clicked or if we hit enter on the form first thing we want to do is click event e dash sorry e dot prevent default this this prevents it from refreshing the page click deposit click you know like one click deposit and then you don't see the page refresh so that fixes that next we want to uh get the amount so we'll say let amount equals this dot deposit amount dot value so that's that's that's where you're reading this from it's basically catching this value that was saved here so this gets saved with a ref and then we read from the ref right here to get the amount that was put in by the user and we convert that to whey like this so amount equals this because remember we convert ether to way with 18 decimal places so we can do that like this probably better to use the web3 utility but this is fine um and then lastly we want to take this amount and pass it into the uh deposit function okay so this deposit function again is up here and this is where we will actually interact the smart contract so let's just see click deposit click one so still nothing happens that's okay but we can ensure that we are wired up to the deposit function here we say console log amount because it'll only log out if we've actually wired it up properly and passed it in here so let's just click one and we should see one fall by 18 decimal places yep boom there we go awesome it's working so now we actually want to we actually want to interact with the smart contract in order to do that so i'm going to show you how we do that with web3 so with web3 whenever you call meth call functions on the smart contract whenever you do things like create transactions you have to do send functions so you do it like this my method so contract like d bank for example methods we fetch the method we fetch the method name so like deposit we pass in the function parameters and then we say send so you have to say send after the transaction and give it some options to actually create the transaction because if you just don't if you do send it just returns the function itself okay so i'll show you what i mean by that so we'll replace this and say like await this state d bank so that's that's the web3 contract that we save from the state object so methods deposit okay and then we do send okay so value is message value that's the amount of ether that we want to send okay so the amount and then from we got to tell it which account it's coming from so this dot state dot account all right so lastly we want to wrap this in some basic error handling um which you could probably handle this a better way but this this will work for now right so let's give it a roll deposit let's deposit one ether let's check our balance first go to ganache 94 ether deposit i see a metamask confirmation pop up click confirm and boom there we go 93 ether awesome it worked very cool so congratulations you've just wired your application up to your smart contract and actually interacted with it so now let's go to the withdrawal part okay because we want to get the money back out we also want to claim the tokens now let's process a withdrawal so it's going to be pretty straightforward basically let's just go ahead and replace the tab here with the final code solution all it is is a button that calls the function to withdraw there's no form we don't have to have any user input the user just says has to say i want to withdraw and then sign their transaction and it'll give them their cryptocurrency the ether plus the tokens so here's the button uh it's just a submit button with some styling on it we have this on click handler so instead of on submit it's not a form so we don't submit we just click so on click i always say this dot withdraw okay and then we pass in you know the data and then we fill in this uh withdrawal function here to talk to the blockchain so it basically does the exact same thing that our other function does up here except it withdraws calls the withdrawal function so we'll we'll actually move the prevent default behavior up here so uh into this which it could be better than that but that's okay but uh withdrawal we just got to make sure the bank is there and we say await this state debank methods withdraw send from this state account it's basically the same thing we did here except we just changed to the withdrawal function right so let's save that refresh the page go withdraw do you want to use draw plus take interest click yes sign the transaction for the meta mask let's check our balance before we do it so 93 ether let's click confirm all right and boom there we go 94 we took our funds out so now you might be wondering how how do we know how do we see our token ballots well there's a couple of ways we can do that uh we can go into our our app here and then say um let's see here actually let's do this let's go to our apis let's look at the token find this address okay go to your meta mask click on assets all right there's all kinds of assets in here let's just click add token custom token contract address and it automatically detects the symbol of the decimals click next and there you go so you have some tokens it's a very very very small amount okay that's why you see the dots after here but you could also uh you know you could write a script in here you can go with the truffle console you could do like uh this i'm actually gonna leave it to you as a homework assignment okay so you see homework up here add new tab to check accrued interest so you can add a new tab i'm gonna give you some hints on how to do it um you can do console log like this uh let's just see the token contract say token methods balance of uh this dot state dot account call const token balance and then console log token balance all right so something's not working here's the token's not defined okay let's try this let's just put it in here all right all right there we go there's a token balance you can also convert it to whey so web3 utils from way convert to the ether value so see it's really really really small i'll leave that to use an exercise all right so uh that's a hint on how you can do it so i'm gonna take this out all right we don't need that necessarily but you can save it to the state here you can create a new tab down here and then show the interest accrued um but that would really be for interest that you've taken out but you could check the interest accrued from the bank you could calculate the time calculate the interest all that kind of stuff right um so that's that's one idea if you want to continue out this tutorial and look at uh how to like borrow money out of this bank and take out loans pay back loans handle collateral you can uh go to the d bank go to the different branch to go to borrow lend and you'll see some more functions inside of there let's see here you can look at the contracts there's actually borrow and lend functions so you can see borrow and then pay off okay so you can uh you can work on those if you want to there's tests for those there's a front end for that okay that's good homework for you to do as well so you can build this in your own define application so i hope you like this um congratulations on getting all the way through this tutorial um you know as always smash that like button down below subscribe this channel that really helps these videos out so more people can learn about blockchain if you're as fast as technology as i am you like this tutorial you want to take the next step uh learn how to become a real world blockchain developer step by step from start to finish so like a lot of this tutorial we kind of like filled in gaps and you know copied and pasted some things but if you want to actually like learn everything for real like concepts step by step create a project from scratch create a real world blockchain application that you can deploy you know out there in the wild use for your portfolio land a high paying job uh an advanced application like you would build at a job get your job ready uh blockchain is one of the highest paying fields in tech right now head on over to dappydiversity.com forward slash boot camp you get started today i can show you how to do all that stuff step by step from start to finish i've helped people with zero programming experience become real world blockchain developers in a matter of months all right so that's all i've got until next time thanks for watching dappy diversity
Info
Channel: Dapp University
Views: 125,334
Rating: 4.9677825 out of 5
Keywords: ethereum developer, ethereum solidity, dapp ethereum, ethereum app, ethereum development, ethereum dapps, ethereum application, ethereum tutorial, ethereum mist, decentralized applications, ethereum web3, dapp, ethereum contracts, solidity, programming ethereum, ethereum programming language, ethereum coding, ethereum contract, ethereum code, ethereum virtual machine, ico
Id: xWFba_9QYmc
Channel Id: undefined
Length: 119min 27sec (7167 seconds)
Published: Mon Feb 22 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.