New Ethereum talks, every Monday. The week's conference uploads by event, in your inbox.

Loading player…

Solidity 101 with Michał Sieczkowski

ETH WarsawThu, Oct 7, 2021, 12:00 AM

Workshops for blockhain beginner devs. Learn how to build on Ethereum! BOUNTY LINKS: Hermez Network: https://gitcoin.co/issue/hermeznetwork/0xhack/1/100025692 https://gitcoin.co/issue/hermeznetwork/0xhack/2/100025700 https://gitcoin.co/issue/hermeznetwork/0xhack/3/100025693 https://gitcoin.co/issue/hermeznetwork/0xhack/4/100025694 DevCon: https://gitcoin.co/issue/EthWorks/hackathons/1/100025722 Golem: https://gitcoin.co/issue/golemfactory/hackathons/18/100025686 Polygon: https://gitcoin.co/issue/maticnetwork/matic-bounties/21/100025715 Status: https://gitcoin.co/issue/status-im/0xHack/3/100025685 https://gitcoin.co/issue/status-im/0xHack/2/100025680 https://gitcoin.co/issue/status-im/0xHack/2/100025680 https://gitcoin.co/issue/status-im/0xHack/1/100025679 Ethworks: https://gitcoin.co/issue/EthWorks/useDApp/181/100025575 https://gitcoin.co/issue/EthWorks/useDApp/180/100025574 https://gitcoin.co/issue/EthWorks/useDApp/179/100025573 https://gitcoin.co/issue/EthWorks/useDApp/178/100025570 https://gitcoin.co/issue/EthWorks/useDApp/176/100025566 Moonbeam: https://gitcoin.co/issue/PureStake/hackathon-0x-moonbeam/2/100025702 https://gitcoin.co/issue/PureStake/hackathon-0x-moonbeam/1/100025701 Ramp: https://gitcoin.co/issue/RampNetwork/0xHack/1/100025724 https://gitcoin.co/issue/RampNetwork/0xHack/2/100025725 https://gitcoin.co/issue/RampNetwork/0xHack/3/100025726 Chainlink: https://gitcoin.co/issue/smartcontractkit/chainlink/4375/100025683

Transcript

hello everyone uh first things first let me introduce myself maybe someone new joint my name is mihao i'm a software developer at ifworks and at this presentation i will show you the basics of solidity and because uh uh there are not so many of us i think we will do it in an interactive way so uh first i'll show you a couple of slides uh and uh code snippets after which uh i'll invite you to join join me and we'll write some code don't worry you don't need any special software uh your browser which you're using right now is enough and we'll see how it goes if you have any questions you can raise your hand so that i can notice it also you can use chats or or preferably ask questions using the questions tab and i'll be answering them along the way so feel free to ask me anything at any point in time so yeah without further ado let's start uh i'll start with introducing you to the data types of that are available in solidity so obviously you have booleans nothing new you have integers and you have both signed and unsigned integers as you can see there are multiple of them with different precisions so int 8 is a an 8 bit integer up to in 256 which is 266 bit integer which is 32 bytes and and you get all of the integers in between going uh in a eight by eight here you have the same for unsight integers uh then if you use uh just int or just uh this is an alias for the largest type why is it alias for the largest type because this is the size of the word in a ethereum virtual machine that is used there and and this is this is what we use for storing uh uh amounts of uh of crypto for instance that uh that you own this is a really big big number uh it's so big that you you'll probably never overflow it when simply adding numbers so this is one nice feature that you have a lot of precision it's also this big uh because you don't have any floats in in in solidity uh so there is no floating point and arithmetic just not to not to uh make uh uh so that you are not tempted to use floats for representing money as we all know uh floats uh have problems with rounding in errors and basically cannot accurately represent base 10 multiples that we use for money that's why for money calculations we prefer to use integers and we have such big integers so that we can safely represent any uh any precision that we that we use for a digital currency you also have an address type it represents a 2820 byte value it's a like an array of 20 bytes that represent the ethereum address i think my presentation is gone let me let me check it out okay i think it's back uh if someone doesn't see it please let me know on chat because that's that's something different something weird okay going back to the presentation um every address has a uh has a a couple of fields i have a balance which which lets you query like that the current balance of this uh of this address of this account uh you have uh code which if the address is a smart is the address to the smart contract you you can get its byte code this way you have a code hash which as the name says is a hash of the code and also a method to call some method on on on this on this address and there are many other i didn't mention them all but just to give you an idea there's also something called address payable so this is the same as address but also you have new methods that let you transfer value to those to those addresses so this is simply so that it's clear in code which variables can be used to send money to you have arrays and those can be fixed size or dynamically sized just like in any other language declaration is very familiar uh so you you specified that the type and in square brackets you specified the uh the number of elements for fixed size array uh there are also like predefined keywords for byte arrays from 1 up to 32 so you don't have to write byte for you to if in square brackets and also you have dynamically sized arrays those are specified without the the number of elements uh you have a keyword bytes uh which is a byte array it's different than the writing byte with great square brackets in a way that in this case uh the the the bytes are tightly tightly packed so it it's so it uses less storage uh string is a byte array that is utf-8 encoded and and doesn't have some of the methods that i will show on the next slide allocating a dynamically sized array looks like this you specify the type of the array memory keyword which i'll mention later the name of the variable uh new you repeat the the type and you give the length uh in in brackets arrays have members thick size arrays only come with a length and dynamically sized arrays come with some of some of some methods that let you add or delete elements from it uh so push adds a zero initialized element uh what does it mean it means that you cannot add a nil or a null or an undefined value because they don't exist in in uh solidity uh if you want to add something to an array you always add uh at least a zero initialized value uh so what is a zero initialized value for integer it's simply zero for boolean it's false for uh string is most probably empty string and so on uh you can push an empty value you can a zero value you can push an existing value you can also pop from the end of an array you get inside it you also get a mapping type which is sort of like dictionary from python or or a map from typescript it holds key value pairs it's declared this way so you keyword mapping and then brackets key type towards value type and the name of the variable you assign to it just as you would assign to an array in the same way what's special for uh solidity arrays uh a solidity mapping story is that they are virtually initialized so again every possible key exists and uh if you query for a key that was never set you'll get a zero value of the value type so this is uh again like an example that you don't have you you never get an anneal in solidity uh you always get some value in this case zero value uh another interesting uh feature or a lack of feature is that mappings are not non-integrable if you want to iterate over a mapping you need to basically implement it yourself and someone may ask why you don't have such a like elementor feature in built into the language i think it's to make you aware of the stuff that that you are doing of the loops that you are introducing into your code and you'll see that in many places solidity is sort of low level in this sense that it doesn't provide you nice abstractions that we are all used to from other languages uh solidity lets you define your all your own uh types uh in in form of structs so as a struct can can is like a a set of of variables which can be of different type those can be other structs and mappings for instance and so so so you can freely create your own types and use them in code we also have enums which are declared just like in any other language and now let's talk a bit about something again specific to solidity in solidity you have three data locations you get storage which you should think of as a hard disk drive it's a persistent storage that outlets the invocation of a function it's simply stored on blockchain and the next transaction can read from that storage then you have memory which is sort of like ram in your computer it's volatile uh it's limited its lifetime is limited to the invocation of a of a function therefore it's uh it's relatively cheap to write because it's not starts permanently on blockchain uh it's only allocated when the transaction is executed on on the miner node and it's gone after that you also have something called call data and the code data is a special place where arguments of methods that you invoke are stored if you uh if you attended my previous presentation uh you remember that i talked about a field of transaction which is called init or data and in case of invoking a method of a smart contract this field was called data well call data is simply this this field so every transaction has some input data in which we in which we encode the method that we want to invoke and its arguments and then in solidity you get arguments of a function and you don't need to copy them to memory you can directly read from dust from this call data which which is used to reduce the number of operations that you do you don't copy the memory your your transaction spends less gas uh because it's uh like a field of transaction it's immutable you cannot change this because that's what that's what that's what comes from transaction uh and and again it's not accessible after the invocation of a function uh ends because uh uh because it's an argument a function simply but what's interesting is that call data is actually stolen blockchain how because we start in information about every transaction that happens on blockchain that's why we also story about information about uh all the arguments of of methods that were invoked and uh this has uh this is used in in in many applications and it's also used in layer two protocols uh which i won't dive into right now but this location is very important there okay i think it's enough of slides let's jump into some code and and see some examples and not just not just me showing you theory okay i'll try to make this window more so you don't have black borders uh all right uh this is uh i just created with some uh with solidity syntax you have comments in solidity i'll copy a link to it to the to the chat so you can look at it yourself if you don't want to follow follow me follow what i'm presenting here i'll make it a bit bigger so that you can all can see okay so um you'll see that uh every every solidity file will start with a version of uh compiler that is used and this this declaration starts with words pragma then solidity and you specify the version in semver so the same way you specify versions in javascript in npm packet json files [Music] later on you'll learn that it's important to to uh hard code the exact version for uh uh for audit purposes so assume that you want to send your your smart contract to an auditor and uh you ask them to look at your code they will tell you hey you should uh you should actually hard code the version because that's how we can make sure that uh what we are of the auditing is what is actually executed one exception to this rule is that uh if you're creating a library you shouldn't actually hardcode the compiler version because then other contracts that use a slightly different version of compiler will not be compatible in such cases you should create like a range that is as broad as possible okay let's uh let's now go into the the pieces of solidity uh this is not uh like like a proper file it wouldn't compile but it shows you the syntax uh so uh declaring a variable and assigning it is done just like in in any other language uh like javascript or or or java uh if you declare a variable but not don't set a a value immediately uh it is zero initialized so again there is no nil there is no undefined uh you can declare constants by putting a constant keyword compiler will replace those variables with actual values in code if you declare a variable that is public the compiler will automatically create a getter function for you uh this is uh this is uh convenient so you don't need to write those getters yourself uh note that no setter will be automatically created if you actually want to give other contracts ability ability to modify your vario your state variables you need to create setter yourself uh i i just noticed a question is there a recommended solidity version last released or n minus one that's a good question i would say that as with every piece of software uh it is validated after some people use it uh therefore i would i wouldn't recommend using the latest version uh unless it solves some critical issue that was in the previous version then yeah you should probably use the latest one so a rule of thumb would be to use an n minus one but you need to be careful um going back if you don't specify public a variable is internal by default which means it will only be available in this contract and those that derive from it so basically the same smart contract it doesn't actually mean that the variable is not readable by uh actors watching the blockchain you need to be aware that every data that we write to blockchain is public nothing in blockchain is private because we wouldn't be able to to run those transactions on thousands of nodes if you want to achieve privacy you need to use other other methods going forward uh as you can see this way you can declare a variable of own that is of type address payable uh it will be a zero address actually because we did not assign anything uh on a address payable variable you have transfer method that you can that lets you send some money uh in case the transfer fails uh this method reverts why would the transfer failed because if you transfer to another smart contract it can have it can have a callback method that uh that can decline the transfer for instance and then you then then trans then this this method would revert you also have send method which doesn't revert but and it lets you handle the the the failure in an if statement just remember to do it if you don't if you don't want to introduce it back in your code you can create the balance as i showed on the slide you have examples of those fixed size byte arrays here bytes 2 and bytes 32. also a dynamically sized bytes array string everything i think is pretty straightforward here is an example of a declaration of a fixed size array of five fixed size arrays of bytes yeah so we have five times 32 bytes this is a dynamically sized array and on a dynamically sized array we can uh to the social area we can push elements uh we have a length property and what's interesting you can assign the length property assignments will either cut or extend the the array if you cut you'll simply get a shorter array if you extend the new elements will be set to zero so again you don't have undefined snills you uh and you don't have some garbage left over from some data location memory just as you would have in c plus plus or the other low level language uh in in solidity if you uh expand the length of an array you get uh zero new zero elements at the end you can create multi-dimensional arrays here is an example of a mapping then assignments to a mapping looks this way so charles has a balance of one if you query for a balance of a non-existent key you'll get a zero as i mentioned all keys are virtually initialized you get a zero value of a given type and because we specify the public keyword here compiler created a getter for us which looks this way it takes an argument uh which is the key and returns uh returns a a value taken from this mapping then a different smart contract could could query this this method this way simply invoking balances here you can nest mappings so a mapping can be you can have them have a mapping from address to another mapping it's totally possible there's something like delete keyword which lets you delete an element from mapping and by deleting i mean setting it to zero again if you delete the whole mapping it will set all of its elements to zero um uh let's not let's not talk about structs structs need to be first declared after which they can be created in in two ways first is a sort of json-like way where you specify keys and values you can change the order as you wish the second way looks more like a constructor where the order needs to be the same as as it was declared you can assign to a field in a really simple way uh if you delete the contents of a mapping it will set all of its elements to to zero except for mappings [Music] in this case it will not be zeroed i'm not sure about that but yeah now you can declare enums and then uh use them this way enums are easily converted to to numbers uh and also uh this way you can cast other types to other types so so for instance you can cast a boolean to a number and you'll get from false you'll get zero from three you'll get one solidity has simple operators just like other languages i don't want to bore you showing them all uh you can easily look them up in the documentation uh well it's i think it's more important to show you the specific uh the fields and stuff specific for a language for smart contracts and here we start the first thing is this uh so i didn't mention it before but you can think of a smart contract as of a class in object-oriented programming language so instead of class keyword you'll get a contract keyword smart contract is like a class and an instance of a smart contract is like an object it has a state and it has some methods the methods can modify the state of this object yeah and uh this way that's why this in in in solidity means the the current contract if you uh cast it to an address type you get all of the address properties in some previous version you didn't have to cast they added the they they they force force you to cast from some version just for readability uh if you call a method on us on this it is uh doing an external call instead of an internal jump what it means is that uh your contract is called as if from the outside uh i won't go into details but it's less uh it's more uh it uses more gas and you shouldn't in in most cases you don't do it in most cases you simply call some function without without this that i know this is a question in your experience a contract starts with some special design process board trello or some other tooling for design or you just go direct to coding so you would do you would uh design a smart contract just like uh any other piece of code uh so if you were to design a class in an object-oriented programming language uh you would probably first think about it if first define some some methods that you would like to see on it some state that you that you would like to it to it to star uh you would pos you would probably think about uh separation across files so uh in object oriented programming use inheritance uh in other in other languages you use composition more so solidity prefer insulating inheritance is more preferred so yes so you would use a blackboard you would use trello and other tools in the same way as you'll see uh later it's really uh it looks really similar to to other languages and and it's easy to learn okay going forward you get a couple of global variables those global variables are accessible inside of functions so a global variable called message represents the current transaction or actually the current message call so to say so uh you get you get to know who called the method on a smart contract and this can be another smart contract if you were curious who originated the transaction so as you as you probably remember from my previous presentation transactions can only be initiated by external accounts they cannot be initiated by some smart contracts and if if an external account calls a smart contract it can in turn call call another smart contract so the last smart contract in the chain will see in this field we'll see an address of its direct uh parent so to say so it will see the others of contract calling it if it wants to know who originated the transaction there is transaction origin for it so that does the difference between between the two you can also get uh the value of ether that was sent along with the transaction you can get the raw coal data and also there is a special method that lets you get to know how much gas is left for computation as you remember from my previous presentation every transaction has a gas limit and you can create a logic in your function that takes that into account so for instance say that you need to loop over an array in a function but you're not sure if you'll have enough gas to do it you can use gas limit a gas left method and and decide based on that if for any reason you needed to know uh gas price you can always use this field to do it there's also something called block timestamp so uh information about block block are current are gathered in this block of global variable the timestamp of a block is the time which miner sets the block to be so this is again an interesting interesting topic because how do you get to know the time in a decentralized distributed system well in in our computers we have a clock that's synchronized with some central server so when we open our windows it probably syncs with some microsoft server to get to know the current type time in case of ethereum you have a peer-to-peer network and you don't want to introduce any dependence on the central service so uh all of these computers around the world can have a different vision or different version of a time and similarly to how we choose the single computer to build the next block we choose the the person to set the time so a minor by building a new block can can tell everyone else what the current time is of course he cannot like give you a timestamp that's uh too much off because we know that blocks are built around in around every 15 seconds so if he tries to set a timestamp a minute into the future it will probably be uh such block will probably be rejected by most of the network uh it's coded into the uh into the ethereum node software anyway this was to give you a a warning here because you shouldn't actually be making your logic dependent on time so for instance say you create a game that where you randomly choose a winner and as a seed of randomness you use time well as the algorithm creating a random number is deterministic a miner could could set a time that will make him win the game i know it's really far-fetched but you need to remember that this is possible you can get to know that the number of the block in which transaction is mined its difficulty which i didn't talk about but it's another another uh topic in in blockchain systems uh also the gas limit of a current block if you need it for any reason let's now see how functions are declared so a simple function has a name a list of arguments and a list of returned values uh the the type the list of types of returned values so increment function takes an x and increments it by one and returns it a function can also return multiple arguments because as i mentioned it's a list of returned values so you can have a function that takes x and y and returns a tuple of two values uh this is similarly to what you have in go for instance and for all the other languages as well calling such increment function returns a tuple which you can destructure into two variables this way what's interesting is that you can name your return arguments again i only saw this in go and i think it's it's a very nice feature for one it allows you to completely omit the return statement so you don't have to do it uh and also i think it's sometimes it makes the code more readable because you not only get the name of the function in the name of the arguments you only you also get the name of the return type okay now you let's talk about some modifiers on the functions so uh or actually visit specifiers modifier is a name for something else that i'll show you in a minute you can have a view specifier which means that this function will only read from uh state variables it will never change them it's sort of like constant in c plus i think in other languages so in this case if y was a state variable declared outside of outside of the function uh incrementing y inside of a view function would be would make the compiler complain you also get a pure specifier uh which is even more more strict than view a pure specifier doesn't allow a function to have any side effects so a function cannot even read the the uh data uh and also cannot uh cannot uh call any other methods that are not pure it's simply it's a pure function it it always it only operates on the arguments that it gets uh you have visibility visibility specifiers so we already mentioned that you can make variables public you can also make functions public and they will be visible to other to other smart contracts and and also can be used internally external function can is visible to other smart contracts but cannot be called internally which is interesting private is only visible in the current contract and internal is only visible in the current contract and also those that derive from it so there are four visibility specifiers there's something called require function require function is a function that throws an exception if condition is not met so it reverts the whole transaction if this combination isn't met uh you can specify a required message uh a message that will be added to the to the to the revert uh so that it's easier to do the debug transactions and where are we using required conditions we can use them in functions we can also use them in something called modifier so modifier is like an extension of a function you'll see in a minute how you use modifiers so you declare it given a modifiers keyword modifier keyword the name of the modifier and the list of arguments a modifier cannot return anything instead of modifiers we usually put our required statements so modifiers are often used for to validate uh input arguments and also to authenticate access to some smart contract functions such checks are often repeated in the code that's why modifiers are handy in extracting this this repeater repeated pieces of code and the way it works is that at the end of the modifier most often at the end you you specify an underscore keyword that will uh that denotes the place where the rest of the function goes you can also uh put the the underscore at the beginning of the modifier then the required will be done at the end of the function call so how would you call uh how would you use a modifier suppose you have a function change owner that takes a new owner as an argument i forgot to put the name of the type of the variable here so assume it's a an address new owner you say that only after some time on the owner and only in state a it can be invoked so only after some on laughter will will run uh this piece of code then only owner will run this piece of code only in state eight state a will run this and only after all of these checks you will be able to the function will be able to continue in solidity you get other logic blocks as in any other language so you have if all statements for loops whiles breaks continue i don't want to bore you with that here's an example for loop that loops over an array pretty straightforward and the last thing i want to mention is events events are again something something specific to smart contracts events can be emitted and the front ends that are created for smart contracts can easily subscribe to such events events are stored on blockchain permanently so that let's say you're building a decentralized application and it runs in a browser user goes into your application and it needs to sync the state of the smart contract instead of querying uh for an older state of the smart contract it can quickly go through through the the log of events and uh be up to date fast so in order to use events you first declare it event can have parameters and then in a function you emit events this way uh okay i think this introduction is enough for us to jump into writing some code of our own and yeah let me let me share share a link to to an online ide that we will use this ide is called remix i'm pasting it on flag right now i'm in the chat in the chat and i'm gonna screen share as well oh actually uh i opened it in in safari if you are on mac as i do uh you should probably use chrome because it works better in home so let me quickly switch to chrome if you have any questions feel free to ask okay i made sure to delete cookies so that i should be having the same state of this id as you do when you first open it you can press anything here on the left you have a browser of the files we'll simply go into contracts and create a new file let's name this file course soul and right now i'll share a link to the to another gist that will include code that we will copy here and start working with it so let me find the gist first i added it to the chat and let's maybe read through it first here we have an example smart contract it represents a course at a university so to say and it's simple enough for us to start playing around with solidity uh what you can see at the top of us of the file is a license specifier from some version of compiler they make you specify a license and if you don't do it you get a warning you can say unlicensed which means that you don't specify any open source license so that so your code is closed source you get the version the compiler version again and then the body of the contract begins as i mentioned it looks like a class from object-oriented programming language so you get some fields you get a constructor you get a declaration of other other elements and functions as well let's read through it so the course has a name has a teacher address an array of student addresses and the mapping from address to point to to a number which represents points this is this will be a mapping where we'll store the results of our students then a constructor of a contract takes the course name and an array of students and immediately assigns them it also uses this global global variable message and sets the teacher to the sender of the message this means that the the person the account that created the smart contract will become the teacher we have a points added event which has three parameters address of the student its point his points and the timestamp that was done we have a modifier that makes sure that add points method is only called by the teacher so in this modifier we required the center of the message is the teacher and if not the the transaction is reverted with a method that only teacher can call this function then add points function simply adds points for a student again as you can see here we don't need to really insert in into the points mapping first because every key is initialized to zero so every student has zero points at the beginning we can simply increment their points this way and uh and then we can emit an event to let other applications watching the the smart contract know that something happens you also get a getter function that given an address takes the points of a student and in a really really dumb way returns uh a number which represents uh the mark of a student so again in poland we uh usually give marks on a scale from two to five and you also get like uh you can also get a mark like 3.5 we don't have floats in in solidity that's why we represent 3.5 as 35 and this is what you do with every time you need to have some fractions you represent them as integers so if someone has more than 90 points they basic or 90 points or more they basically get a five okay i think that's simple enough uh let's now copy this code from the list into the remix ide follow me for now i'll give you some time uh in a moment so after we copied we can go to the second tab here we can choose compiler version to be compatible with with the version of smart contract the language is obviously solidity we can choose autocompile which will compile the contract after every change so if we for instance forget a column a semicolon you'll immediately get an error here which is nice and you can also enable compiler optimizations this is uh this is similar to optimizations that you can set for your c plus code uh compiler does some has some heuristics to optimize the resulting byte code a bit uh now we have the com the contract compiled we see a green arrow here a green tick here which lets us know that it was successful we can now deploy our smart contract so what will happen right now in our web browser an implementation of ethereum is run this implementation is written in javascript obviously and it lets us play around with ethereum that's why we don't change the the environment here remix is also capable of connecting to metamask which is an extension that i have also installed here and which enables us to use it in production as well so if you wanted to deploy a contract to a real network it's also possible using this tool if you decide to stay with a javascript virtual machine you have a number of accounts here with predefined ether let me check if i can share it differently so you can also say uh see don't think so uh so you unfortunately you'll not be able to see the the the lists that i'm putting here but you can you can check it on your own that you have 10 accounts here in this list all of them are pre-filled with 100 ether and you get and you can use all of them for our for our purposes you can set a gas limit of a transaction here the value in ether that you'll send along with this transaction and a bunch of other buttons so what we will do right now we will choose the smart contract that we want to deploy and we will specify constructor arguments so for course name i'll put anything in and for addresses i'll actually use addresses that were auto generated for me here so i'll take the second and the third let me create this input data and i will paste it on cuts so you don't have to do it on your own i press transact and this will deploy the smart contract in this virtual machine and i can also uh see the deployed smart contract at the bottom uh if i scroll further you can see uh an interface to our contract so you have a button for odd points method you have a getter that returns the the the smart contracts take the course name you can see that for the array of students we got a getter which allows us to iterate over existing students there are two because i said i set them two addresses in the in the constructor the the third one will result in an error so you get an error revert something goes wrong yeah because we didn't we run out of the range you press teacher you'll get the the address of the teacher and uh the other the address of the teacher is the address of the account that was used for deployment uh mistakenly i used the same account that was you that was used for students so i'll correct my error right now i'll remove the smart contract and i'll deploy again using using the first account so now you can see that teacher is a different address than than students i get a mark of a student i can copy his address into the getter and i'll see that he currently has a mark two because he doesn't have any points okay i think that's uh straightforward enough let's see what the question is let's say the this course contract needs to have a description field or something other some other field that is long and expensive to start is it okay to add the field to the contract as a property or would there need there need to be some other storage like a relational database so in real life your decentralized application will either be will most likely be still hosted by some central server this is what happens right now so you'll you'll you will never need to start such description in the smart contract uh this course name variable is also redundant in this case uh so this is this is just an example in in a real uh in real uh contracts you rarely store any strings um and uh you you you if you need such description you store it in uh you you get it along with the the front end of the of the smart contract uh at my previous presentation when i showed the slide with uh comparison between web 2 and web 2.0 and web 3.

0 i mentioned that in the future we want to see decentralized applications that don't have any dependency on the central server in this case you are you will be fetching the the front end of a smart contract uh from a distributed storage like ipfs or some other protocol that allows to do that and in this case also you would fetch such description from from some other database and not necessarily do it fetch it from blockchain why not from blockchain because storing data blockchain is very expensive this is the the the simple simplest simplest answer to this question okay uh going forward uh now it's time for you to try uh try uh playing around with this code i have a task for you and i'll give you a couple of minutes to to code your solution so the task is to modify add points function right now it's not verifying the student's per student parameter so it is totally possible to add students uh for that points for students that don't that are not members of the course the task is to add the validation you can use any syntax features that that i presented so far and you can also you you can do it in any way and uh i'll give you a couple of minutes and let's say that if if someone is done please write on chat you can also ask questions i'll answer them and the first person who will finish and will be willing to show their solution is invited to share their screen so yeah if you are done please raise your hand and we will ask you to the stage where you will be able to share your screen uh i have a question uh here uh i missed some of the setup uh which environment should we use uh you should use uh the first environment javascript virtual machine this will run the the implementation on ethereum javascript that i mentioned and this comes with those accounts with ether available for you to use i'm getting the following error creation of course error error encoding arguments expected array volume okay um in in the when you're deploying the smart contract and the first argument which is name can be like any string that you provide and the second argument is an array of addresses you should use exactly what i copied on chat so an array of addresses is looks like an array in in in json you have a square bracket with two square brackets with two elements inside and those are strings uh so they need to be uh inside uh uh i don't know what's the name of it asterisk no i forgot the english name for for those things okay i managed to get my solution ready let's use some of the nice features of this aramid platform i'll try to create a vote whether you need more time or not and because i'm still waiting for someone to volunteer to share their screen and show their resolution [Music] okay let's start the vote let's see okay it used to be almost all knows but then we get some yes so i guess i'll give you more time even though more people don't want to wait uh let's see i'll give you uh three more minutes and if no one volunteers i'll show you the solution a solution around the use of a modifier yes you can use a modifier to do this validation you may not remember but you can also pass an argument to a modifier so a modifier has a has an arguments list and you can easily pass an argument of a function to the modifier invocation so to say by the way do you do you see the results of the poll as well or only only the speaker does oh okay so the results were that 31 percent of people said yes no more time and 69 said no more time uh yeah but i'm still hoping for a volunteer so oh even more yes answers so yeah let's see the answer because we have many people waiting for it okay so this is how i implemented it what changed is that i added only student modifier and also i added a student exists function so we get we get a student as a as an argument which we pass to only student modifier then inside of this modifier i added a required statement which says require that student exists if not fro student does not exist and the student exists is a getter you can see that it's a view method so it doesn't modify any any state uh you in this in the solution you loop over the array of students and as soon as you notice that the student exists in the array you return you don't you don't iterate further if the student if after the iteration none of the if statements were true you return files because the scene doesn't exist so this is my solution uh uh i always like to extract stuff so i i thought that this student exists could be used by someone else that's why i extracted it and also i'm using it in this modifier which looks nice on this method of course i could just simply write this as a first line of this function but hey why not use modifiers if we have them in solidity i see someone saying that they had the same solution but could make it run i'll give you one more task if you have any problems with compiler errors feel free to complain in the comments section but before i do that let's see our code in action so you can use this trash button to remove the deployed contract and deploy the deploy again if you pressed autocompile you don't have to press compile here it automatically quickly compiled i'll choose again the first account then in this in this constructor i will specify the same arguments as before copying it from your chart and i deployed it and then uh let's see uh i'll try to call at points for a student that doesn't exist so first let's see what students exist zero is is this address student one is this address and the teacher is this address let's add odd points for teacher he isn't a student and yeah let's do it 80 points for teacher we if we expand here we will see transaction log and the last transaction has this red cross which tall tells us that that there was an error student doesn't exist so my solution worked let's try adding points for an existing student it worked i get green tick and let's now query the the mark after adding 50 points for a student it he he should get free mark free because he got 50 points so far yeah and we see mark three here okay uh i got some questions is it possible to just add this piece of code to add points uh and then here's a loop for arranging over students uh not really because uh what you're doing here remember that require throw frozen exception when uh when the condition is not met so let's say that you have two students and you're adding uh the points for the second student in the for loop you first run the the comparison uh between current student and the student that you got as a parameter and you you can see that the first student is not the second student that you got as a parameter and the require is not met it throws and the function doesn't work so no you cannot use require in this for loop creation of course errors uh error encoding arguments argument null invalid arguments i guess you forgot to add arguments for in the constructor let's say if i can reproduce your error if i yeah if i don't set arguments here in this deploy section if i i emptied it out and i got the same i think i got the same error expected array value argument needle value yeah that's why you got the error remember to paste here what i posted on in chat i'll post it again so it's uh no that's not necessary um didn't copy this is it the array needs to be supplied okay let's run another task task two we have a problem uh with uh add points function the problem is that in blockchain you pay something called uh base fee for every transaction so even before your call the runs the transaction already burns some fee some gas and the and this is paid for every student for every student that you want to add points why not create a method that takes an array of students and an array of points and addo adds those points in a loop so this task is as simple as as it make at points function take two arrays of the same length and add those points for your students again i'll give you some time and let's hope just this time someone volunteers i got a question why not use a mapping [Music] if you mean a passing a mapping uh yeah instead of two arrays uh if you mean passing a mapping as a parameter uh you cannot do that this is the the the only yeah you cannot pass a mapping as a parameter to a function it used to be this way that you couldn't even pass a struct as a parameter to a function uh there is a like a new version of something called abi encoder uh a newer version of uh solidity uh it's enabled by default uh with so the latest version of solidity actually allows you to pass extract as a in a parameter which was not possible before let me yeah i'll share my solution right now so if you still have some time uh let me quickly code it okay so we want to get two arrays let's first change the parameters and now we need to do addition in a loop for that simply let's create a loop before i loop over i should check that the lengths of the arrays equal not introduce a bug in my code now i need to check that a student exists before i add students for him so i require that current students actually exist if not i throw the same error as before student does not exist and before because i now have multiple students i'm getting rid of the only student modifier and now i'm adding students for adding points for the current student in the loop i get a compiler error saying that uh the location of array should be memory all call data this is what i mentioned on my presentation uh you have three places where you can install data for this i use call data because i don't have a need to modify uh modify this parameter yeah this solution should be working uh if you want to look at it uh yourself i'll create a gist and quickly right now and paste the link to it uh let's wait a second to do it in a different browser when i'm logged into github hey i'm posting the gist solution in the chat uh because we need to finish uh i'll quickly show you another task that you can do as a homework to learn more about solidity and uh yeah i think it's nice to have something to practice with homework so i mentioned before that mappings in solidity don't provide iteration so as a homework you can try implementing an iterable map that that has the following methods you can set a key you can get its value you can get a length of the mapping which returns the number of elements you added to it and then after you get a length you can iterate over the elements with at method so you will call the add method this many times as you have as your arrays length so if you have a if you have a mapping with three elements you will call method at three times to get all of the elements this is my this is my proposal for you uh we'll i think we'll post it in on discord so uh mateos if you're still with us if you could paste a link to the discrete channel on the chat and after that that would be it from my side thank you all all for your attention and i hope you enjoyed this presentation and workshop uh the last question can we display the address of the student how can i conquer address to student that knows not exist and this is a bit tricky again in solidarity you don't have methods for string operations so you don't have like a nice method for concatenating a a string to a to a literal for instance or or making uh a concatenation of two strings uh this is caused again by uh by this uh idea that uh programmer should be should be aware of what he's doing so you can do it yourself you can create a loop where you yourself write to a dynamic array creating this concatenation but then you are really aware of what you're doing of all the loops that you are introducing which are money because every computation costs gas and in in return it costs fees that we pay to the miners for our transactions and i think this is one of the rationale behind not creating such methods in solidarity thank you for your comments and again thanks for the attendance yeah i hope to see you tomorrow uh on other lectures on other lectures in our series thanks again

Automatic transcript — names and jargon may be misspelled.