Solidity Development with Foundry: Cast, Anvil, Chisel, and Forge
Solidity development with Forge · 30 Aug 2023 · 1:09:19
Christian Koopmann gives an introduction to the components of Foundry, the Solidity development toolkit, covering Cast, Anvil, Chisel and Forge with a focus on Forge. Useful for developers who want to start building and testing smart contracts with Foundry.
Speakers
Topics
From Solidity development with Forge, hosted by Ethereum Engineering Group.
Transcript
Hello and welcome everyone. My name is Peter Robinson and today I've got Christian on the line who's going to tell us all about Forge and related tools. So Christian, why don't you introduce yourself before we start? Uh yes, sure. It's actually um one of my first slides. So uh um can I just go ahead and share my slides? Yeah, why not? Why not? Can you see my slides and hear me well? Uh yes. Yeah, all right. So um yes, a little bit about me. I'm a uh long-time listener, first-time caller, so to speak, of the show.
Um and uh yeah, generally uh got into smart contract development during the COVID lockdown. And um yeah, I've been doing uh pretty much uh nothing else since then. Um I'm a um open-source enthusiast as well. So I try to give back give back a little bit where I can. And um yeah, since uh since pretty early in the in the Foundry project, I'm a I'm a big fan, a heavy user, and um even occasional contributor. So I am uh yeah, super excited to be able to share a little bit about my um my enthusiasm and and what I know about the the project uh with you guys. And um yeah, if uh if you have any questions, corrections, uh anything
else, uh feel free to uh contact me on Telegram. Uh and if you want to see what I'm up to, uh you can also check out my GitHub account. Um and so without further ado, um I want to talk a little bit about Foundry. Um first uh to to kick off, um what is Foundry? Foundry is a uh smart contract development tool kit. So um kind of similar uh to tools like Hardhat or Truffle.
Um but it does uh it does a few things differently, uh which hopefully I'm I'm going to show today. It is a um as far as I know, it's a an extended port of a previous project called Dapp Tools. Uh so if you've heard about that, you'll see that the interface uh and the philosophy behind it is very similar. Um it is implemented in Rust, uh which makes it very very fast. Um and yeah, just as a as a side note, it's a great project also to get involved if you want to do some Rust open-source work. They have a an amazing community uh and really welcome new contributors.
Um and yeah, so it's also a a great chance uh to learn some some Rust. Um and uh generally it it consists of four components. Uh so a lot of the content out there about Foundry um really focuses very heavily on Forge, um which is kind of the main testing uh framework um and compilation and scripting. Uh but it's actually it also has three other parts, um which uh are very yeah, powerful tools in their own right.
Um and today I want to give a bit of an overview of all of it. Um and uh then dive a bit deeper into Forge. So that's going to be the structure of this talk. Um we're going to go through the three other tools, namely Cast, Anvil, and Chisel, uh really quick and just kind of tease what they're about and and what you can use them for. And then the rest of the talk we're going to look into Forge, into uh mostly into testing, um and then also a little bit into uh scripting.
And um yeah, so the first tool that I want to talk about in the um in the Foundry tool kit is Cast. Uh oh, sorry, no. Uh first first we're going to going to obviously have to uh say a few sentences about uh how to get started. So in order to uh to use Foundry, because it's unlike Hardhat, uh it's not a uh JavaScript framework, and so you cannot install it with the npm or yarn, which you might be used to. Instead, they have their own installer called Foundryup. And so the first command here basically downloads uh that installer and uh initializes it. And then you will have in your terminal you
will have uh uh or in your path you will have this Foundryup command, and you can use that when installing um Foundry for the first time, and also to manage uh versions, uh upgrade, downgrade, uh all that kind of stuff. Um and um yeah, once you have installed uh Foundry through Foundryup, you will have uh all the four tool kits that I said before, so Forge, Cast, Anvil, and Chisel will be their own like kind of commands in the command line, uh which you will then use to um to basically leverage this uh these tools.
And yes, the first one uh is Cast. Uh Cast is a kind of tool uh that allows you to uh to do all kinds of cool stuff when interacting with uh Ethereum or any uh blockchain. Uh and so it's kind of for these ad hoc things, uh like you want to uh get some data on a on a block, on a transaction, on an address. You want to make a call to a contract, execute a transaction. You can read specific storage values.
You can all kind You can do all kinds of encoding and decoding call call data. Uh and uh a lot more, really. So it's it's a great tool for for debugging uh the state of um of any kind of chain or node, um both like the actual chain, but also if you have a local uh local test node and and you want to look at what happened there, it's it's really great tool. Um and uh again, it has a huge amount of commands. If you uh you can use the help command to see all of them.
Uh I'll just show two right now, which are really for me have been uh have been great uh yeah, productivity enhancers. Uh and uh yeah, have have uh have really helped me a lot. So one example of something cool you can do with Cast is called Cast Interface. Um and so if you if you run the command Cast Interface and then the address of a contract, it kind of generates automatically a Solidity interface file for you.
Uh so I don't know about you guys, but uh sometimes when I'm working uh on a smart contract and I'm integrating a third contract, uh what I have to do is look into their source code, copy-paste the function um the function signatures that I'm using, and then deleting the function body and all that kind of uh manual, quite tedious stuff to generate this type of interface. Um and basically Cast uh automates all of this for you. Uh and it makes sure that you actually have all of the functions of all the inherited contracts in your interface uh definition. Uh which is great. Um the way it does that, uh as far as I know,
it uses uh like Etherscan um to get the contract's ABI and then generate this. So this will most likely only work for contracts that are verified on Etherscan or a part of what you're developing locally. Um but uh yeah, those those uh most I think most most cases uh that would be the case anyway. Um and yeah, this also works with other chains. Then you have to like give it a custom uh Etherscan URL. Um but yeah, this is this is uh like really a neat little trick that uh saved me a lot of time already.
And then the second one uh is called Cast Run. So Cast Run and and this is really, to be honest, even just for this one command, I think it's worth installing Foundry for. Anyone I've shown this uh has been has told me that uh this is was a really game-changer for them. And what it allows you to do is basically um uh kind of it's it's really good for debugging um transactions. So uh what it will do is it will uh resimulate a a given transaction um on a local EVM. So it will uh kind of fork uh the chain uh just just prior to
that transaction, and then it will in a local EVM rerun the whole transaction and give you a whole um trace of um all the external calls that were called, uh errors. Uh it gives you gas um gas usage. It shows you when there were delegate calls, so you can easily understand uh when there might be a proxy involved. It's really good at error tracing. Uh so you rarely get the old, I don't know, reverted without reason or whatever, uh that you might have that have has frustrated me a lot in the past. Uh if it runs out of gas, it tells you it ran out of gas.
Um and all these kind of things. So it's really really good uh at finding um quite often what went wrong, or just generally understanding it. Um and it even like all these tools, it can be run against a a local uh node. So the scenario where I find myself using this the most is actually when I have a project where I'm using hard hat and I have some kind of error in my tests and I'm not quite happy with the with the traces in in hard hat. It doesn't give me enough detail. I don't quite understand what went wrong. I can run this command and get a whole more detailed view on the failed transaction which is really really great.
And yeah, if you want to go really really deep, you add the dash dash debug flag and then it will even open a kind of interactive debugger, EVM debugger, so you can go through the transaction opcode by opcode and yeah, understand what went wrong and yeah, it's it's I mean this is this is a more advanced tool but even even without the debug flag it it helps me find find the error in I would say four out of five cases.
So that was cast or just a small subset of what cast can do. The second tool is is anvil. Anvil is really just kind of hard hat node but faster. So basically it runs a local yeah, a local node that you can run tests against. You have kind of unlimited ETH in that local node. It has all the features that you used to so you can fork and you can fork the the main mainnet at a specific block number and all that kind of stuff.
So in terms of yeah, in terms of functionality it's really pretty much as far as I know exactly the same but it's just a lot faster. So um yeah, even even just swapping your your hard hat node with anvil can can really speed up your your test execution or your CI and due to the kind of because the RPC interface is the same, you can use use these these different you can use it pretty much interchangeably with hard hat node or with the truffle ganache or these tools.
Just faster. And the last one before we go to the testing is called chisel. This tool to be honest, I haven't really used in my day-to-day work yet. I looked into this in preparation to this talk. It's kind of yeah, it's really even mentioned when people talk about foundry as far as I know but it's it's quite neat in my experience in it in preparation. I found it quite cool and what it is is basically a REPL so a read evaluate print loop for solidity and REPL is pretty much the same that happens when you just type
python or node in your in your terminal. So you can do a kind of interactive programming where you type in each command and you can immediately see each variable's value and do all kinds of tests and here you can do all of that in solidity here also you have access to pretty much the whole solidity syntax. You can call other contracts. As you can see up there, you can specify specific block number and then the code will be executed as if it is a transaction at the beginning of that block.
And so yeah, I could see this also being very useful for some iterative development or some debugging. There's yeah, so before we go on to the main part which is about the testing, does anyone have a question about these tools? Or about foundry in general? I think there are a few questions in the chat. Yeah sure.
You want to read them out maybe? Yeah, yeah. So um I'll I'll go to Eric Bengar's question. Can it be used to run integration tests? So this was the cast run. So cast run basically just re-runs a an existing transaction. So it it re-runs a transaction that has been submitted and included in the blockchain already. For integration tests, we'll look later at forge which is the testing tool for both unit and integration tests.
So yeah, this is this is mainly mostly for re-running transaction but if you have an integration test on your local node running and it fails, then you can use cast run to debug that that integration test and maybe find out where it went wrong. Yeah. Yes, so so that that value there that 0x1ACFF is the what the transaction hash I guess. Yeah okay. So Dev asked and I think they may have misunderstood. You had mentioned that it decoded decode the function details even software source code is not verified and I think you were saying you thought
it had to be verified for it to be No, actually I forgot to mention this because it's really cool. Of course as first I mean I didn't fully look into the implementation and might have changed but my understanding is such that it first checks if the contract is verified on on etherscan or or any other explorer and then it will use that but it has a fallback and it use something called the four byte registry. This is like an online repository of of function selectors.
And it will if if the function selector is in this four byte registry, it can decode a function even if it's if the contract is not verified on etherscan. So obviously it it cannot like it won't work for for any for for all of them but in many cases yes, it can even decode unverified contracts. Okay, right then. Yeah, that makes sense. Yeah, the other one was a comment. So I don't have any questions. Does anyone else have any questions?
All right then. Yeah, go ahead. Question. Yeah, so then the next topic and the main tool in the in the foundry tool kit that we're going to talk to going to talk about is forge and forge is yeah, what what sometimes people even use forge and foundry like interchangeably when they're really just talking about forge. And it's it's the kind of it's the tool that contains the the testing, the deployment, the contract compilation, managing your solidity project. So it's really like the the core tool that you're using when you're when you're developing a
smart contract. And so in that sense, it's kind of similar to functionality of things like hard hat but it has a has a bunch of differences and the main difference is that everything or pretty much everything you'll be writing is in solidity. So the tests are in solidity, the scripts in solidity. Of course the contracts that you're working on are usually I mean can be in viper but usually also in solidity. So in most cases you will have no no context switching because you're doing everything in solidity.
And then it's also as as before it's it's very very fast and because you're doing everything in solidity and in a smart contract, there's a lot less boilerplate code when when interacting with the chain and yeah, also it has these improved error traces what we showed what we looked at earlier with um with the cast run, these kind of detailed traces you have in a lot of places in in forge in your tests and everything.
And then it also has some really cool advanced testing features that go beyond what you would normally do in in in the existing tool kits and those are fuzzing and invariant tests and we're going to talk about those later as well. And so basically you can do everything and more that you could do with existing tool kit and you're going to be a lot faster. Um and again, when you have installed foundry, you will have the forge command in your in your path and so you usually start by setting up a project using the forge
init command. And what that will do is it will create a kind of a template project and with with all the files you need so it contains a an example contract. It's the it's the standard like counter example where you can increment a number and then it also contains some example tests and an example script. Uh you can see that all of these end in SOL because, as I said before, everything is is written in Solidity.
Uh it contains a configuration file. Uh I'm not going to go in too much into the configuration file, but it's kind of it's got pretty sane defaults, but you can you can you can pretty much change anything in there if you want to. So, you can change the uh RPC URL, the block number, you can change uh the compiler version, all that kind of stuff. Um and then it also has this lib folder where you find the dependencies.
And because Forge is again it's it's not a JavaScript project, so we're not it cannot use like your standard JavaScript package managers to manage dependencies and libraries. And so, it has kind of its own system, uh which is based on a Git submodule, um uh which is kind of a bit of an advanced Git feature, but basically allows you to to quickly install any any dependency that is on Git. So, it doesn't have to be on any like NPM or anywhere.
You just say Forge install and then kind of the GitHub repo name and owner. And then it will um it will basically just just download that repository. Um and kind of link the files such that you can then import it import the contracts elsewhere. And yeah, so everything is in Solidity including the the tests. So, this is the very very simple test slightly adjusted from the from the template example. Um and to create a test, all you need to do is first you need to uh create a contract. As usual, everything in Solidity and so everything also in these tests and scripts needs to
be wrapped in a in a contract definition. Uh you inherit from this test contract, uh which is provided by Forge and which gives you access to all kinds of assertion functions and all kinds of tools that you need for your tests. Um and then yeah, you have a setup function that is kind of run before every single test. So, it's equivalent to before each in the JavaScript setup. Uh so, yeah, this function is is run again before each test, so you can have a clean setup for for every test.
And then Forge will recognize recognize as a test any public function on this contract that is that starts with the word test. So, yeah, that's that's how you kind of tell Forge run this as a test. Um and then the you have a a variety of of different functions from from the inherited test contract such as assertions like we do here. So, this is a very simple test where we just increment the the counter and then we check that it's the number is one afterwards.
Um and yeah, so this is this is basically the the most basic test setup you can have really uh in Forge. Um and once you have defined your test, uh you can run it with Forge test. Uh as usual, there are a whole bunch of different arguments or like parameters that you can pass to specify how these tests are run. So, you can use regex expressions to only run specific tests.
You can run them against specific block numbers, all kinds of stuff. You can make it such that on a failure you you enter the debugger that I showed earlier. Uh but normally most of those you don't need. What's really good to set is the verbosity. So, it's from from level one to five. So, in here in this case, dash VVV means we have verbosity level three, which means that we get the the traces on every failed test.
And so, here I kind of adjusted the test a little bit to to have a failing test just to show what it looks like. And yeah, again you get the uh get the same kind of really detailed traces that you also got in the cast run argument uh that can really help you debug what went wrong in your test. Um and also here in the screenshot you will see how fast it is. So, this is 794 microseconds, so less than 1 millisecond that it took for this test to run.
Um and yeah, it scales pretty well as well. So, it's it's really very fast. Um And yeah, now any questions regarding how to set Forge up, how to initialize your project, how to run a basic test? Or anything else really? If not, then I guess we'll proceed. Um so, this is obviously this was a very very basic example and in many cases in your tests, you actually want to do a little bit more.
You don't just want to uh have these like basic assertions, but quite often you need to do things like oh, I want to check that maybe only the owner can call a specific function or something else. So, you in in in many cases you want to check that certain things don't work under certain uh conditions. So, you want to basically check for reversions. Uh and this is something where maybe you would think oh, I only have the normal Solidity syntax at my fingertips, it would be pretty hard to do that. Um but Foundry has has got you covered with that. So, uh
there are two ways of of having a test that kind of checks for for a for a reversion or a failure. Uh the first a little bit more crude example is to just call add the word fail to your to your test name. So, if it's test fail then Forge will run this test and it will expect there to be a reversion anywhere in that test. Uh and so, if there is a reversion in that test, it will be green. And if this this function runs without any reversion, then then Forge will complain.
Um but yeah, I would say the somewhat better way to do it is to use the expect revert function that also comes with this test test contract and that allows you to check for a specific uh for a specific reversion, so a specific reason error in the very next call. So, here in this case, we are checking for an arithmetic underflow error in the decrement function, so in this last test.
Um and normally in this expect revert function, you would just type in as a string the the reason that you expect. Um in this case, uh it's this this underflow error is a Solidity compiler level error, so it's it's not an error reason that we define ourselves. And so, for this for this case, there is this standard error library that Forge also provides that contains the the the the error data for all these kind of compiler level errors um that is quite handy if you want to check for these kind of
errors. But yeah, normally if if you have if you have an error you define yourself, you just type in your error message there. Um and this is actually the first example of what is called cheat codes in Foundry. So, uh this vm.expectRevert uh is a quote unquote cheat code. Um and cheat codes are these kind of functions that are added by Foundry that extend the normal Solidity syntax to allow you to do all kinds of quote unquote fancy stuff that you might want to do in your tests, but you you normally cannot do in uh on Ethereum. So,
using these cheat codes, you can control the message sender, so you can you can check for example your access control. You can control the block number, the block time, really anything about the state of the of the blockchain at the point of the test. You can check for reversions, what we just looked at. You can check for event emissions, which we're going to look at next. You can interact with things outside of the EVM such as your file system, your environment variables, your CLI commands, and a lot more. So, quite often when you come to a point where you think I probably can't cannot do this with Foundry, they'll more likely than not there will be a cheat code or a combination of
these cheat codes that let let you do what you want to do in your test. And yeah, another cheat code that is quite useful during test is this expect emit cheat code. And so what this allows you is to test that a certain event has been emitted. So up here we see in the top we see a snippet of the implementation of the contract that we're testing. And it's still the standard counter contract but here we added like just a little like just emitting an event when we increment the number.
And now below is the test that checks that the correct event was emitted. And this to be honest is a little bit more complex maybe in in the foundry case so you have to do a few more steps. You have to kind of copy paste the event definition into your test. Then you have to call the expect emit cheat code and you have to tell it which which parameters of the event you want to check for in your test. So in this case our our event has just one indexed index parameter so we set the first flag to true and all the other ones to false.
But normally yeah the first three flags um refer to the maximum three indexed parameters of an event and the last one to the to the rest of the data. So here here you kind of just here you kind of tell foundry which parts of the event you want to kind of match and and check against. And then what you also have to do is you have to emit in your test you have to emit the same event that you expect to be emitted by your implementation.
So you have another like emit with this event and the the parameters that you expect and then you call the function under test and forge or foundry will will test that in that in that call the same the same event was emitted that you emitted just just before. So this is kind of how you um how you um how you check for events. It's actually I would say it's the most complicated kind of cheat code in in uh in in forge and foundry.
Um but yeah it's it's how you how you do it. Um so Yeah and then another cheat code so again here we're just giving a few examples. There are a lot more um but another very useful one is impersonating an account. So I mentioned earlier you might have a have a contract where you have some access control. So in this case I have slightly extended the uh the counter contract to make it such that only the owner which is the account that deployed the contract can
can actually call these these methods and if if anyone else tries to call the method they get an error. And then below we see the test to kind of check for that. Again we use the expect reverts function to say okay in this in this in the next call we we expect there to be this this reversion. And then also we use this vm.prank vm.prank cheat code that allows you to set the message sender for the next call to any address you want. So here we're going to call the counter the contract from the zero address.
And we expect there to be this error. And so so this this test would work. And it's it's yeah another one very frequently used scenario in in testing. But this is an example where you have to kind of so there are some subtleties when using these cheat codes that you kind of have to get used to. So this is this is a common pitfall at least for me it was a common pitfall that I um that I ran into many times.
And want to see if if maybe you can see um what what goes wrong here. So this this example does not work. We have only slightly changed the changed the test you can see. The only difference we did was instead of using the increment function we're using the set number function to kind of achieve the same goal. And again we're calling it from like we want to call it from the zero address.
But this time it doesn't work. So it says the call did not revert as expected. And the question is why. Does anyone here maybe have an idea why this example doesn't work? I think I know but in fact I'll put it in the chat but is it because the counter.number is the next call? Yes that is correct. So um counter.number is the next call so what forge will do found will it will impersonate the zero address when calling the number function. But then when we actually call set number
we're using the original account again which was the one that deployed the contract and so there will be no reversion. And for that case you have that's why I usually prefer to use a function called start prank and stop prank. And in that this case it will impersonate all calls in between those two cheat codes. And so in this case we're also impersonating the dot number call. However this still doesn't work and this was actually when I was when I was preparing the the test the talk actually had this iteration and I was wondering
why this still doesn't work. Does anyone have an idea why this still doesn't work? Wait to see if anyone else has got it. I know it. But I guess I've used forge so I've sort of cheated. That's all right. Yeah it's it's the vm.expect revert isn't it? Is now looking at count.number and it's saying it didn't revert. Yeah. So it's kind of the same same error again but this time with the expect revert instead of the prank. So yeah this this is a working example. So yeah in this case we really didn't have cuz I
there's there's no equivalent of start prank stop prank for expect revert so we didn't really have an any we kind of have to factor out the counter.number call. Um Um and yeah I mean in this case we could just use prank again. Um in between expect revert and set number but I still kept it at start prank stop prank. And yeah so this is this is the example where that works. And so this is just kind of shows you that with some of these cheat codes you really have to pay attention especially when thinking about okay what is actually the next call what that I'm expecting a reversion for that I'm expecting an event from. And this is a very in my in my case a common
kind of tripwire. But yeah once once you get used to it you're usually able to debug it as quite quickly as Peter just did. Yeah. And another handy tool that uh you might be used not just from smart contract development but really from any kind of development is you want to debug your contract and the first tool usually is just starting to log stuff out. So your good old trusty console.log and yeah you'll be happy to know that uh forge has you covered for this as well.
So you have the you have this console.sol library that you import in your implementation. So here the code is the implementation itself cuz we want to log something out from the from the contract that we're developing on. And then you can use these console.log functions and print out messages. Of course again in solidity everything is very strictly typed so they have they have sometimes they have different log functions for different types and stuff so you got to be a bit careful and and but generally it's it's a once yeah once you use it once or twice it's kind of the same
that you used to maybe from JavaScript any other library and then it's yeah for me the first tool to go to when debugging something. And you can see on the top that the log message is then included in your in your test output. And yeah so this is kind of introduction to kind of basic testing. So far we've we've only like we've talked about basically replicating a lot of the functionality of of maybe what you're used to in your old toolkit. Um Uh and next I want to talk a little bit about advanced testing, but before this uh are there any other questions
regarding uh what I just showed? Um So, Abdurahman has put a question in the chat. I'll read it out. It is um a a question regarding Forge. How can we get off-chain non-solidity data for the test? Say real-time API call. So, real-life example, writing integration test for a smart contract integration where we fork network at latest block, call off-chain APIs, for example, 1 inch and some other bridge.
Build transaction call data based on both of the two last APIs calls and the other parameters. So, is there a way of like integrating off-chain stuff into a call? Yeah, I mean in this case, honestly, it's probably going to be a bit more hacky than what you do if you have a JavaScript base library cuz but there are as I said before, there are a lot of cheat codes to interact with with both the file system and the the console, so you can run any arbitrary um uh command in your CLI so in your terminal basically, and then you can
also what you can also do is read in uh any JSON um JSON data, for example, there's a there's a cheat code to read in a JSON file from the file system. And so what you could do is you could uh run I don't know the the curl command to to call an API uh and then uh save the uh save the uh resulting payloads on your file system, and then you can use another cheat code to read in um a uh that file and even get like a specific uh JSON object or JSON uh parameter out of it. Um but yeah, it's it's definitely a bit more hacky than
what you'll be doing in in JavaScript. And of course, it still has some some limitations because you are still in Solidity. So, anything you save in a um in a fair in a variable has to be of some Solidity type. So, uh there's kind of a limit uh of it it can be a bit bit hacky regarding that. Um but uh for example, if you want to use an aggregator API that might return some call data, uh you should be able to do that using this kind of workaround uh and then just reading in the call data from the file system um and uh yeah, doing that.
But so, yeah, very good question. Um and something that um yeah, I've also sometimes struggled with. It's yeah. Great question. Any other any other questions? Right. Okay, then um yeah, let's go next to uh a little bit more like advanced testing. Uh so, looking at two features here uh that you normally don't find in uh in your standard uh Hardhat test uh toolkit. Um although you might be able to implement them there, but uh as far as I know, they're not they don't come out of the box, whereas in Solidity,
uh they do, and they're really quite powerful and quite performing. And those are fuzzing and invariant tests. And uh both of you allow you really to take your testing to the next level in terms of uh like the amount of tests you run, so you really get a lot of extra testing power for just uh some very minor changes in your testing code. And so, the first one is fuzzing. And what this will do, it is it will run your test uh over a large uh set of different inputs. So, what you do here is you just add one or more argument to your test function.
And then um Forge will randomize uh inputs. It will generate a lot of random inputs for that argument or for multiple arguments. And it will run uh it will run your test uh for every single uh random input. Um and uh if any of those fails, then um the test will fail, and it will show you uh what the input was for which it failed. So, here we're doing a very simple test where you where we're just uh using the set number function and we're subtracting one from it. So, here we're quite obviously going to get an error if if we run this test with the number zero uh cuz it's it'll be an underflow. And
this is what the what Forge shows us shows us below as well. So, um you have to kind of learn how to how to read some of these messages, but if you if you look at the green sticker, you'll see that it shows you the arguments for which it failed. And in this case, it found it very quickly, so it ran only 10 times. Um but yeah, again, it's very fast, and you can configure the number of of random um uh numbers that it tests, so number of runs basically for your function. So, you can have thousands or even tens of thousands of iterations of with different random values.
And so, you can really get a lot of um coverage. Um they're not 100% random if you think about this. Uh like there are two to the 256 different U ints, so it's quite a coincidence that this test found the value zero. Um But uh yeah, I think it it probably checks the uh checks the ranges of of the of the values first uh and then does does the random numbers afterwards or something like this. Um but yeah, if if your if your if if your if your number zero, it will always always find this very quickly.
Um but yeah, it's in in most cases, it's still random. Um and that's fuzzing. Um The second one is uh invariant testing. And invariant testing is in some ways even more powerful. Um and you have to do even less, and you get even more testing. Because all you have to do in invariant testing is you define an invariant, an expectation uh in your test, and then Forge will try to run all kinds of different uh calls against your contract uh to try to break your your invariant. So, it will uh call all kinds of different functions from different senders with different
values, everything again randomized uh until it finds a combination of calls uh that leads to there being any um reversion in that test. Uh so, here in this example, the invariant basically that uh the number should always be even of our counter, uh which is obviously not the case, and uh it was yeah, uh Forge found a way to break it. So, basically, it first set the number to zero, and then in a second call, it set the number to one, and at that point, it wasn't uh it wasn't even anymore, and uh it shows you here the whole uh whole um set of calls it did. You can also see that it called both functions from different senders.
Um so, it it randomizes really kind of every aspect of it. Um it can be very powerful. Um sometimes in these cases, you want to uh kind of guide it a little bit to uh to make only call specific functions. So, maybe you have a test where um for example, if you have a a a contract that has tens of different functions, of course, the uh uh like the number of random runs that uh Foundry will do and the kind of scenarios it will try is limited. Again, it's something you can configure, but so, sometimes if you want to really get the best out of it, and you already know
that uh there's only like certain kind of functions that uh that make sense to be called in that scenario, then you can tell Foundry uh to only call these functions or these contracts. Um so, by default, it will try any function on any of the contracts that you defined in your in your test or in your setup function. Um but you can really have very fine-grained control. So, in this example, we're telling uh we're telling Foundry basically to only call the increment and decrement functions on the counter uh contract.
And uh yeah, there's a little bit of boilerplate here. You have to use this fuzz selector uh struct, which is defined by Foundry, and then this target selector function, all this. Um but yeah, this is really just what it does is is limiting the uh uh the kind of uh like uh the scenarios that Foundry will will try out when when doing this invariant testing. Uh and so, yeah, you can have really fine-grained control in very advanced scenarios for this. You can have multiple contracts that it's allowed to call if you're testing a whole system.
Um and yeah, again, it's a very powerful feature. Um And yeah, this is kind of a little bit of a uh view on on some of these advanced testing features. Are there any questions regarding fuzz testing or invariant testing? All right. Guess not. Um okay yeah.
Everything everything you're saying is obviously very clear. All right, thank you. Yeah uh um, all right, there will be a quiz at the end. I'm just kidding. Um, okay, yeah, so so far about testing, uh, again, normally testing is is what people talk mostly about when talking about Foundry and Forge, but I also want to uh, show a little bit about the features that are often a bit underrepresented or underrated in my in my opinion of Forge. And so, um, another tool that you have when using Forge, uh, instead of in apart from testing is also scripting.
So, scripting scripts are basically, uh, yeah, things like programs that usually, uh, you're not just doing a test, but you actually want to uh, submit some transaction to the blockchain. So, often this can be a deployment script, it can be some kind of configuration script, all that kind of stuff. But yeah, the difference to a test is really that you're actually, uh, submitting uh, transactions to the blockchain. Uh, and uh, Forge has, um, I think really a really good implementation of this. Again, it's completely in Solidity as we'll see in a moment. So, the scripts are written in Solidity.
Uh and uh, it it's it's it really has some advantages, uh, and uh, one one really big advantage is that it kind of what it does is it simulates your whole script on a local EVM before broadcasting any transa- transactions. So, what that means is, uh, let's say you have a script with 10 different calls, um, before it sends out anything, uh, to the mempool, it uh, it creates a local EVM fork of the blockchain, it runs your whole script, and sees that no calls revert, uh, that you don't run out of gas, all that kind of stuff, and only once it ran
through the whole, uh, simulation, it starts broadcasting the transactions one by one. Um, and this protects you from, uh, something that I I have experienced sometimes in the past is where you have a script and then in the middle of the script, um, I don't know, something goes wrong. You run out of gas, uh, a a call reverts, uh, anything, and then you're in this, uh, weird state where your script ran halfway through and, uh, you, yeah, you you have to do kind of all kinds of gymnastics to recover from that. And, um, this has has I don't think this is has ever really happened or very rarely, uh, in Foundry because it has this kind
of yeah, really killer feature in my opinion. And then it also has a really good management of like output files, so it keeps a lot of logs about all the transactions that you ran with which call data, and so it's really nice you can look through these files afterwards, uh, to see what what what you did. Um, and yeah, this is an example of the script. Uh, again, it's, um, like it's our counter example, it's just a deployment script. So, what we're doing here is we're going to deploy our counter contract, uh, and then we're we're just going to set the number. Uh, and um one important thing is, uh, so there's a few things you have to do instead of the test contract, you inherit from the
script contract. Um, and instead of calling your function test whatever, you just call it run. Uh, and then this will be run as a script. Uh, and there's another thing to be mindful of is that by default, even in scripts, everything is just simulated. So, if you want to have um, certain calls or certain actions actually be submitted to the transac- to the to the mempool, you have to wrap them in these start and stop broadcast function calls. So, here, uh, the only things we are we're going to submit two transactions. One is the, uh, deployment of the counter contract, and the other one is the set number call further down.
Uh, and everything else is, uh, is just simulated. Uh, in this case, everything else is is just a static call anyway, but this uh, setup allows you to really have inside of your your script, you can have really sophisticated tests. So, you can deploy something, and then you can run a couple of test transactions or what what would be transactions normally to make sure that, um, that your, uh, your contract actually works as you expect it. And this will be included in this simulation step that I mentioned earlier. So, if any of these tests fail during the simulation of your script, uh, nothing will be nothing will be submitted. So, you can really have a
lot of lot more, uh, certainty, uh, and a lot of extra testing built into into your, uh, into your scripts, uh, which is, yeah, really great. Um, and it makes this really powerful. Um, and, um, yeah, so again, also you can have assertions here. Like this script, uh, contract is gives you a lot of the you have access to a lot of the functions that we saw earlier during tests, so you can also do kind of all all kinds of complex tests, um, in your in your script combined.
And then once you're happy with your script, you can run it with a Forge script command. Um, again, you have all kinds of flags, parameters that you can set. One very important one is, uh, that even when even when you have marked certain transactions as, uh, to be broadcasted, you have to in addition add this broadcast flag to your Forge script command. Otherwise, again, Forge will only simulate. So, Forge is always trying to protect you here and always defaults to just simulating stuff, and you have to tell it specifically in multiple places that you actually want to, uh, have something executed, um, against the real chain. But this is also a nice feature, so even have when you
have a script, you can run it first without the broadcast, um, flag to kind of make extra sure that everything works and, uh, the outputs look like you expect, and then you run it again with this flag to actually execute the transactions. And then below we see like kind of the output. Um, you see the results of this like simulation that I mentioned, so it tells you in advance how much how much gas you're probably going to going to spend. And then after the transaction it sends out, uh, one, uh, one transaction after the other, and it waits for, for it to be mined and everything. Um, so, yeah, and it's it's really good also. The nonce management is really
good, so, um, I said that it's it it waits um but it it it works really well, so you never have any issues with nonce too low or some of the stuff that you sometimes can have have in, uh, in other tool sets. And, um, yeah, this is Forge scripting, um, which, uh, I also use a lot. Uh and uh yeah concludes uh my talk for today. Uh, again, this was meant as a bit of an appetizer of like showing how amazing this, uh, toolkit is.
Uh it's uh, it's got a lot lot more functions than I than I have shown today and a lot more that could than could fit in one one talk, so uh, there are amazing resources out there. Uh, the canonical resource, uh, to learn anything about Foundry is the book, uh, which you can find at at URL, which is like a really complete uh, documentation with tutorials and everything, so technically it's really all you need to learn. Uh, but then there are also, uh, included a bit more, uh, like, uh, content in other formats.
Uh, one thing I really liked is this, uh, smart contract programmer Foundry playlist, so he he did a really good uh, it's a YouTube channel, he did a really really complete Foundry course, uh, much more than I covered here, but, uh, divided into like small bite-size videos, so it's a great resource. Um, and then also like a couple of repos, uh, that you can look at. One really interesting is this Hardhat Foundry, uh, template. So, uh, you might be thinking, "Oh, Foundry sounds great, but I have a huge Hardhat project and I don't have the time to rewrite everything in Foundry."
Uh, no problem. Uh, it's got you covered. You can use those tools side by side. You need to do a little bit, um, of, um, of configuration, um, but it's really not too bad, and, uh, you can find it all in that, uh, template. And, uh, yeah, with that, thank you very much, and, um, yeah, if you have any more questions, I'm, uh, happy to take more of those. Otherwise, I'll, uh, return it back to Peter. Hey, Christian. I I did have a question, actually. Um, so, you talked a lot about, uh, testing and fuzzing, um, sort of dynamic techniques. I'm wondering, is there any interest in doing any kind of static analysis using Forge?
Sort of more static or compile time techniques. Yes. So, there is a linter. Um, I forgot what the command is, but they do have a built-in linter. Um, I'm not sure how much static analysis it does. It definitely does like looks for like, uh, decent formatting and syntax. Um, um, I think it has also some like best practices coded into it. Um, but yeah, I I I the name. I think something like Forge lint or something like this. But yeah, there's a there's a lint up for some static analysis as well. Okay, yeah. I mean it seems like sort of static analysis is kind of the next step from your sort of invariant testing basically, you know, to start looking at
some some other properties there. Yeah. Yeah. I mean there's also something else. I forgot the I think it's Is it formal verification? I forgot this this actually that next step beyond invariant testing is uh something where it actually uh analyzes like the whole tree of possible program states. Probably Peter knows what they called and it does like a formal analysis of whether whether there's any case in in your test that that will break it. Mhm. Um but I think it's not yet implemented in in forge. I think they're working on it.
Okay. Um but yeah. Okay, cool. No, David David knows an awful lot about that. Um I guess that's why I'm laughing. Interesting right? Um but yeah, look, I mean having run Slither recently in a project, it would be good if they had I don't know, a version of Slither that doesn't um essentially core dump um integrated into forge so that um yeah, cuz Slither itself I don't know, maybe it's just the configuration I'm running or something, but golly it's unreliable. Um just as a tool. Just seems to, you know, like randomly say, "Well, just because you can compile the code, I can't compile the code."
And you're going, "But why?" Anyway, um so one thing one question I had was so we've got the um forge script command and we're presenting a private key which is stored in an in an environment variable and um you know, for say if your if your contract's going to be protecting a billion dollars, you really don't want to be doing that. You want that private key to be in uh hardware hardware security module or AWS key manager or something. Is there a way of like getting using a key that's in uh HSM or a AWS key manager or something like that?
I don't know. I haven't tried this. Uh there might be. Uh if not uh Uh there might be a a PR or an issue on this. Uh but I don't know. I haven't used I have so far I haven't I haven't used any of these integrations. I'm not sure if there's integrations. Yeah, cuz it looks like a really great idea where you essentially you're forking the current chain, you say run your upgrade script checking that everything's working okay, and then assuming everything's working okay, then you go, you know, and you actually do the deployment. Um but yeah, then you want to be deploying that from the real private key which is a big deal.
Um yeah. Um Devendra asked, "Is there any plan to extend Foundry or Forge to um non-EVM chains?" Um Um not that I know of. Um Maybe something I should mention is they as I said before, they have a really great open source community. They have a Telegram channel. They have a whole bunch of issues and a lot of also documentation on their GitHub of what they are planning as next features. Um I haven't read anything about non-EVM chains, but uh yeah, there might be. Uh but I mean it is based on uh on like something called REVM which is a Rust implementation of the EVM which
makes it really fast and which is at the core of of Foundry. So um yeah, it would be a if if they are planning to do this, I think it would be a very very big uh effort and probably a more or less complete rewrite of the whole library, but who knows. Yeah, but I think there's enough momentum around EVM that um Yeah, I think non-EVM environments will end up being environments. I mean, I'm who knows? Maybe the others will survive.
Um let me go through this. Um so thank you for your talk by the way. That was amazing. So it was very very well done. Um yeah, very much appreciated. Um yeah. Yeah. Yeah, the virtual clapping. But yeah, let's go through this. So the merch store is open and um I think I've sold somewhere between 50 and 100 t-shirts. Um so um yes, you should now's the time. You know, there always always a time. And I am going to produce a an Ethereum research t-shirt. I have an idea now. So um I'll get around to doing that.
Um next slide, please. Yeah. Okay. Um so next week, golly, next week Clemens is going to come along and tell us his um thoughts on AI and Web3. So Clemens is a deep thinker at ConsenSys. And so I'm sure that will be very interesting. Um I'm going to talk about the Passport wallet and Immutable ZK-EVM. So I'm going to talk about a new uh Web3 wallet that um we've got at Immutable and convince you all that not only is it really easy to use, great if you've got a game, and so non-intrusive even when
you're playing a Web3 game or a game, cuz aren't all games Web3 these days or going to be? Um so anyway, it's um telling you all about Passport and broadly about the Immutable ZK-EVM and how that works. Um there is a talk that is very tentatively planned for um 2 weeks after that, but I haven't got it there yet. So and I'll just wait for it to be locked in. Um then I'm going to talk about some ERC-20 bridge improvements. So um I've been, you know, looking at um these large hacks and thinking about, "Well, for Immutable, what can we do to make our bridges not uh you know, so hackable as these other um other projects?" And so
the bridge improvements that I've come up with are readily applicable to any ecosystem. So this will apply to anyone who's running an ERC-20 bridge for a roll-up, a side chain, so an L1, L2, L3 in any configuration. So I think certainly worth um coming along to. Um Tim Beiko from um Ethereum Foundation is going to give an overview of Ethereum governance. And so that is all about how um Ethereum as a group makes decisions.
So I think that should be very interesting. And we're going to end the year with me doing a Solidity interview challenge. And so this will be another interactive session. Um please bring your Remix or favorite um IDE and we'll try and together work out a problem. And um if we don't have lots of interactivity, I'll probably rope in people like Sandra, David, and Joanne and anyone else who I think won't mind too much if I ask them a tricky question on the day. Um yeah.
And um Christian, can you move to the next slide, please? Just one more slide. Yes, okay. So if you're here today, um there is a YouTube channel that you can watch the recording on. There is a Slack workspace. Um there's also a um um if you're watching this on YouTube, you can join live and ask the tricky questions live. Sometimes there is example code and that'll be on that repo. And um there is a is the formal methods reading group still happening, David? I've I wonder, should I No. All right, so scrub that formal methods reading group.
Um yeah, I will have to get have to get around to removing that from my final slides. So um yeah, so thank you again, Christian. That was really awesome. And um thank you for your time producing that that I know that would have been a lot of effort. And um yeah, very very much appreciated. Thank you. I have a question. The merch store, is it shipping globally or only Yeah, yeah, absolutely globally. Um and I've tried I I searched out merch store um possibilities. And um this um company that I've um partnering with, they do global manufacturing. So um there's manufacturing in Australia, in
the US and Europe. So if you're in any of those places, the shipping costs and the time to to delivery is generally pretty good. Um I have no idea. I've never said I live in Thailand and I've found out what the shipping costs are to Thailand. So I'm not sure. But the of all the companies I've of, you know, I considered, this is the company most likely to say set up t-shirt manufacturing or partner with a manufacturer in your country and hence have global low cost um merch. Which so I think it really worked well. So yeah, global shipping and hopefully low cost and low time to
delivery. All right. So thank you everyone. Have a great rest of your day and um thank you again Christian. Thank you for having me. Thank you. Bye. Bye everyone. Bye.
Related talks
- Foundry, a portable, fast and modular toolkit for Ethereum application
- Crea Tu Primera Cripto Moneda ERC20 Desde Cero | Cyfrin Updraft
- Truffle and TruffleCon
- BUIDLing DeFi protocol from perspective of compiler core dev
- Wake Framework: Swiss Knife to Ethereum Tooling
- Hardhat 3 Preview: Overhauled & Rust-Powered
- How to Build Private Smart Contracts on Aztec for Solidity Developers
- Better Smart Contracts with Behavior-Driven Development with Thomas Vieira and Neodaoist
- Cyfrin Updraft: Full-Stack Web3 Development Crash Course
