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

Loading player…

LearnWeb3 DAO 🛠 Blazing fast smart contract development using Foundry - Haardik

ETHGlobalMon, Oct 9, 2023, 12:00 AM

Join Haardik from LearnWeb3 DAO for a talk titled "Blazing fast smart contract development using Foundry". Learn how to set up Foundry and have a blazing fast smart contract development workflow including fuzz tests, cheatcodes, and more and deploy to your favorite EVM chains! As new users flock to web3, critical infrastructure advancements are needed to scale. Scaling Ethereum is your chance to shape the future of Ethereum. Join us March 10th-29th for three weeks of hacking and summits featuring teams like Gnosis Chain, Scroll, Hyperlane, UMA, IPFS/Filecoin, and more. ----------------- Follow us: https://twitter.com/ETHGlobal​ Check us out: https://ethglobal.co​m Email us at: hello@ethglobal.com

Transcript

foreign [Applause] [Music] to the learn web3 dial Workshop blazing fast smart contract development using Foundry joining us today is Hardwick who will be talking us through this session and with that we'll pass it over to hardik to get this session started absolutely it's just finished sharing my screen and it's a bit conference you all can still see it uh get started hey guys hello everyone uh it's been a while since I've done any Global workshops it really helps to come back and to really see a lot more me or everybody want to do workshops but today we are talking about smart contract development that has been using boundary so a little bit about me my name is Harvard uh I don't know first name legally uh the co-founder at the an education and bib back to the list uh for this talk or Works off I'm gonna be keeping him at anyone's head so I have to have a bit of work here if anybody has any questions you can put it inside I'll answer sort of that I go along as it happens single further pause we have any time and yeah try to keep this conversational if you have any questions um so what is Foundry right so Foundry is leading is solidity based smart contrary development environment that kind of falls into the same category of tools as like higher hot or travel or eight vertex which you might have used before the main difference is that everything you do in Foundry is done in solidity so you're writing tests in solidity you're writing your deployment scripts and all of that in solidity everything you're doing isn't solidity unlike for example hard not or truffle where you have to do stuff in JavaScript or in e-ports or Brownie and similar you have to be stuff in Python every single Foundry is done in solidity and we'll see they have there are certain advantages doing that there's actually a very good case for doing all of this stuff in solidity as it avoids kind of that one level of abstraction that all you now also need to add up an understanding of data but you also need to have an understanding of how JavaScript test seeks work you also need to understand how to convert uh U and 256 to a big number and then back and forth and is this really annoying so doing everything in solidity very very helpful the sort of the key differences you mindful to consider using battery or that if you're relatively newer um if you're kind of starting yellow do you double tap past experience in JavaScript or write thought and your learning solidity file three might be a better fit for you the in just focused on sort of solidity based stuff all around the second thing is and this is actually also a pretty big deal Foundry is very very fast as much as eight times faster at 100 female Predators the reason for this is you know Foundry was built from the Roundup uh it's written in Rust first of all and I had everything that filed reused it is eternally was built from the ground up to sort of support this product it's not really uh relying on external things as much compared to something like hard hat uh where first of all it's generous for it then it's using the solidity generous book compiler and then it's using like e3cis uh overall it's relatively much slower than Foundry is now for this hackathon if you're just starting to get up again maybe this doesn't matter as much to you right now to get the up late a simple project with maybe one or three solidity files uh the time difference between hard hat and sound reads that'll be pretty negligible and you might not notice major time differences but as you start working on bigger frauds in it this time difference becomes a very very noticeable to the point of uh the Salt Lake Library it was pretty famous the solid library takes six seconds to get compiled and be set up using probably is going to take up to like 45 seconds on that tools that even a couple of minutes if you're using hard and that probably adds up over Kai so as you're trying to fix above you know five seconds versus two minutes or compilation really adds up a lot so it's it's pretty fast it's it's it's up there um so generally found green is in a broken j3 specific segments and we're going to take a look at a couple of them today so there's Forge uh there's cast and there's Annabelle right so Forge is the main uh sort of the compilation tool the CLI Community kind of do everything related to running uh like creating a new Foundry project compiling your contracts the running tests all of that stuff happens with Forge uh cast is a CLI tool to sort of send transactions to the theory of that for and so on so you can call functions on your smartcontract about any network uh using tasks so it's kind of like the terminal based uh label it Call functions and stuff on ethereum and admill is a local local ethereum node that you can run for development and testing purposes and it's kind of like hard hat node or truffles diminish this is the local evm implementation that just is really fast either you can run your tests against data you can Fork a network and run about ad will and so on so forth we're mostly going to be focused on Forest today and I will try to take you through as much as iPad about concrete and what you should care so let's just let's just jump into it uh we should just start writing code so the first thing you want to do is if you haven't already installed boundary you don't already have found every other machine what you want to do is it is actually let me just pull up the page for it that will be easier uh there's a current command you have to run but I will send it inside it will also open the page so you can find it yourself but basically uh yeah if you already haven't installed Foundry um I'm on a Mac Oso you just have to run this command you need to download the final three up binary from Paradise and once you've installed conry out that is the sort of package manager for final Breeze I know like the tool you use to keep cloudberry up to date and it's solid and all of that stuff so I already have family up on my machine and once you've downloaded it you just type on react and it will install the latest scores setup Foundry which basically means the latest version of the force cast and handle on average series right so once this is all done um we will start by creating a new project so create an empty directory I'll call it uh Foundry tutorial oops probably tutorial and what we want to do is just type boards in it and this little oops forwards oh I have entity well I'll go there yeah see you then too I've had the folder you create and then type Forge edit and this will set up a new Foundry project in that folder and now let's just open this up and yes code to see what it looks like it looks all I don't know what we have over there so we start off it gives us a a solidity simple solidity contract to get started right we have a counter on track this the number you can set that number or and increment that number over time so the way things organ boundary of us that everything is validity right so you write now Quant cracks and solidity but then you also you write your tests in solidity this is a test for that on thread and then you also write your scripts in solidity this is where you might want to deploy your contract to a natural Network and so on other than that what we have is we have a lit folder which comes with The Four's standard Library installed and we'll get into what that means but this is really really cool stuff but just to get you familiar with the basic commands the very basic commands that you must set up our Forge build so once you have the product you run Forge build this will compile all your celebrity files and then it says okay compiler when successful and at this point you will have an out folder that comes with the Avis of all your contracts so most of these contracts currently run from the standard Library uh but your contract powder this is the API for counter.solve it comes from fordsville once you've built it the another basic problem you need to know the sports test and course tests add the name to this runs the tests against the corporate runs the tests that you wrote and the cool thing about the bit is is it actually gives you the gas cost required to run each one of your tests since your test is not written in salinity and you're calling others functions that can tell you the gas cost for that test and in fact if you do first test things they'll get into it also gives you like the average gas price and the median gas per average gas cost at the media gas costs required to run that test so the forge build and forged test two leasing commands needless now okay um so this this contract obviously is super simple but we'll get into a kabulous neat probably uh final features that I'll show you kind of why it's so full uh so we'll start off by creating a new contract first of all with a new contract let's call it mirror.soul and this is going to be an extremely simple concrete I'll just copy paste this this building could be an extremely simple contract which all it does it has a function called Mirror which takes in a number X and then it Returns the same number back unless that number is 30. if x is certainly better prepared sporty too but otherwise it's just for points like spat so you know 99 of the cases of blister turned the same number back but then there's this one sort of edge case where it will return 42. so what we want to do is we'll create a test file for this we'll create a test file and the convention with Foundry is your test files are named contract dot PE dot sole so the contract name is a better so this will be mirror.

t.so right once you have this test file we write the test as a regular solidity contract and I will copy paste it with it that I already have it but we'll walk through this ourselves so what's happening over here so first of all the import the testing framework quote unquote from the fourth standard library and the fourth standard Library comes from this live folder over here rates and you can look at the test of dot solve file that we're importing it basically Imports a bunch of other files and read sports it but it allows us to write uh tests and solidity and then we import the absolute on crack that we're testing which is litter.so with that we declare a new contract mirror test is passed and then you have a function called setup so every test will have a function called setup which initially sort of you know sets up the testing environment specifically in this case it deploys a new version of the mirror contract and saves it as a state variable so you can call functions of the same concribe over and over in your following tests um then we have two test functions over here again the convention and Foundry absolutely I think this is enforced is your tests your test functions must begin with the term test right so you could you cannot like have a 178 symbol over here you have to name it like tests and a little or Test X Y to Z so you have a super simple test DOT test set volt and we're like okay assert assert equals 0.05 and five so this is just typing okay if I call the mirror function with x equals five it should return to me five and it should be equal and if it's not equal the test will fail so the authority pull nice helper function have this built into the testing standard Library uh this is pretty basic test over here this one is more interesting so boundary has support for what's called Buzz testing and then what first testing basically means is it can sort of so in this case you know we're studying x equals five ourselves we're setting x equals five matterally um but in the fuzzing test you'll see somebody say something okay so in the buzzing test we take X as an argument and then we just pass that argument forward can I send the mirror that's all um I don't know if I should just put it in chat there you go yeah so in the first test we take an argument and we pass that argument so we're not testing for a specific value of x but what first testing does and this is a more General concept than to spawn variables the more General sort of computer science related stuff but first testing basically means that the tester itself the testing framework itself will try to find random inputs to your function it will try to find random influences to your function and it will try all of them out and if it fails that any one input it will let you know so in this case it will try a different value effects and then it will assert equals on all of those problems effects and if it fails at some point it will let you know so you might have guessed what's going to happen over there if we run this test um what we are going to do is let's go back to our current model and type for its test and it may not detect it the first time because it's not running as many times right now so by default that's a good question in the chat really by default binary tests 256 values randomly so it runs for 256 times randomly and partly that's not enough to bind the obvious issue in our code um and you know it depends on your sort of problems so Plus testing is not a hundred percent guarantee and uh have it runs like all infinite values you need to set like some sort of limit and to do that in this case so probably read one so the finally the funnel files okay this is sort of the configuration file if you used hardback before standard lately part of mp3. yes filed but you didn't set the configuration values for file grades and specifically for bus testing what you can do is add a bus parameter and set clown breed underscore bus underscore runs and I'll set it to say at how the relevance great and if I run for status again okay it's still passing there we go test with the rate of values every time so we reached the number of runs even more if we wanted to test even more values but in this case uh you can see it says test fuzz failed with the argument 50.

right so we didn't tell it to run x equals 50 it just randomly failed into the argument 50. um so it was testing for random values and this first testing is very very useful and this is obviously a very simplified example you know looking at this code you can clearly tell some mirror functionism beginning as it should but typically these buds are this easy to find you can imagine some sort of complicated B5 protocol with 100 solidity files all across the project balls of importing each other and inheriting from each other and having all the fancy stuff around there and sometimes it's easy to skip out on certain Edge faces oh on multiplication is going wrong somewhere or there's some dangling different Vision that's gonna like given a certain input it's going to be something that's not expected of it so sometimes manual testing fails to pack certain types of bugs that first test LinkedIn lb patch and it's really useful that Foundry comes with Plus testing as a built-in feature so and all you have to do is just take an argument take an argument in your tests and pass that argument forward and it will automatically Generate random values for those arguments that's all you need to do can you define the range for those numbers if you had to define a specific range you're probably better off just using like a regular test function instead because you know like a Min and max value for it um if it's a really large might so well yeah I think there's probably a way I've been out to look in the config for it but I do not know that off the top of my head right now unfortunately um but okay great question though so that's for Buzz testing now what else I want to show you one more cool thing about Foundry so let's go ahead and create another little contracts and we'll call this one cheat codes that's all and cheap codes are really bold so it will be the super simple contribe again as we have this contract called cheat codes which stores a number and a last time stamp and it has one function called set number which takes saying a parameter new number and it just requires that the current block timestamp is greater than the last tiny stem Plus 120. so this basically means that get out I'll set number is thing called at least two minutes after last time so let's block the tank stand for currents the bank step in seconds so we're saying that the current step is greater than the last penny stand plus 122nd so two minutes um and then if that is true then the update number equals new number and these at last time stamp equals laptop time stamp okay again a simplified example but you in playing those things like the count the com file and the governance mechanism or like time block related things where certain functions an old lady call in certain type intervals very useful feature do have generally on a smart contract but can be a pain in the ass when you're testing for it how do you test for it you don't want your tests to wait for two minutes just because your function cannot be called again uh until ideally you want to do some sort of happy things that are out there and make it delete that could be dead set the past and this is where cheap boats come in so we'll create a test for this we'll call this speed product of soul and cheat codes dot P dot solo what we're going to do actually let me pull up this out so I'll set up a basic window replacement same as before on Brad keep posts test this test Imports the standard testing Library add import speech feed solidity file so it will take a reference to the gpug smart Cloud branch and in our set of content uh we'll just deploy the cheat code slot Quantum credit and what we will also do uh actually actually this is blind burnout so we'll deploy the cheat code slotband Pro well when the sentence is deploying well this is just deploying initially uh initially last time step equals zero radius that's a default value per unit in solidity this is equals to zero uh one thing you have to note is when pests are being run they're being run in sort of a stimulated EDM environment right and initially when your tests start running your blog.t timestamp is also equal to zero it is not connected to a real Network it's equal to zero initially uh so in that case if we just try calling set number right now um can somebody tell me what are cheap posts yeah we're getting to we'll get into it so right now seat belt is just the name of this Pawn cracks and I'm going to get into what boundary take that was actually I guess but so like if we have a test something like test set number and we just knew cheap dot set number five right now this test will fail and why will this test fail because when the test starts running blocked up timestamp is going to be zero and zero is not greater than zero plus 120 initially so this test right now as it is will fail and we can see that if I just do fours test once more uh uh this is the Miracast but she's she's going to pass over here uh test set number field with the reason error right and that is the DSL in the um and they require segment over here so apparently this test is failing only is zero is not greater than 0 Plus 120. um two things to note first thing you can actually create failing tests in primary so you can expect a certain textbook bail and that is okay so the way to do that is to change the name from ask set number to test fail set number so this will tell binary we want this test to fill and that's expected Behavior so now if I run file rate test1 smart oops Yeah I better run find request lots more you'll see everything passed everything is good it expected that has to build and that's perfectly fine but now what I'd say we want to call the set number function once again so create another test set number uh like and we do list that number again and this runs into the same problem block paint stamp has a moved forward by two minutes this is where value cheat codes come in so probably has a bunch of two colors they were basically things that allow you to alter the state of your execution environment they allow you to change things in the EDM or Alby Pawn brackets became a sort of website it's called a cheap code these things do not work on a real Italian Network they only work within The Foundry sort of environment and they're meant to make their testing easier and faster right specifically in this case what we want to do is there is a cheat code called and Chico's by the word called by em Dot cheat code name so VM is something that's built into the standard library for ports and it's kind of like the the virtual machine the EDM that you're making direct SQ code calls to it so you study vm.

word uh 150 let's say and the worksheet code what this does worksheet code increases block dot kind stamp by whatever value you tell it to so let me do vm.org 150 it's been a little block the paint stamp to 150 and then call the set number function so our tests will immediately pass another real ethereum Network it's the same thing as actually waiting for two minutes to go by you can see this time nothing failed this time speeds both of the tests passed over here this is not the only cheap code that finally as available to you there are actually a bunch of cheap those that are really full uh let me show you the list and there are a bunch of cheat codes we don't have time to go through all of them but warp is one of the first ones you see here sets the block time stamp to whatever you wanted to uh you can change the block difficulty even change the block number you can see it's the block coinbase you can change a whole bunch of things uh my favorite one has to be prank where you can pick name as a different address even if you don't have a private key for it it's really useful in case it look things like if you're testing something against an audit last slow and you need money to pay back the flash load I just prank uh some mail somewhere and just pay 10 million dies from them and do the Audi flashlight is pretty cool but they have a bunch of like cheap codes you can use uh you can change a lot about the ebm within your testing environment which makes things easier um last thing before we head out for almost that time is a couple person is how do we use all these other libraries of it I want to use open sampling contracts you know I want to use Soul like I want to do all these things open settling upon Cracks by default were designed for heart not they were designed for Foundry but finally supports them that you you have to do something called we mappings and let's say you wanted to create an nft collection so what you do is you type boards install um open zablin slash opens upload quantrex which is their GitHub repo is the GitHub organization remote and what this is going to do well and so it downloaded so you get clone the repo into your projects and specifically it's going to put it in the little folder next to the poor standard Library um if you notice over here you know how we're able to do import for standard Library slash has stopped Soul so basically you can import things from your lib folder including opens Upland contracts and you can also change how these Imports work um let me just say so it Parts comes with this thing called remappbase by default it has support for three reboundings which is the port standard Library opens Upland contracts and Bs test so what this basically means is typically if you have a pawn cracked over here let's say however dot solve and if I had to import from the lip folder it will typically look something like this I'm in the SRC directory it's like go back and going to live and build click open the blink on France and the yada yada yada whatever since the query playing does a little advice rebap beans allows you to pay to remap those tags so your Imports can look clay uh it comes with the open the blink contract speed map built-in so instead of typing Libs Lots open Zeppelin contracts I can just do import open that Lit upon products slash whatever so if I have an e dot Soul over there all right then just import it like that import open Zeppelin contract slides and forwards will figure out because of remappings that it's supposed to grab it for the link slash open ziplin Quant rights and whatever and you can see this if I look forward still it's a build without any issues there we go you can also have custom remapping so if you play this to remapping then you output it to a file all remappings.pht then you can now create your old remapping for example for a library that's not supported by default like if you're cloning the audio repo or the uni slot repo or whatever you can build your own remappings for random reader but as an example let's say I want to create a remapping called VRC 721 slash which equals to lid slash open set of land on cracks slash 12 Bill slash bi sleeps on 21. with this remapping I can change my import to just the UFC 721 lives erc721. so as it takes me directly into that specific folder where I need to go and now again if I reports build uh oops build the result file something went wrong so they probably all live uh oops oh you guys have found a while equals lib I messed something up over here open that one point right oops oh yeah it makes somebody that's popular slash slash token slash Style um and see it works perfectly wide so yeah um that is all I want to do cover about find Rick today bunch of cool so we cover bus testing we cover cheap codes or remappings and imports it's obviously pretty fast like on file is have been taking less than one second to finish uh on hard hack this will generally take decently longer and yeah I'll take a look that's happened now for any other questions Oops I did not need instruction by sweet as MacBook I so let's go back to the slide back and there we go so yeah guys uh yeah so that is that thank you for listening um let's take a look at Chad yeah if you want to learn more about bullying it but we've done all this learning about be General hit us up at learn level three uh at learn what we got ideal or find us on Twitter and Discord but we're always there if you have any questions um so three mapping raises some errors did not find the file um you have to create a remapping stock txd Pile in the root of your project you can either build that manually or you can run it forwards remapping flash email address dot DLC to input it directly over there I did not use emacs I am only a scholar plan I don't know foreign if any depends on your background if you already know jalisprit and you're just getting started in the space and you're only making like small projects uh hard at is probably easier because you already have that knowledge but there will come a point in larger projects where harder starts getting a little bit annoying and changing between data types or like solidity and JavaScript and get a little bit tedious they have a constantly convert data types back and forth um at this point doing file three would be better however you know there's nothing stopping you from just starting off at fundry at most you'll learn some even more solidity um with that point we are installed fails are you on Windows or Linux or Mac OS or whatever are you getting sure um and we expect a Divine reason on the test field so actually what you can do is you can log things uh I did not show that but let me open that so when you are creating the either when you play them like test files you can log uh they have a bunch of like logging helpers in the standard Library so you can do stuff like long address for you and or like long numbers or spring or long underscore address whatever it may be and if you run it you need to run it with the verbose mode so if you just do like force test these logs will not sell but if you do like boards test last week where both I would put it will tell you uh it will sell you all these loves and regarding ex defining specific reasons specifically for asserts uh what you can do over there is if you look at all with the different assert helpers that exist you know I showed you a certain equals uh there's a bunch of other uh other ones but you can optionally provide a string I don't know if this is very readable but you can absolutely provide a spring with the two arguments for assert equals or any of the other asserts which will be the error that shows up if uh if the nation happens yes laundry wasn't an interest all previous vote solidity developer extensions I think I just used one really which I believe is just for visual solidity developer I believe that's what it's called this one that's pretty much the only things I use I used to use some of the other AD extensions but um there's a lot of covers most of what I need um Nicole Silas slate that's pretty much all the questions better not been missed anything but yeah thanks everyone for over time to roreal you know back to you as yeah check this out at learn Web video if you have any questions really terrible we'll get back to you cheers yeah cheers thanks so much for joining us today great presentation and uh yeah that's hardly excited to reach out if you have any questions um but yeah awesome cheers thank you all so much thank you for the late foreign

Automatic transcript — names and jargon may be misspelled.