Build Crypto Apps (Mine Ether, Write a Smart Contract in Solidity) with newline Founder, Nate Murray

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right i think it's time that we start working with ethereum directly one of the great things about a decentralized cryptocurrency is that we can connect directly to the network to submit transactions of course to make a transaction you have to have some currency to spend which we don't have yet also it can be a little daunting to try and learn ethereum while we're spending money on a production network when coding we generally develop and test on our own machine before we deploy to production in ethereum we're going to do the same thing we'll run a single ethereum node on our own machine to make sure we understand how it works later when we're confident in our code then we'll deploy it into production for now let's boot a single private ethereum node that way we can test whatever we need without worrying about making mistakes so let's download an ethereum client create some accounts and then send some money between them one of the first things to know about ethereum is that it is a protocol and that means that there are many possible clients that we could use think of it like this we send and receive email by using smtp and pop you can use any client that you want to i might use gmail you might use apple mail or hotmail but as long as all the clients know how to speak the protocol we can send and receive emails from each other the same thing goes for http http isn't owned by the http company where they can just change the protocol at will to be whatever they want instead http is a defined protocol that we all just agree on you can use whatever browser or code that you want to to communicate to any other service that uses http in the same way ethereum itself is a protocol in one sense ethereum is just whatever we all agree it to be and this idea of consensus defining the rules by which we all agree on something it comes up all the time in the blockchain space but for now the practical implication is that we have several different ethereum clients we can choose from we're going to be using go ethereum or geth for short it's the official go implementation of the ethereum protocol and again you could use any client you want and you could even implement your own but geth is the most popular so that's what we're going to use to download geth head on over to the download page and download the binary for your system when you unzip it you should have a binary named geth which you need to save somewhere so i'm going to make a new directory courses newline web3 and i'm going to make a bin directory and copy geth into it now that we have geth we need to do some initial configuration for our private node we are not joining the production ethereum network we're not going to download the history of everything that has happened in the ethereum network this far instead we're going to start our own private network we're going to start with a clean slate this clean slate means that we are creating our own blockchain i know that we haven't talked about what a blockchain is or how it works but we will for now just think of it like your test database and your production database you can't just merge your test database into your production database and expect it to work similarly changes to our local ethereum blockchain will have no effect on the production ethereum network we're going to configure our local test blockchain by using this configuration file genesis.json you can get a copy of this file from the lesson notes each of these configuration parameters will make sense in time but for now just copy this file and save it as genesis.json when we boot geth it's going to save its database in a folder on our disk this folder saves the state of our blockchain and more importantly the keys to our accounts we'll specify this folder every time we boot our geth node let's initialize our node now i'm going to type dot slash bin slash geth datadir equals datader init and pass thegenesis.json so i can ls this folder and look what's inside datator we can see that datador was created for us and it contains two folders geth and keystore the geth directory holds our blockchain data the keystore directory will hold our account keys once we have them geth contains a number of commands and options we can see the list by running dash help one of the first things we're going to need are accounts we can create an account like so slash bin slash geth datador equals datader account new we're going to need this password later so i'm just going to use the password abc123 obviously you need to use a strong password when you start handling real funds notice that when we created this account it output an address which is a long string of characters this is your receiving address and it's ok for it to be shared publicly we can now see that address in our list of accounts by calling accounts list now if we look at the data dir you can see that we have a new file in the key store we can cut that file out but that's not very clear to look at so i'm going to pipe it through a tool jq for readability here's our address and a variety of other parameters while the address can be publicly shared the rest of it needs to remain secret if someone had the information in this file they would be able to steal all the ethereum controlled by this account there's another important and interesting thing that you should know about accounts they're generated completely offline for comparison when you create an account with facebook you hit facebook servers and they'll create an account in their database which you can use and similarly when you create a traditional bank account you go to your bank you prove your identity and you ask them to create an account for you they create an account in their database and they let you use it ethereum accounts and bitcoin 2 are generated from an algorithm completely offline you're not hitting a remote server to generate this address in fact no one knows that this address even exists until it's part of a transaction in the network in one sense you're just picking an address at random out of a huge pool of possible addresses if you're familiar with ssh it's a lot like generating ssh keys you don't ask for permission from a central server to generate an ssh key you generate it from randomness and an algorithm on your computer so you can generate as many addresses as you need just make sure that you securely backup your private keys now that we have an account let's play with it so far we've been running geth commands from our shell but geth actually comes with a console of its own we can run this with the console command this console is a javascript console that means we can write functions perform calculations etc there are also a number of libraries pre-installed that we can use to interact with ethereum the first one is simply called eth we can view our list of accounts like this eth.accounts ether is the currency of ethereum if we want to find out how much ether we have we call eath.getbalance so here we call ethe.getbalance and then we paste in the address of our account we don't have any ether yet so it just says zero and this brings up an interesting question where does ether come from in the first place ether is created as a reward for mining blocks again we'll talk later about how mining works technically but loosely when we want to send ether to someone else we create a transaction and these transactions are grouped into blocks miners verify that these blocks are valid and then they are rewarded ether for doing this the key idea is this the ether is created out of thin air this is another example of consensus we all just agree that miners get to create ether to give themselves a reward for doing their job so here we can get ether by being a minor ourselves to do this we'll call minor dot start we pass the number of threads in this case it'll just be one now when you call this you might need to wait a few seconds maybe even a minute before you see successfully seal the new block but let it run for a bit just wait and then after a few blocks stop the miner you can find out the number of blocks we mined by calling ethe.block number every block we mined will have earned us a certain number of ether as a reward this reward will go to the account address we set up earlier and note that your mining destination address is sometimes called your ether base address let's find out how much ether we earned first let's look up our accounts and because this is javascript we can also do this now instead of copying and pasting our address we can use that in get balance well you can see this is a large number what we're actually seeing here is the number of way we earned ether has a bunch of different units with whey being the smallest whey is sort of like cents are to dollars except that one ether is 10 to the 18th way you can view the whole list of the units here but we're only going to be using whey and ether it would be nice if we could see this number in ether instead of way and thankfully we can use the from way method to do this the fromway method is in the web3 library so we type web3.fromway we put in our account address and then the unit we want which is ether much better now we can see that we earn 20 ether for mining the last few blocks now that we have some ether let's spend it if we spent some ether we need to have someone to send it to but right now we only have one account we could create a new account by using the geth command line like we did earlier but we can also create an account from here we do that by calling personal new account and then passing the password for that account i'm going to use the same password as last time abc123 now let's check our list of accounts great now let's check the balances between them so in this first account we have ether because that's the account we sent our mining rewards to but in the second account we don't have anything to send ether from one account to another we need to specify the from address the to address and the value of the transaction we'll do this with the send transaction method we'll type ethe.send transaction from ethe account 0 to ethercounts1 and the value will be 3 ether uh oh we got an error it says authentication needed why is this well it's because our from address is locked this is a security mechanism to prevent you from sending funds when you didn't intend to let's unlock our sending account and then try sending the funds again we'll call personal dot unlock account pass our address and then our password now we can try sending our transaction again i'm hitting my up arrow here to search my history and find the code earlier that we used to send a transaction great this says submitted transaction and it returned a hash this hash is the identifier of our transaction let's look at it more closely we can do that by calling eth.gettransaction and then passing the hash take a look at the to and the from fields you'll notice that these match our account addresses also the value field is the value we were sending denominated in way since we submitted a transaction sending three ether from one account to another our balances should have changed right well let's check we'll call east.getbalance on account 0 and ethe.getbalance on accounts1 it looks the same as before why is that well it's because even though we submitted a transaction they haven't been included in a block that was processed by the miners take a look at the information returned by get transaction again notice that the block number says null and the block hash is just zero this transaction hasn't been included in any block so our account balances haven't changed in order to process this transaction we need our miners to include it in a block we can do that by starting our minor again here we'll call minor start and wait a few seconds wait for a few blocks to mine and then call miner.stop notice in our minor debug log that the transactions equals one this is saying that this particular block has one transaction and notice that the rest of the transaction numbers are zero and that's because we haven't been submitting any other transactions but the miner will still mine the empty blocks just to get the reward now let's try checking our balances again this time we'll get it denominated in ether well with account zero it's hard to tell if that worked because this is our ether base account so it's earned rewards while we were mining let's check the destination address great it has three ether in that account so our transaction worked let's take a look at our transaction hash again notice that we now have a block number as well as a block hash we can also take a closer look at the block this transaction was included in by using ethe.get block there's a lot of data in here that will make more sense as we get further along but take a look at the array of transactions and notice that it contains our transactions hash each block stores a reference to its parent block and we could look up the parent block by using the parent hash and if we looked at parent hash we would see a list of transactions there and then we could look at its parent and so on all the way back to the original genesis block this idea of a block being parented by another block is the chain part of a blockchain every transaction that has ever happened in ethereum can be found this way while it's exciting to send value from one account to another through a decentralized network ethereum can do so much more what makes ethereum so special is that we can write programs that will handle this value for us and that's we're going to take a look at next so you might be asking what is a smart contract and the answer is it's like a regular contract but defined by code but let's take a step back what is a contract anyway normally when we think of contracts we think of a piece of paper where you sign on the dotted line but the idea of a contract is a lot more general than that fundamentally a contract is an agreement between two parties and we agree on and participate in contracts all the time maybe it's an agreement to buy a car and pay the lender every month or maybe we'll make an agreement with our library that we can borrow a book and we'll return it on time or else we'll pay a fee of 10 cents per day maybe it's an agreement to pay monthly for fire insurance and if our house burns down the insurance company agrees to pay us a lump sum or maybe we have an implicit social contract with our friends that when we go to dinner we'll all split the bill evenly another place where contracts are used extensively is financial products stocks are a good example of this owning shares in a business gives you certain rights as a shareholder you might receive a portion of the business's profits through dividends have access to their financials or hold certain voting rights etc these rights are defined by a company's shareholders agreement which itself is shaped by the governing laws in a particular jurisdiction and even then enforcement of any particular clause depends on the lawyers and judges and lawmakers involved the idea with a smart contract is that we're totally defining the rules of our agreement in code we should look at some examples nick sabo the inventor of bitgold developed the concept of smart contracts in his essay titled the idea of smart contracts he gives two examples one the idea of a vending machine and two a car loan with a twist let's start with a vending machine you can think of a vending machine as a mechanical contract between a thirsty buyer and a beverage manufacturer the buyer puts in a certain amount of money and the machine dispenses a drink and change if necessary there's even a rollback mechanism if the buyer requests a refund or the drink can't be delivered the vending machine acts as an escrow between the buyer and the seller and although what's at stake is small there is a moment where the vending machine controls both the drink and the funds the buyer and seller both agree to this arrangement because there's an understanding that the machine will act according to its programming and treat both sides fairly of course one weakness of the vending machine metaphor is that the vending machine is controlled by the drink manufacturer which as a buyer means that there is a chance that the machine will cheat you by taking your money and not dispensing a drink in smart contracts however this asymmetry of trust can be removed that is in the ideal smart contract there's no scenario where one party can defraud the other you can't inspect the code of your vending machine but you can inspect the code or at least the proofs of your smart contracts another example sabo gives is the idea of a car loan but in this case the keys to the car are cryptographic keys and these keys are initially controlled by the smart contract the idea is that the terms of the loan are encoded in the smart contract and the contract gives control of the car to whoever rightly owns it for instance the buyer needs to make payments each month and if he pays on time he keeps control of the car however if the buyer were to fall far behind on his payments the smart contract would automatically return control the keys to the lender on the other hand if the buyer keeps his payment schedule when the loan balance is paid off the smart contract will return control of the car to him irrevocably that is the smart contract would permanently cryptographically give control of the keys to the car to the buyer to generalize the key idea here is that any property which can be represented digitally can be managed in code with smart contracts another way to view smart contracts is as a board game when you and i agree to play chess we're agreeing to a specific set of rules such as the board will have 64 spaces or a pawn can move two spaces on his first turn we can model chess in a smart contract and then sit down and play the game any move made within this game must abide by the rules and conversely any move that's within the defined rules is permissible when we agree to abide by a contracting code whatever is logically valid within that code that's what we'll hold to no matter what however a problem with this approach is that many contracts are a lot more open-ended than the rules of chess and it can be very difficult to define every possible outcome traditional contract law is dynamic and has been refined through thousands of years and this means it can remain robust in the face of complex and ambiguous situations niksab was fond of saying that a contract is a program that runs on the brains of lawyers and the upside is that these brains are very sophisticated but the downside is that these human executions are non-deterministic and this idea of contracts as a program is really at the heart of what we're trying to do when we talk about smart contracts it's really just code in bitcoin a smart contract might be something as simple as a list of operations that check for a required number of signatures in ethereum with solidity a smart contract is essentially an instance of an object our vending machine for example could be a smart contract from a programmer's perspective this vending machine smart contract code is an object it holds its own state variables such as the current inventory of the sodas and it also has methods which can read and write that state it's early days for smart contracts and the scope of what contracts can be written in code remains to be seen but we now have the tools to start experimenting in code on production decentralized systems let's start writing a smart contract in code let's write and deploy our first ethereum smart contract the process looks like this we'll write our contract in a high-level language next we'll compile it then we'll deploy it to the network and after it's been deployed we can interact with it in order to write contracts on ethereum it's really important to understand the context in which they are run the first thing that we'll start with is the ethereum virtual machine or the evm for short the evm is a low-level assembly-like programming environment it can perform arbitrary computations put data in storage read that data out etc when we write code for ethereum we generally don't write the bytecode directly instead we use a higher level language that compiles down to these basic operations the second thing to know is that this code is run by every node on the network that is every minor node on the ethereum network will run our smart contracts code but keep in mind they're going to run the evm byte code and not our solidity code directly because our code is run by every node on the network this has a lot of implications around data privacy and cost we'll talk about those later the third thing to keep in mind is that our contracts will only run in response to a transaction that is they're not running constantly in the background instead our contracts will only run and make changes if a transaction is sent to the network that wakes them up there's a lot to unpack here so let's just start by looking at some code i'm going to be working out of our new line web3 directory i'm going to make a contracts directory and i'm going to create the file contracts counter.sol you can find this in the lesson notes this is a solidity contract it keeps track of account variable which we can increment now it's not the most exciting code but we have a lot of new ideas to cover around ethereum itself and we'll expand into more interesting contracts once we grasp how everything fits together we open by stating pragma solidity and then a version number this pragma is an instruction to the compiler as to what version of solidity we're using the version number is semantic versioning much like javascript's npm modules the version number is important because remember we're not running solidity code on the evm we're running byte code the solidity compiler compiles this contract down to evm bytecode the solidity compiler like the rest of the system is under development and so two different versions of the compiler could reasonably emit two different versions of the bytecode this might not be that important when we're compiling code for a regular computer but when our code is controlling thousands or sometimes millions of dollars little changes in the compiler can make a big difference so we fix our solidity version in our smart contract so that way we know we can get a consistent output from our code down the line next we define our contract with the keyword contract as well as the name of the contract which in this case is counter a quick scan of this code might remind you of javascript and that's deliberate in that solidity was designed to be approachable for web developers that said don't let the superficial similarities fool you solidity is just similar enough to javascript to be dangerous there are some unintuitive aspects of solidity that you really have to be careful of we'll cover them as we go along but one similarity is that you can think of this contract as a class the counter contract is like an object class on the next line we have uint count solidity is a statically typed language and this count variable is an unsigned integer uint is an alias for uint256 which means it can hold a positive integer up to two to the 256th minus one it's a very large number the value of this counter will be stored on the ethereum blockchain this means that the value of count will be stored on every full node on the ethereum network this service is not provided for free if you want a value to be stored permanently by thousands of nodes you're going to have to pay for this understanding and calculating these costs is also something we'll talk about later for now know that this count variable is like an instance variable we can read from it and write to it as you see in the functions below the first function that we have is the constructor the constructor is a function with the same name as the class as happens in other languages the constructor function is called when we create an instance of the class one question you might be asking is how do we create an instance of this class anyway the answer is after we compile the code we'll submit a transaction to the network that creates an instance of this class this instance will be given its own address and it can control both data and funds on the ethereum network that is this contract can receive payments of its own it can verify conditions and it can send funds out well this counter contract can't do any of that because we haven't implemented any of that functionality but in other contracts we will just know that when we upload this code to the network an instance will be created and given its own permanent immutable address speaking of immutability another thing that you should know is that once we've created an instance of a contract its code is immutable and cannot be changed you can't upload a bug fix and you can't make any tweaks once it's been created it's written in stone there are strategies for mitigating this limitation but really immutability is a feature not a bug but you'd better make sure that you do extensive testing before you start handling real funds back to our code in this constructor we're going to set count equal to 1 when the contract is created the next function is increment the increment function will read the existing count from storage add 1 and then store the new value in the count instance variable the get function returns the value of count in the get function declaration we're stating that it is a constant function which means it doesn't modify any of the state and it returns a uint an unsigned integer remember every node on the network stores a copy of the storage for every contract and given that we have our own node this means that we can read any of the data for free instantly that is the get function can be executed completely on our local machine without going to the network we already have the value of count on our disk the increment function however is different because it changes state the validity of that change must be confirmed by the whole network so to make a call to increment we must submit a transaction that calls increment that transaction will hopefully be picked up by a minor to be included in a block when that happens the transaction will be run which will increment the count value we've looked close enough at this code let's compile it deploy it and then interact with it on the blockchain to compile our solidity smart contract we need a compiler the main solidity compiler is sulk it's written in c plus plus and it's a good idea to use a formal release build for your production smart contracts that said getting the c plus version of sulk installed can sometimes be a pain my recommendation is that you install sulk before you deploy your first smart contracts to the production network but for now we can just use the javascript version sulk js to install sulk js we'll run npm install g sulk remember this installs sulk js not the c plus version sulk js's core code is generated using mscriptin which converts the c plus version of sulk into javascript this means it'll work just fine it's a little slow but know that the command line options are different there are other ide like tools we can use to compile our contracts and we'll look at those but since we're just getting started i think it's clearest to just compile them by hand ourselves on the command line we can compile our contract by typing this sulk js dash bin counter dot soul let's take a look at the output well that's not exactly enlightening but this is a hex encoded version of the bytecode of our script there are other ways of viewing the opcodes that are clearer but we don't need them right now while we're here another thing we need to generate is the abi which stands for application binary interface the abi defines the interface to the functions on our contract the reason we need this is because the encoding of our program is not self-describing that is you can't easily tell from the byte code how each function should be called or what it returns the abi tells us how we can use a contract and actually we can just generate both of them at the same time like this soul js dash dash bin dash dash abi counter dot soul let's take a look at the abi and that's a bit compact so i'm going to pipe it through jq for indentation and color reading this api we see that we have an array with one entry for each function here we have get which has outputs of a uint256 our increment function and our constructor we'll use this abi when we call our contract as an object let's flip back to geth and deploy this contract first start geth like we did in the earlier video slash bin slash geth pass the day editor and call the console now we're in a javascript console so we can declare variables functions etc as a reminder in an earlier video we created some accounts and mined some eth we'll need both the accounts and the eth now so if you don't have those go back to that earlier video the first thing that we're going to do is assign our contract hex code to a variable it will help if you have two tabs open i have a get console in one and a shell in the other so i'm going to cat counter soul counter dot bin and here you can either select to copy and paste the code or because i'm on a mac i'm going to use pb copy and flip back over to our get console we'll create a variable var counter code equals and then paste in our code into a string let's take a look now to create an instance of this contract on the ethereum network we need to send a transaction also to send a transaction it will cost some eth so we need to unlock our account first now it's time to send our transaction we'll type ethe.send transaction from ethercount0 and for data we're going to pass our contract code but hex strings must be prefixed with 0x so we're going to prepend our counter code with the string 0x for the third parameter we're going to set gas we haven't talked about gas yet so just put 1 million here the second argument to send transaction is a callback function with the first argument being an error if there was any and the second argument being the transaction we'll just console log both of those out notice in the output that we have contract equals a hash this hash is the address of our contract this is a permanent address so make sure you save this value we're going to need it here we'll set it as the variable contract adder one way we can check on our contract is using eth.getcode here it says 0x which means something isn't right and the problem is although we've submitted a transaction we haven't mined it yet so let's mine it now this might take a second all right we'll stop the miner let's check east.getcode again great if you call ethe.getcode and it says 0x then something went wrong a value of 0x means it didn't work but here i can see my contract code so we're good we've deployed our contract our code's permanent address is now stored at the value of contract adder you can think of that address as your contract's personal domain name it isn't pretty but it's uniquely yours now that we have a contract on the blockchain we can start using it now that we have a contract on the blockchain we can start using it to do this we're going to make a javascript object that acts as a proxy to our smart contract remember that our contract code doesn't describe its own api so we need to use our abi file the process to get a handle of our contract instance feels a little odd coming from normal javascript it looks like this first we'll parse our api into a json data structure second we'll create a contract class using that abi and third we'll instantiate that class using our address it's probably easier just to show you in code first we're going to copy our api definition file we compiled earlier next we'll go back to geth and parse the string using json.parse take a look at the api you can see that it's an object next we're going to create essentially a javascript class for our contract var counter equals eth.contract passing the abi and finally we need to tell our code where to find this particular instance of the counter contract on the blockchain so to create an instance we type var counter lowercase equals counter at the contract address and looking at counter we can see we have our address and our functions get an increment now we have a handle to our contract instance in javascript and this means we can now interact with our contracts code like a javascript object sort of remember that all reads can be performed locally for free as long as they don't change any state let's try to use our read function get do you remember what the return value should be great it's one we just read our first value from our first contract on the blockchain even though we just read a single number it's worth noting that right now we have the pieces that we need to build javascript applications that read any data from the ethereum blockchain we'll talk about how to connect this to the browser using web3 in a bit but by making this connection between solidity and javascript we're now in somewhat familiar territory for a minute anyway it gets more complicated when we want to update the state let's call our increment function now counter dot increment hmm error invalid address well it might not be clear what that message means but it's clear that what we were trying didn't work and the primary reason is that you can't just call functions that change smart contract values locally you have to submit a transaction that the rest of the network agrees is valid so how do we do this here's another area where solidity javascript api is not that intuitive to send a transaction on a contract method we call send transaction on that function it looks like this and you might need to unlock your account again we'll call counter dot increment but then on that increment function we'll call dot send transaction from eth account 0. so here we're calling the send transaction function on the increment function this api of calling functions on functions to change their behavior is something we'll see a few times when using javascript and solidity our send transaction call returned the hash of our transaction and notice that the recipient is our contract address and what will happen if we call counter.get right now you probably already know that we need to mine another block first so let's do that minor.start minor.stop and now let's call counter.get 2. it works we wrote our first change to our contract state on the blockchain now if it didn't work or you want to dig in you can use debug.trace transaction and pass the address of the mind transaction you can also call eath.gettransaction or ethe.gettransactionreceipt this might output quite a few logs but you can just check for any errors for now of course this is a simple contract with a simple application the next thing we're going to do is bring the interface to this contract into our web browser in the last video we built a simple counter contract in solidity we deployed it to the blockchain and called methods on it to update the state there's a lot more we have to learn about solidity and smart contract programming but i want to show how to make a connection all the way to our web browser that is i want to make a user interface for this contract i think it's helpful to see how an ethereum based app is done end to end and then we'll go back and learn how to make more sophisticated apps to build a ui for our ethereum app the key idea is this our ethereum node has a json api and will connect our browser to that api so the core architecture is that we have an html file which loads javascript and this javascript instead of calling out to say a normal centralized server we'll call to our personally controlled ethereum node instead now just to be clear our web app is all just javascript so you can call out to other servers if you want to just like you can call lots of apis in a normal javascript app in fact this really is just a normal javascript app the only difference is that we're connecting to an ethereum node for the api the library that we use to connect our javascript code to the ethereum json api is called web3 to build our ui we need to start with a basic html css javascript boilerplate i'm not going to teach web development here we have other books and courses if you want to learn that instead i'm going to assume that you know how to write javascript install npm modules and use promises in a real app i'd probably use a web framework like angular or react but i want to focus on what's new here and so vanilla javascript will be fine i also want to warn you that in this tutorial we're going to take some javascript shortcuts like creating global variables on window and directly manipulating the dom we'll cover how to properly structure larger web3 apps later but for now let's just get it working everyone has their own favorite boilerplate and i'm going to use nwb here because it's an easy way to get a nice vanilla javascript app up and running so we can install it first by doing npm install dash gnwb nwb new web app hello counter then i'll cd into hello counter do an npm install and then i'm going to npm install web3 we can start our server using npm start and then open localhost 3000 in our browser a great thing about this configuration is that it will automatically reload our app whenever we change these files we can open up the code and see that the basic app we're given has an index.html and an index.js the first thing we'll do is require web3 and the way the web3 api works is we're going to call new on this object so we'll declare a lowercase web3 equals new web3 and so we can expose variables to our console by setting them on window so let's make web3 accessible to our browser console by typing window.web3 equals web3 the next thing to do is to set the web3 provider in this case we're just going to use the http provider but you could also use websockets if you wanted to get real-time updates and notice that we're setting the address to local host port 8545 this address is the address of our gethrpc server we haven't booted geth in an rpc mode yet so let's do that now flip back over to our guest shell kill it using ctrl c and let's start with new options so i'll use bin gas data i'm going to set the options no discover rpc rpc api and then a list of rpc apis that we want to use db personal ethernet web 3. there's several these are the ones we'll use for now and then there's a few other options rbc cores domain you don't need to worry about that for now rpc address i'll put localhost rbc port 8545 and console you can find this full command in the lesson notes feel free to adjust the rbc address or rpc port if you need to for example you might try using 0.0.0.0 for the rpc address if localhost doesn't work on your machine you might also need to change the rbc port but essentially what this will do is launch geth in console in our shell but it's also opening up an rpc server in the background which our web browser can connect to now we should be connected to our geth node we can try it out by typing web3 web3.eth web3.ethe.personal and web3.ethe.personal getaccounts now notice here when we call the get accounts function it returns a promise so if we want to actually get the result of our accounts we'll type web3.ef.personal.getaccounts and we'll call dot then and then we'll log out the results of that promise if this didn't work for you check out the network pane in your browser but at this point we should have web3 connecting from our browser to our gethrpc server node now what we want to do is write a button on our page that will allow us to check the balances of our accounts we'll do that by writing app.interhtml equals and then we'll put an h2 tag show some text and then a button where on click we're going to call the check balance function now let's write a function that will check our account balances again it's not a good practice to put functions on window but we're just testing web3 here so we'll type window.check balance equals function and first we'll call web3.eth.personal.getaccounts.then we'll log out those accounts and then we'll get the balance of the first address by typing web3.eth.getbalance account 0. that also returns a promise so we'll call then and log out the balance let's flip back over to our browser try it out great there you can see that we checked the balances of our ethereum accounts in our browser now that we know that we have a connection between our browser and our ethereum node let's make a connection to our contract remember that in order to create a javascript representation of our contract we need to load the abi let's copy the abi that we compiled earlier into this project only i'm going to rename it tab.json at the end so i'm going to rename it to counter soul counter abi dot json in the code we can use a javascript require to load this.json file this is possible because of the nwb config if you're building using another method you can always just copy and paste the api here in the code i'm going to type let counter abi equal require then i'm going to require the file we can log it out to make sure it loaded see it in the log great also remember that our particular instance of the counter contract lives at a specific address on the blockchain i hope you save the contract address from last time so i'll copy that address and i'm going to define a variable let contract address equal and then paste the hash in and remember this is an important point when you deploy your website it lives on a specific domain name when you deploy your contracts they'll live at a specific address so you'll have these addresses hard coded or at least in a config file committed into your code so now that we have our api and our contract address we can create a new contract object we do that by saying var counter contract equals new web3.eth contract we pass the two arguments counter and contract address let's assign this to window so that we can inspect it in our console so looking at counter contract notice that the functions that we want to call are in methods on this object in order to get the value of our counter we have countercontract.methods.get but notice here there are two important functions on get send and call there's a difference between them we use call when we want to call a function locally and send when we want to send a transaction to the network getting the value of the counter can be done locally so let's use dot call however calling out to our ethereum node is async so dot call will return a promise so we call counter contract dot methods dot get dot call dot then and we take the count and we'll log out the count great we got our count now let's add a function for this and show the value in our view first thing we'll do is we'll add a div and placeholder to show our counter value and we'll update our button to call check counter let's define our check counter function first we'll type window.check counter equals function then on the contract we'll call counter contract.methods.get.call.then which will be given account then we find the counter value element by id and we set the inner text equal to the count flip back to our browser and let's try it out great it works the next thing that we need to do is send a transaction from our browser to mutate that counter value now let's mutate our contract state by incrementing the counter to do this we'll need to send a transaction to the blockchain we can check this out in our console the counter contract object has functions that help us build this transaction it looks like this counter contract dot methods dot increment we'll call dot send on this dot send means send a transaction so recall that to send a transaction we need to specify the sending account as well as the amount of gas that we're willing to spend to run this transaction let's grab our first account address and try it we'll set our account to a variable and then call counter contract dot methods dot increment dot send passing from our account gas we'll just put 1 million dodge then and capture the error and the response and log it out the promise that returns isn't resolving let's check our logs to see if we can figure out why in the network tab we can see the response that says authentication needed password or unlock we forgot to unlock our account so let's do that first we'll type web3.eth.personal.unlock account pass our account address and then the password abc123 looks good now let's try resending our increment transaction looking at the network tab it looks like it went through let's mine this transaction back in geth we'll do miner.start we've got our transaction and miner.stop let's check our counter again it works all right let's add a button which will increment this counter for us we'll set our from account so we're going to add a new button where on click calls increment counter and let's define our increment counter function we'll call window dot increment counter equals function counter dot methods dot increment dot send from from account gas 1 million and let's flip back over to our browser and press the increment counter button and we need to mine the transaction now i don't know about you but i'm getting tired of starting and stopping the miner manually so let's just leave the miner running now let's increment the counter and if it doesn't work you might need to unlock your account again let's wait a couple seconds for it to be mined then check the counter value it works let's try that again wait for the miner click it again it works fantastic so there's a really basic web3 ethereum tutorial i think the most obvious improvement i'd like to make here is to have the counter value automatically update in the view once the transaction has been mined we'd use websockets to push the new information from the rpc server to the browser and then we could update this value automatically without the user having to check manually but using websockets is something we'll cover in a later video in fact we have a lot to cover in other videos this tutorial shows you the key connection and how to build d apps but there is so so much more to cover for example i want to talk about the specifics of writing real world solidity contracts taking performance and security into account i want to talk about building apps where our users can trade collectibles or vote on resolutions and make provably fair agreements i want to go beyond ethereum and talk about distributed storage with ipfs and talk about high throughput transactions with side chains and state channels i want to talk about how to accept bitcoin payments on your website without any bank or credit card intermediary and of course we're going to talk about how to build your own cryptocurrency we'll discuss what it means to create your own tokens and how to integrate them into your own apps for now though let's celebrate our success connecting our ethereum network to a browser app we're entering a brand new world and we've got a lot to build you
Info
Channel: newline
Views: 879
Rating: undefined out of 5
Keywords:
Id: u_FD_9FTg8w
Channel Id: undefined
Length: 52min 23sec (3143 seconds)
Published: Mon Dec 13 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.