Aleph Zero Workshop | Pete Urinsky | Safe and Robust Smart Contracts in Ink! | ETHDam 2023
CryptoCanal·Sat, Oct 7, 2023, 12:00 AM
Pete Urinsky is an Ecosystem Tech Lead at Aleph Zero. Aleph Zero https://alephzero.org/ ETHDam is a Hackathon & Conference that gathered over 500 DeFi and Privacy builders on the 20th and 21st of May 2023 in Amsterdam. Privacy is normal. Following the arrest of Alex Pertsev, a Tornado Cash developer in the Netherlands, ETHDam 2023 is determined to counter the chilling effects of the lawsuit and bridge worlds to discuss the future of privacy and encourage to build on the shoulders of cypherpunk giants. ETHDam is powered by CryptoCanal, - a blockchain education and events platform growing in Amsterdam, spreading its roots to Rotterdam and Zurich. ETHDam 2024 is on the map already! Keep up with us to see updates: CryptoCanal https://www.cryptocanal.org/ CryptoCanal Twitter https://twitter.com/CryptoCanal Join CryptoCanal Community https://t.me/CryptoCanalCommunity We would like to thank our partners and sponsors that made this event possible. 🌷 Our BFF 1inch https://1inch.io/ Our Frens: Sismo https://www.sismo.io/ Aleph Zero https://alephzero.org/ Scroll https://scroll.io/ RAILGUN https://railgun.org/#/ And our Sisters: oasis.app https://oasis.app/#earn Maven11 https://www.maven11.com/ bitvavo https://bitvavo.com/en Lido https://lido.fi/ Spankchain https://spankchain.com/ API3 https://api3.org/ Gelato https://www.gelato.network/ VanEck https://www.vaneck.com/nl/en/crypto-etn Marlin Protocol https://www.marlin.org/ Silent Protocol https://www.silentprotocol.org/ Cyber Capital https://cyber.capital/ … and Proto https://twitter.com/protolambda 🍍
Transcript
foreign [Music] and I'd love to tell you about smart contracts in ink specifically but I guess the first part of the talk will be more generally applicable to well other smart contract languages and and platforms um so so yeah I felt compelled to include the definition of the smart contract but um well like a slight remark is that basically the word contract may be misleading to some as well of course you can't think of it as like an actual contract that you you know you enter between the like you yourself and the code or your own program and the code but to be honest this this intuition is maybe not uh not the best I like to think of smart contracts as basically programs that execute on the blockchain like treating the blockchain as a computer of sorts um because well the blockchain is essentially has like the the Processing Unit which would be the runtime and the storage which would be just you know the blockchain storage so it kind of tracks in the whole like computation model um and yeah that's that's I think the best way to think about them like programs that execute on the blockchain um so you know once we have that we can build out a lot of interesting use cases uh starting of course with D5 decent Fast Finance uh but then there's some very interesting developments in in the digital identity space with all the kyc and KYB Solutions uh perhaps with privacy included it's uh it's really good space supply chain provenance tracking uh especially for like bigger bigger Enterprises um quite quite a Hot Topic is the certificates of ownership of course nfts right with you know art real estate uh and um you can use the nfts as as a form of like software licensing or well yeah or tickets to to events and whatnot uh and of course you can you can come up with as many use cases as you want maybe some game Phi or or something even entirely different um so so yeah I think and especially important area is the decentralized finance right uh so basically think what you know and love from traditional Finance but all put in a very decentralized and permissionless setting so there's like no no trusted intermediary no no no bank it's all just you know pieces of code running on Smart contracts so in that way it's it's very transparent and you you can actually verify what's what's going on uh provided you well you have some some small amount of like code literacy and um examples of of D5 include you know decentralized exchanges of course uh by the way you of course know Union swap if you don't know Common this is something that's being built on Outlet zero um Landing protocols trading crowdfunding payments uh yeah whole whole variety basically actually you can think of you know like the whole whole traditional Finance World replicated on on the blockchains and using smart contracts um so now what I kind of wanted to focus on during this talk is like writing the smart contracts and and building all this out in a way that's that you know that's robust that that avoids uh some common problems right so I well kind of jokingly but not really uh formulated this Grand theory of hacks saying that basically an exploit can happen or probably will happen in the places in the code where you are not 100 sure what actually happens right maybe you're losing track of some State updates maybe something happens implicitly maybe the data is not exactly in the format you would expect it to be all right so uh as kind of general advice this is not this is applicable not only to Ink Smart contracts but but I guess in even into programming in general and especially other smart contracts like to avoid that I would say input validation is extremely important and in general like typing your code in in the right way meaning that things should have you know like clearly defined types right um that in general helps you avoid the the most common common problems then mutating the state so like you know uh going to the to the smart contract storage and actually changing something uh that's that's a risky operation actually right it's also inevitable uh in a sense that well your contract needs to update its state in order to function but I would suggest uh treating the the State updates as as kind of like a special operation that you need to do extra carefully right um and later we're gonna see how how Inc actually helps you kind of track these State updates track in a way that uh they like really starts to stand out in code and uh you know it's way harder to like mutate the state without even knowing it right um actually and this may sound trivial but all of the places where the code repeats are are quite risky sometimes so Loops obviously but especially like recursive code so functions calling other functions and especially contracts calling other contracts this is like a huge well I would say Vector for uh things going wrong okay um and as we're gonna see in a minute in on like uh well actually a real world example um the catch-all statements that you know whenever you don't know what to do you do you call this certain function this is this is risky okay um so just just to illustrate and this is not not you know maybe not very accurate but just a bird's eye view and a general idea of how the Dao hack happened uh a few years back of course the issues have have been fixed uh since but I think this illustrates a really important concept in the whole of smart contract development so imagine we have the we have the Dow contract obviously and we have some some actor malicious actor so I decided to call the actor malice just like the traditional you know Alice and Bob here gets malice I thought it was funny uh yeah maybe not so much I don't know but um the dial contract essentially for well at least for the purpose of of this this example has two functions you can deposit some eth and you can withdraw some eth Okay so the the attacker first deposits let's say 100 dth it can be actually any number um now and then actually immediately the the the bad actor the malicious malicious actor wants to withdraw the the deposited amount right so what happens is the dial contract basically checks if if the attacker has enough balance yes of course because the other tracks this is actually a completely legit operation so what then happens is that the dowel contract basically sends a transfer of 100 eth back to malice but the way this happens in in solidity is that whenever you're sending money to a to a Smart contract he this smart contract to like handle this transfer will call the receive function right and if the contract does not have a receive function it will call the fallback function and this is what happened in this example but the way the fallback function was written it actually contained another withdrawal okay so yeah this withdrawal call happened again and you will notice that the dowel contract was actually sending the sending the eth before updating the balance okay and um so what happened here is it still happens in context of like one one execution step that the contract does the transfer again to malice which again calls the fallback function which again calls the withdrawal function so basically the loop repeats until the dial contract is out of out of funds and uh actually an important step in the attack was that the the attacker contract was checking whether the dial contract still has enough funds because it needed to stop the recursive loop at some point not to revert the whole transaction because of failure of of the last transfer but uh yeah this is basically how they drained the the contract of all of the funds and uh well you will notice that it's actually super simple to prevent you just first update the update the balance of of the attacker's account and only then you do the transfer if you flip the order of these instructions the the attack basically doesn't happen but I think it goes to show that you know it's obviously a very basic like re-entrancy example but it goes to show that while smart contracts may look very simple and you know like to any seasoned programmer the code looks like almost like a toy example the the stakes are quite high right because there's there's users funds involved and um and sometimes the the interactions can get like non-trivial uh so so yeah you need to really you know uh write the code in a in a really Safe Way and really focus on all correctness and safety right um yeah so moving on we are going to discuss the ink development in context of the LF zero blockchain um well if you are not familiar with ls0 it's a layer one proof of stake blockchain with some nice privacy features that we were building out you can read about the liminal framework uh we actually have like a developer preview let's call it it's called The shielder you can check it out all in our documentation I will actually link to that later um yeah the blockchain well because basically um it's a substrate based blockchain but we have created our own consensus which well results in the you know both block times and uh times to finality being sub second so um yeah it's really fast basically and the transaction costs are really low which actually is quite important when you know thinking about smart contract development because it kind of can influence the way you you write the smart contracts right you won't probably have to like you know dive into the byte code and do some crazy optimizations because it's just cheap if you're conservative enough with how you allocate storage so like you know if you want to store videos on the blockchain it's probably gonna get expensive but if you're like reasonably conservative with with your storage you'll be you'll be fine and a few months ago we've launched you know smart contracts and ink on the mainnet so there's uh use cases building out we have an ecosystem funding program in place so we've got a lot of exciting stuff going on uh I think it's worth you know taking a look at Inc um so if you want to oh if you want to check it out the QR code I think points to our main website but you can you can get to all of the other places and like one or two hops uh through the links I would I would pay special attention to the oh let me get the mouse pointer to the developer portal uh it contains some nice you know guides and articles that go beyond what I'm what I'm going to show here because well my goal today is basically to get you excited about ink development and not necessarily you know uh walk you through all of the aspects of ink development I try to be fairly comprehensive but this is mostly like you know a tour rather than a very detailed tutorial right um so yeah what is ink basically um Inc is an edsl for rust if you're not familiar with the edsl contact concept it's an embedded domain specific language but uh well it's I think it's best to think about Inc as basically a subset of rust so what I'm hearing quite often is oh but rust has such a steep learning curve and it's hard well be that as it may Inc is not the whole of rust and actually Inc I think focuses on just the very basic features of rust so everything that is actually hard about rust development you won't find an ink so well okay the syntax is perhaps new to you and you will need to you know learn like uh a few types but uh for all intents and purposes Inc is an easy language to learn I'm you know I'm not one of those Geniuses who just learn everything in 30 seconds so you can believe me um so so yeah but being a subset of rust it inherits some of rust's benefits oh actually most of them but um first of all it's a modern language so if you look at it like the history of programming language research over the over the last I don't know 20 years like rust really and Inc by extension uh rust really like makes use of the like best discoveries uh it's type safe it's like as typesafe and as a language can be while still being usable right because you can you can do some crazy stuff like dependent types and really prove stuff about your your pro your code but then it's gets really tedious to write and you need a PhD and here I think it's uh it strikes the right balance then it's memory safe and we're gonna talk like very shortly about the memory management in in ink but but yeah but I'm seeing that my time is actually running way faster than I thought okay yeah sorry I don't need to talk incredibly fast uh I'm not on anything I just I'm pressed for time um the tooling is is actually very nice in Inc well in the context of smart contracts it's maybe not as mature of an ecosystem as as for example EDM but I think it's in terms of like you know the support for developers it's it's there and it's well it's getting there so so yeah there's that and rust actually is like winning and has been winning for the past few years the like stack Overflow surveys for the most liked language so I think that's you know that says something uh I don't know about like last years but but definitely it's uh it's always there at the top um and the next well important feature or actually a benefit is that it compiles to wasm so webassembly which you know has has a like a proven set of benefits like ubiquitous fast and secure obviously uh basically runs everywhere and um is yeah it's efficient uh and runs in like a Sandbox environment so so yeah we can say it's secure of course not to say that if you're you know write that code it it will automatically become good no but uh you know it it helps it helps um now this table I know it's quite intimidating when you see it on the slide like this uh but it's it really just you know I don't want you to really memorize it or anything but uh I think it goes to show that well even though ing is like well it's a new language for for many of us but when you look at like the level of the you know like high level Concepts it's really compared to solidity it should be familiar like all of the concepts should feel familiar familiar right the exact implementation may be different and uh like for example the storage entries are always 256 bits on evm their variable size in ink which which is actually great for performance because you rarely actually need 256 bits for your like numbers um but in general if you're a smart contract developer on evm you should be able to switch to to wasn't based contracts and to Ink specifically quite fast and without you know like any significant significant conceptual shifts um this is something that I probably should skip but I like it this is just you know a fun fact for you so awesome is basically well you can think of it as like like binary format uh well kind of kind of like regular assembly but when you actually take the binary blob and decompile it into like textual representation you see this you see this familiar little fellow and uh if you're like if you're like a programming language nerd like me you instantly recognize it this is lisp right we all know lisp okay probably not all but um but this is list this is like a language that's been there for like 80 years uh so yeah but with like a cool modern twist and you know executing in the browsers and everywhere um so I I like the like the beauty of Simplicity here right because when you look at the the code you notice that there's actually a stack machine so basically the whole execution of your program goes like this and notice how simple it is if you have an expression like say five plus seven you parse it so that you start putting stuff on the stack right and you first put the operands so five and seven and then the then the the the operator the plus and the whole execution of your program is basically that simple you pop something from the stack if it's a if it's a function you see how many arguments it's got well it's got two in our case okay so we know we need to pop two more elements from the stack if they are not functions themselves then we are good to go we can execute so we just perform the actual function and pop the value back onto the stack and well in this simple case it's it's easy right we just end up with 12 on the stack and once we pop it we know that okay the stack is empty we have one result well we've executed the program but it actually you know extends very well to to even like very complex programs uh jvm I don't know if it still is but it certainly used to be a stack machine so like half of the world software was running on the stack machine I just thought this is an interesting concept um but yeah you know moving on to like uh more practical uh part of the of the presentation again this is something that maybe quite intimidating but it's just meant to give you like a bird's eye view of what the what is it like to to develop a smart contract in ink right from like the very you know typy type perspective like what I need to do on my computer to to get up and running and actually deploy a smart contract okay so well first thing is as always installing some some prerequisites some some dependencies uh some libraries um you just copy and paste a few lines there you go um then a concept familiar from every like web framework and uh yeah that that you might have used you're basically using the cargo contract tool that you've installed in the in Step Zero uh you basically bootstrap the the new contract it gives you like the whole scaffolding like a minimal scaffolding basic contract as a starting point and then you just write your code okay then you use the like built-in uh test Suite to to run your tests which are in code and then you can compile it and upload it to your chain um and there's a joke here that yeah that's um again that's maybe not as funny as it was in my head when I was writing this but um you get well I'm gonna read the slide you get two two artifacts when you build the code right the contracts binary code the Watson blob the contract metadata the the Json and the the like contract bundle so the two above bundled together and uh this goes to show that you need to watch out for off by one errors right um yeah this is a good time to laugh but but yeah don't worry don't worry I can take it um okay so we are gonna also look at the actual you know deploying the contract to the chain but later okay uh if we get to it even so my my whole like demo example is the bread and butter of of defy and smart contracts so an erc20 or PSP 22 token uh PSP 22 is basically erc20 but in in the substrate ecosystem talk um I'm calling it Bitcoin because I'm Pete and it's a coin so it kind of made sense um yeah when you look at you know what the erc20 actually is it's just a standard and basically a set of questions that your contract needs to respond to so it needs to know its total Supply a balance of of a specific address uh well we are going to skip allowance and the the whole approve and transfer from thing we're just gonna focus on transfers to keep it short because as far as I know I have 10 minutes left um and then some it needs to emit some events but this just goes to say that the standard is just you know it's very basic it just your contract needs to be able to do a few things and there you have it you have an erc20 token right so so yeah well let's now look at how this actually looks in code okay and uh don't worry you in most of the time you won't need to remember how to write all of these macros and everything because you almost always start with like a bootstrapped contract so you just need to modify the logic and not really you know uh remember the exact syntax of the macros I mean you will just learn it after you know the second contract you write but it's it's actually not not that essential to start out um but yeah I think an important information is that uh the line starting with the with the hash sign uh are macros uh not comments so um yeah they basically um well pre-pre-defined some stuff for you do some imports um enforce certain invariants especially the ink contract macro we're gonna see that in a second so basically the smart contract is is a module it's a rust module and the module is well a set of things of language constructs bundled together um now use that we see here and we are well it's kind of like importing something but it's mostly just putting it in the scope and assigning a new name to it so it's more like C plus plus than for example Python and the difference is that python for example can execute some code on import and here it's just introducing something into into the scope okay um now each contract needs to wait I'm saying it here yeah so once we have the module with the name the same as our contract and everything we need to declare the storage struct okay uh each contract needs to have exactly one storage tract uh this doesn't limit you in any way by the way because well if you wanted to have two storage tracks you can just you know combine them as two fields of one parent storage track that's it's uh perfectly composable in that way but um but yeah well first you need to tell Inc that this is actually the storage track and did just basically well tell us the tells the ink compiler that okay this this piece of data needs to be actually put on the blockchain so so you know it needs to have a certain memory layout and everything it's uh it's slightly different from like your regular storage outside of outside of the chain um but you just need to remember to include this macro um and yeah the derived default we are gonna talk about that but for now we are just gonna say that it's a way for the rust compiler to basically give you the like the default implementation of your struct it can figure it out uh basically whenever you want to create an empty struct you can use the default here uh it's not that important since we're pressed for time um right so since we're doing a ERC an erc20 token uh I think everyone knows what you need to do it needs to have a total Supply which will be just a balance and balance is just an alias that the ink contract macro gives us and the and the balance is mapping so you know kind of things like a bank which keeps track of the balances of each individual account is actually the same way here it's a mapping between the account ID which is like the account from like the native blockchain so it's the same account that you use to interact uh with with the chain natively uh it's also here um to basically keep track of balances well and obviously the balance that it maps to uh by the way if you don't know structs in Rust they are very similar to say extracts in C plus or maybe well objects in JavaScript maybe but they are just like very very simple very minimalistic so you can you know they have some Fields you can address the fields by their name but there's no like weird inheritance so rust actually does subtyping in an interesting way but uh we don't need that for for the smart contracts just to tell you that it is there but for structs there's no inheritance which I think is an amazing design choice and I like applaud the creators of rust every day now I'm I'm joking but but it's a really good choice um yeah okay I think we can we can move on we have the storage um yeah the default we're gonna skip that because there's not enough time uh but essentially what this derived does is creates an implementation like that uh basically rust has traits which are well kind of like interfaces and you can Implement them for your structs and then you can call the operations from this given interface on your struct here it's default and you can see that it just delegates the default call to the individual Fields that's how it can be done automatically actually so basically the default you know if you're familiar with like category Theory or algebra the default value is basically like the zero of a monoid if you're into that but uh it's really not necessary to know in order to write smart contracts successfully um yeah let's give that okay each contract again as enforced by the ink Constructor macro needs to have at least one Constructor and this is basically like the the entry point this is what gets called when you're creating the contract Sno as an owner right so you're like instantiating it for the first time um so here well it takes some arguments uh obviously and it actually creates the instance of well itself here but it's basically I could could could as well write Bitcoin instead of self because it's just this uh the same thing is just more a bit more generic when you yourself uh but don't worry about that for now um so the cool thing about the constructors being just functions marked well actually methods marked with the Constructor macro instead of like having a predefined name like in it or something is that well first of all you can choose the name for yourself which may fit your particular use case a little bit better you might you might choose initialize you might choose you know create or I don't know even maybe mint in some instances would be would be okay secondly you can have as many Constructors as you like provided that it's at least one and um and yeah that's it so here we are doing a very simple thing actually uh we are creating a variable called balances where we are assigning a default mapping remember the default huh it's here again um a default mapping is basically a an empty mapping right and um then we are using like this magic end function uh called on the class itself uh to get the color of the smart contract because it's quite important for the smart contract to know who's calling it and it also can own its own account because each smart contract is like an account on on the blockchain here we are we want to know who's calling us because if someone is calling the Constructor it's the owner of the of the contract so um so yeah so now we know that you know if I'm the one creating the coin I own the initial Supply initially so okay this tracks uh should we finish okay yeah no sure let me just finish this slide and then I'm I'm off um initially the owner will have the whole whole balance right so our mapping initially is just the owner has all of the initial Supply and we can just uh create this instance and if you want to see the rest of of this whole conceptual Journey uh yeah let's go to alex0.org developers where we have some tutorials that are pretty comprehensive and um yeah see you on the internet grading smart contracts uh sorry I had like three times more but miscalculated that time okay um see you everyone [Applause]
Automatic transcript — names and jargon may be misspelled.