Binance Square
LIVE
Bloqarl
@Bloqarl
Enhance Web3 Security | Build On-Chain | Master DeFi | If you share my same goals, I share everything I learn. My Twitter https://twitter.com/TheBlockChainer
Following
Followers
Liked
Shared
All Content
LIVE
--
#Web3 #security explained. Learn about #SmartContracts and how to avoid reentrancy on them. https://www.binance.com/en/feed/post/536271?ref=730857736&utm_campaign=web_share_copy
#Web3 #security explained. Learn about #SmartContracts and how to avoid reentrancy on them.

https://www.binance.com/en/feed/post/536271?ref=730857736&utm_campaign=web_share_copy
Want to leave #trading aside and focus on #Ethereum #blockchain and #EVM Checkout my articles on how to get yourself started. https://www.binance.com/en/feed/post/536400?ref=730857736&utm_campaign=web_share_copy https://www.binance.com/en/feed/post/536250?ref=730857736&utm_campaign=web_share_copy
Want to leave #trading aside and focus on #Ethereum #blockchain and #EVM

Checkout my articles on how to get yourself started.

https://www.binance.com/en/feed/post/536400?ref=730857736&utm_campaign=web_share_copy

https://www.binance.com/en/feed/post/536250?ref=730857736&utm_campaign=web_share_copy
Studying Web3 security, auditing SC and more. How do I handle this?I do feel a bit like in that picture, to be honest. These past few days I have started doing my first audit in code4rena and together with the Smart Contract course and my job it’s quite a lot to handle.  Yes, mainly because I did pay for it. But that only helped me take it even more serious. And then, a week ago I left my “fear” of not being prepared aside and I registered in code4rena, determined to participate in the next auditing contest. And so I did. A couple of days after that, the asymmetry contest started and I went all into it. “Cool, now you’re doing those two things everyday then? Not a big deal…” Well, anyone involved with any of this, will know that it’s mentally demanding which means that you can’t really be doing this for a long time and yet be productive. And you know what? Besides that I do have a full time job as well. So, how do I organize my time to handle this? For good or bad every day has 24 hours and that won’t change. So, to take the most out of them I needed some commitment and organization: 1 . I decided to wake up earlier than I used to in order to be able to use one to two hours before starting my full-time job to do either of my tasks. There’s, however, something important to mention, I try to keep the minimum of seven hours sleep. Otherwise, I might be useless and my brain won’t work as well. So, I would for instance continue where I left off from the SCH course and focus on that for as much time as I could before having the need to stand up and rest. 2. After using a break to eat something and/or going for a short walk I start my full-time job. As I’ve mentioned in my first article I am a software engineer in test, so my job is as well mentally demanding, so, I do need breaks, and during those, I sometimes check if there’s any new video on Youtube from Owen, Patrick Collins or any other people I follow or just check what’s going on on Twitter Blockchain community. 3. After finishing my working hours, usually I switch right away, even without moving from my chair (I work remotely) directly to my studies or the audit (depending on the day and feeling) and I would spend a short while before going for a walk or doing some exercise. 4. I usually work out at home with bodyweight exercises. I’m a fan of Calisthenics so, some of the exercises are from this discipline as well. I don’t spend 2 hours working out, usually 30 to 60 minutes as it helps me mentally and obviously physically. 5. During the rest of my day I find that after doing some chores, and to be fair, just having some life, I do find time for reviewing this project from code4rena and try to apply some of the auditing tips I’ve got from the community. What I find is that since I am learning to exploit vulnerabilities, when I learn something new I would look for that in the code from the audit and see if I can catch a glimpse of a potential case. Independently of whether me being successful in it or not, what matters is the time spent analyzing and trying to understand the code. __________________ Twitter @TheBlockChainer to find more daily updates about Smart Contracts, Web3 Security, Solidity, Auditing smart contracts, and more. __________________

Studying Web3 security, auditing SC and more. How do I handle this?

I do feel a bit like in that picture, to be honest. These past few days I have started doing my first audit in code4rena and together with the Smart Contract course and my job it’s quite a lot to handle.



Yes, mainly because I did pay for it. But that only helped me take it even more serious.

And then, a week ago I left my “fear” of not being prepared aside and I registered in code4rena, determined to participate in the next auditing contest. And so I did. A couple of days after that, the asymmetry contest started and I went all into it.

“Cool, now you’re doing those two things everyday then? Not a big deal…”

Well, anyone involved with any of this, will know that it’s mentally demanding which means that you can’t really be doing this for a long time and yet be productive.

And you know what? Besides that I do have a full time job as well.

So, how do I organize my time to handle this?

For good or bad every day has 24 hours and that won’t change. So, to take the most out of them I needed some commitment and organization:

1 . I decided to wake up earlier than I used to in order to be able to use one to two hours before starting my full-time job to do either of my tasks.

There’s, however, something important to mention, I try to keep the minimum of seven hours sleep. Otherwise, I might be useless and my brain won’t work as well.

So, I would for instance continue where I left off from the SCH course and focus on that for as much time as I could before having the need to stand up and rest.

2. After using a break to eat something and/or going for a short walk I start my full-time job.

As I’ve mentioned in my first article I am a software engineer in test, so my job is as well mentally demanding, so, I do need breaks, and during those, I sometimes check if there’s any new video on Youtube from Owen, Patrick Collins or any other people I follow or just check what’s going on on Twitter Blockchain community.

3. After finishing my working hours, usually I switch right away, even without moving from my chair (I work remotely) directly to my studies or the audit (depending on the day and feeling) and I would spend a short while before going for a walk or doing some exercise.

4. I usually work out at home with bodyweight exercises. I’m a fan of Calisthenics so, some of the exercises are from this discipline as well.

I don’t spend 2 hours working out, usually 30 to 60 minutes as it helps me mentally and obviously physically.

5. During the rest of my day I find that after doing some chores, and to be fair, just having some life, I do find time for reviewing this project from code4rena and try to apply some of the auditing tips I’ve got from the community.

What I find is that since I am learning to exploit vulnerabilities, when I learn something new I would look for that in the code from the audit and see if I can catch a glimpse of a potential case. Independently of whether me being successful in it or not, what matters is the time spent analyzing and trying to understand the code.

__________________

Twitter @TheBlockChainer to find more daily updates about Smart Contracts, Web3 Security, Solidity, Auditing smart contracts, and more.

__________________
What is a Reentrancy attack? — Let’s understand them and prevent them. Firstly, I am going to help you understand in a simple way what is a reentrancy attack and how you can prevent it, and then, I will dive deeper into code examples in order to show where are the vulnerabilities, what would be the attacker code and most importantly I will show you the latest verified methods to protect not only one but all the smart contracts in your project. Spoiler: If you have already heard about the nonReentrant() modifier, keep reading because you are about to discover a few lines below the globalNonReentrant() modifier and the checks-effects-interactions pattern.  In the image above we have ContractA and ContractB. Now, as you know a smart contract can interact with another smart contract, like in this case, ContractA can call ContractB. So, the very basic idea of reentrancy is that ContractB is able to call back to ContractA while ContractA is still executing. So, how can the attacker use this? Above we have ContractA which has 10 Ethers and we see that ContractB has stored 1 Ether in ContractA. In this case, ContractB will be able to use the withdraw function from ContractA and send Ether back to itself as it passes the check where its balance is greater than 0, to then have its total balance modified to 0.  Let’s now see how can ContractB use reentrancy to exploit the withdraw function and steal all the Ethers from ContractA. Basically, the attacker is going to need two functions: attack() and fallback(). In Solidity, a fallback function is an external function with neither a name, parameters, or return values. Anyone can call a fallback function by: Calling a function that doesn’t exist inside the contract; Calling a function without passing in required data; Sending Ether without any data to the contract. The way reentrancy works (let’s follow the arrows step by step) is with the attacker calling the attack() function which inside is calling the withdraw() function from ContractA. Inside the function, it will verify if the balance of ContractB is greater than 0 and if so it will continue the execution.  Since ContractB’s balance is greater than 0, it sends that 1 Ether back and it triggers the fallback function. Notice that at this moment ContractA has 9 Ethers and ContractB has already 1 Ether.  Next, when the fallback function gets executed it triggers again ContractA’s withdraw function, checking again if ContractB’s balance is greater than 0. If you check again the image above you will notice that its balance is still 1 Ether.  That means that the check passes and it sends another Ether to ContractB, which triggers the fallback function. Notice that since the line where we have “balance=0” never gets executed, this will continue until all Ether from ContractA is gone. ___________ Let’s now take a look at a smart contract where we can identify reentrancy with the Solidity code.  In the EtherStore contract, we have the function deposit() that stores and updates the balances of the sender and then the withdrawAll() function that will take all the balances stored at once. Please, notice the implementation of withdrawAll() where it checks first with the require that the balance is greater than 0 and right after sends the Ether, again, leaving for the end the update of the sender’s balance to 0.  Here we have the contract Attack that is going to use the reentrancy to drain the EtherStore contract. Let’s analyze its code: In its constructor, the attacker will pass the EtherStore address in order to create an instance and so being able to use its functions. There we see the fallback() function which is going to be called when EtherStore sends Ether to this contract. Inside it will be calling withdraw from EtherStore as long as the balance is equal or greater than 1. And inside the attack() function we have the logic that will be exploiting EtherStore. As we can see, first we will initiate the attack by making sure we have enough ether, then deposit 1 ether in order to have a balance greater than 0 in EtherStore and hence pass the checks before starting to withdraw. I explained above in ContractA and ContractB’s example step by step how the code will run, so now, let’s make a summary of how will it be. First of all the attacker will call attack(), which inside will call withdrawAll() from EtherStore, which then will send Ether to Attack contract’s fallback function. And there it will start the reentrancy and drain the EtherStore’s balance. So, how can we protect our contracts from reentrancy attacks? I am going to show you three prevention techniques to fully protect them. I am going to cover how to prevent reentrancy in a single function, reentrancy cross-function, and reentrancy cross-contract.  The first technique to protect a single function is using a modifier called noReentrant. A modifier is a special type of function that you use to modify the behavior of other functions. Modifiers allow you to add extra conditions or functionality to a function without having to rewrite the entire function. What we do here is lock the contract while the function is executed. This way it won’t be able to reenter the single function since it will need to go through the function’s code and then change the locked state variable to false in order to pass again the check done in the require. ___________  The second technique is by making use of the Checks-Effects-Interactions pattern which will protect our contracts from cross-function reentrancy. Can you spot in the updated EtherStore contract above what has changed? To deep dive into Check-Effects-Interaction pattern I recommend to read https://fravoll.github.io/solidity-patterns/checks_effects_interactions.html    Above we see the comparison between the code vulnerable from the image on the left where the balance was updated after sending the Ether, which as seen above could potentially never be reached, and on the right what it has been done is to move the balances[msg.sender] = 0 (or effect) right after the require(bal > 0) (check) but before sending ether (interaction). This way we will be making sure that even if another function is accessing withdrawAll(), this contract will be protected from the attacker because the balance will always be updated before sending the Ether. Pattern created by https://twitter.com/GMX_IO The third technique I am going to show you is creating the GlobalReentrancyGuard contract to protect from cross-contract reentrancy. It is important to understand that this is applicable to projects with multiple contracts interacting with each other. The idea here is the same as in the noReentrant modifier I have explained in the first technique, it enters the modifier, updates a variable to lock the contract and it doesn’t unlock it until it doesn’t finish the code. The big difference here is that we are using a variable stored in a separate contract which is used as the place to check if the function was entered or not.    I have created here an example without actual code and just with function names for reference to understand the idea as, from my experience, it can help visualize the situation more than just writing it with words. Here, the attacker would be calling the function in the ScheduledTransfer contract which after meeting the conditions it would send the specified Ether to the AttackTransfer contract which would, therefore, enter the fallback function and hence “cancel” the transaction from the ScheduledTransfer contract’s point of view and yet receive the Ether. And this way it would be starting a look until draining all Ethers from ScheduledTransfer. Well, using the GlobalReentrancyGuard I have mentioned above it will avoid such an attack scenario. __________________ Twitter @TheBlockChainer to find more daily updates about Smart Contracts, Web3 Security, Solidity, Auditing smart contracts, and more. __________________

What is a Reentrancy attack? — Let’s understand them and prevent them.



Firstly, I am going to help you understand in a simple way what is a reentrancy attack and how you can prevent it, and then, I will dive deeper into code examples in order to show where are the vulnerabilities, what would be the attacker code and most importantly I will show you the latest verified methods to protect not only one but all the smart contracts in your project.

Spoiler: If you have already heard about the nonReentrant() modifier, keep reading because you are about to discover a few lines below the globalNonReentrant() modifier and the checks-effects-interactions pattern.



In the image above we have ContractA and ContractB. Now, as you know a smart contract can interact with another smart contract, like in this case, ContractA can call ContractB. So, the very basic idea of reentrancy is that ContractB is able to call back to ContractA while ContractA is still executing.

So, how can the attacker use this?

Above we have ContractA which has 10 Ethers and we see that ContractB has stored 1 Ether in ContractA. In this case, ContractB will be able to use the withdraw function from ContractA and send Ether back to itself as it passes the check where its balance is greater than 0, to then have its total balance modified to 0.



Let’s now see how can ContractB use reentrancy to exploit the withdraw function and steal all the Ethers from ContractA. Basically, the attacker is going to need two functions: attack() and fallback().

In Solidity, a fallback function is an external function with neither a name, parameters, or return values. Anyone can call a fallback function by: Calling a function that doesn’t exist inside the contract; Calling a function without passing in required data; Sending Ether without any data to the contract.

The way reentrancy works (let’s follow the arrows step by step) is with the attacker calling the attack() function which inside is calling the withdraw() function from ContractA. Inside the function, it will verify if the balance of ContractB is greater than 0 and if so it will continue the execution.



Since ContractB’s balance is greater than 0, it sends that 1 Ether back and it triggers the fallback function. Notice that at this moment ContractA has 9 Ethers and ContractB has already 1 Ether.



Next, when the fallback function gets executed it triggers again ContractA’s withdraw function, checking again if ContractB’s balance is greater than 0. If you check again the image above you will notice that its balance is still 1 Ether.



That means that the check passes and it sends another Ether to ContractB, which triggers the fallback function. Notice that since the line where we have “balance=0” never gets executed, this will continue until all Ether from ContractA is gone.

___________

Let’s now take a look at a smart contract where we can identify reentrancy with the Solidity code.



In the EtherStore contract, we have the function deposit() that stores and updates the balances of the sender and then the withdrawAll() function that will take all the balances stored at once. Please, notice the implementation of withdrawAll() where it checks first with the require that the balance is greater than 0 and right after sends the Ether, again, leaving for the end the update of the sender’s balance to 0.



Here we have the contract Attack that is going to use the reentrancy to drain the EtherStore contract. Let’s analyze its code:

In its constructor, the attacker will pass the EtherStore address in order to create an instance and so being able to use its functions.

There we see the fallback() function which is going to be called when EtherStore sends Ether to this contract. Inside it will be calling withdraw from EtherStore as long as the balance is equal or greater than 1.

And inside the attack() function we have the logic that will be exploiting EtherStore. As we can see, first we will initiate the attack by making sure we have enough ether, then deposit 1 ether in order to have a balance greater than 0 in EtherStore and hence pass the checks before starting to withdraw.

I explained above in ContractA and ContractB’s example step by step how the code will run, so now, let’s make a summary of how will it be. First of all the attacker will call attack(), which inside will call withdrawAll() from EtherStore, which then will send Ether to Attack contract’s fallback function. And there it will start the reentrancy and drain the EtherStore’s balance.

So, how can we protect our contracts from reentrancy attacks?

I am going to show you three prevention techniques to fully protect them. I am going to cover how to prevent reentrancy in a single function, reentrancy cross-function, and reentrancy cross-contract.



The first technique to protect a single function is using a modifier called noReentrant.

A modifier is a special type of function that you use to modify the behavior of other functions. Modifiers allow you to add extra conditions or functionality to a function without having to rewrite the entire function.

What we do here is lock the contract while the function is executed. This way it won’t be able to reenter the single function since it will need to go through the function’s code and then change the locked state variable to false in order to pass again the check done in the require.

___________



The second technique is by making use of the Checks-Effects-Interactions pattern which will protect our contracts from cross-function reentrancy. Can you spot in the updated EtherStore contract above what has changed?

To deep dive into Check-Effects-Interaction pattern I recommend to read https://fravoll.github.io/solidity-patterns/checks_effects_interactions.html 





Above we see the comparison between the code vulnerable from the image on the left where the balance was updated after sending the Ether, which as seen above could potentially never be reached, and on the right what it has been done is to move the balances[msg.sender] = 0 (or effect) right after the require(bal > 0) (check) but before sending ether (interaction).

This way we will be making sure that even if another function is accessing withdrawAll(), this contract will be protected from the attacker because the balance will always be updated before sending the Ether.

Pattern created by https://twitter.com/GMX_IO

The third technique I am going to show you is creating the GlobalReentrancyGuard contract to protect from cross-contract reentrancy. It is important to understand that this is applicable to projects with multiple contracts interacting with each other.

The idea here is the same as in the noReentrant modifier I have explained in the first technique, it enters the modifier, updates a variable to lock the contract and it doesn’t unlock it until it doesn’t finish the code. The big difference here is that we are using a variable stored in a separate contract which is used as the place to check if the function was entered or not.







I have created here an example without actual code and just with function names for reference to understand the idea as, from my experience, it can help visualize the situation more than just writing it with words.

Here, the attacker would be calling the function in the ScheduledTransfer contract which after meeting the conditions it would send the specified Ether to the AttackTransfer contract which would, therefore, enter the fallback function and hence “cancel” the transaction from the ScheduledTransfer contract’s point of view and yet receive the Ether. And this way it would be starting a look until draining all Ethers from ScheduledTransfer.

Well, using the GlobalReentrancyGuard I have mentioned above it will avoid such an attack scenario.

__________________

Twitter @TheBlockChainer to find more daily updates about Smart Contracts, Web3 Security, Solidity, Auditing smart contracts, and more.

__________________
New in Blockchain? Don’t start by learning Solidity. Learn first about DeFi When I first discovered Blockchain and started to read about the potential that it has and how much certainly present is going to be a big thing in the near future I wanted to tell everyone about it and I found myself in a situation where I was not even able to explain what it is and what is it applied to. “Blockchain is the new internet” — I was saying. Okay, but tell me more about it, sounds interesting “The internet will be decentralized thanks to this new technology” — I was mentioning next Well, that was about it that I could explain. Honestly, I could not even guess what it is all about because I was never involved with crypto even for a moment and didn’t read anything about Bitcoin and what it really is. Learning about what Bitcoin is, can give you a great idea of what is the main goal of Blockchain. So, what was my next move? How did I continue to get into Blockchain? Well, I knew I was not interested in trading or suddenly start to learn all about investing in crypto. What I was interested in was that I knew there was a new programming language and that now there is the so-called Blockchain developer. I wanted that. I wanted to learn to code in Solidity! So, what were my first steps to get into this new world? How did I finally start to move toward my goal of becoming a Blockchain developer? I started an online course to learn about what is Bitcoin, what is a Blockchain and how many exist and what is the so-called “DeFi” and what is this all about. Couldn’t I just jump directly into learning about Solidity? No, because I needed to understand more of what is this all about, I needed to understand why is it called decentralized and how much truth there is in that. I started to combine the course with a book I bought called “Blockchain Revolution: How the Technology Behind Bitcoin Is Changing Money, Business, and the World”. From the course, I learned what is an Exchange, what is lending and borrowing, what is UniSwap, what are the different types of protocols in blockchain and so much more about how people are nowadays involved with blockchain. And from the book I learned the potential that Blockchain has in the world. How it can change everything. How the world would look like with a voting system decentralized, with a decentralized system in hospitals, many usabilities, and let me tell you I loved all of it. But, did I start learning Solidity or not? Yes, I got to both, learn Solidity from an introductory class in the online course and on my own research. And then, little by little I started to move my interests and time, more towards Solidity and how to program smart contracts. And a few months later came Auditing to my life… but that’s for another day. ________________ So, for those enthusiast programmers that want to go all in with Smart Contracts. Learn first about the history of Money, the history of blockchain and bitcoin, and also how decentralized finance work.

New in Blockchain? Don’t start by learning Solidity. Learn first about DeFi



When I first discovered Blockchain and started to read about the potential that it has and how much certainly present is going to be a big thing in the near future I wanted to tell everyone about it and I found myself in a situation where I was not even able to explain what it is and what is it applied to.

“Blockchain is the new internet” — I was saying.

Okay, but tell me more about it, sounds interesting

“The internet will be decentralized thanks to this new technology” — I was mentioning next

Well, that was about it that I could explain. Honestly, I could not even guess what it is all about because I was never involved with crypto even for a moment and didn’t read anything about Bitcoin and what it really is.

Learning about what Bitcoin is, can give you a great idea of what is the main goal of Blockchain.

So, what was my next move? How did I continue to get into Blockchain?

Well, I knew I was not interested in trading or suddenly start to learn all about investing in crypto. What I was interested in was that I knew there was a new programming language and that now there is the so-called Blockchain developer. I wanted that.

I wanted to learn to code in Solidity!

So, what were my first steps to get into this new world? How did I finally start to move toward my goal of becoming a Blockchain developer?

I started an online course to learn about what is Bitcoin, what is a Blockchain and how many exist and what is the so-called “DeFi” and what is this all about.

Couldn’t I just jump directly into learning about Solidity?

No, because I needed to understand more of what is this all about, I needed to understand why is it called decentralized and how much truth there is in that.

I started to combine the course with a book I bought called “Blockchain Revolution: How the Technology Behind Bitcoin Is Changing Money, Business, and the World”.

From the course, I learned what is an Exchange, what is lending and borrowing, what is UniSwap, what are the different types of protocols in blockchain and so much more about how people are nowadays involved with blockchain.

And from the book I learned the potential that Blockchain has in the world. How it can change everything. How the world would look like with a voting system decentralized, with a decentralized system in hospitals, many usabilities, and let me tell you I loved all of it.

But, did I start learning Solidity or not?

Yes, I got to both, learn Solidity from an introductory class in the online course and on my own research.

And then, little by little I started to move my interests and time, more towards Solidity and how to program smart contracts.

And a few months later came Auditing to my life… but that’s for another day.

________________

So, for those enthusiast programmers that want to go all in with Smart Contracts.

Learn first about the history of Money, the history of blockchain and bitcoin, and also how decentralized finance work.
Solidity Gas Optimization: Understanding how EVM works can save you gas You might have come across some Solidity tips to improve your code skills in order to save some gas, but, today I want to focus more on how understanding the Ethereum Virtual Machine can effectively save you gas costs on your smart contracts. Since we are going to dive into Ethereum, I am going to leave here the snippet of its Yellow Paper which specifies the gas costs of the opcodes, and during the article we will be referring to them.  Tip #1: Cold access VS warm access Gcoldsload: 2100 gas Gwarmaccess: 100 gas There we have our first OPCODES, the first one is specifying how much it costs to access a variable for the first time (or cold access) while the second one specifies how much it costs to access the variable a second time and further (warm access). As you can see the difference in price is quite big, so understanding this can make a big difference in the costs of your smart contract’s transactions. Let’s see an example.   Caching the data inside a function in Solidity can result in lower gas usage, even if it needs more lines of code. In this case, it is by switching the location of the array and instead of using it from storage and hence cold accessing it every time in the loop, it stores the array in memory where is cheaper to access it. Tip #2: Zero vs non-zero values and gas refunds Gsset = 20,000 gas Rsclear = {discount on execution price} Changing a value from 0 to non-zero on the Ethereum blockchain is expensive as we see in the price of Gsset, but changing a value from non-zero to 0, can give you a refund in gas value as per the opcode Rsclear. In order to not take advantage of the refund, it is established that you can only get refunded by up to a maximum of 20% of the total transaction cost. You can find such a scenario in a very common scenario on blockchain, which is updating the balance of addresses in smart contracts. Let’s see an example of each:   In the first example ZeroToNonZero contract, non-zero to non-zero (5,000 gas*) + zero to non-zero (20,000 gas) = 25,000 gas In the second example NonZeroToZero contract, Non-zero to zero (5,000 gas*) + zero to non-zero (20,000 gas) — Refund (4,800 gas) = 21,200 gas *2,100 (Gcolssload) + 2,900 (Gsreset) = 5,000 gas Tip #3: Order of state variables matter The Storage is like a key-value data structure that holds the state variables values of a Solidity smart contract. You can think of storage as an array which will help to visualize this. Each space in this storage “array” is called a slot and holds 32 bytes (256 bits) of data and each state variable declared in the smart contract will occupy a slot depending on its declaration position and its type. Not all data types take all the 32 bytes of each slot as there are some data types (bool, uint8, address…) that take less than that. The trick here is that if two/three or more variables together are 32 bytes or less, solidity’s compiler will try to pack them together in a single slot, but these variables need to be defined next to each other.   Here we are using the data types bool (1 byte), address (20 bytes), and uint256 (32 bytes). So, knowing the size of these variables you can easily understand that in the first example in the TwoSlots contract since we have bool and address together (1 + 20 = 21 bytes, which is less than 32 bytes) they will occupy one slot. On the ThreeSlots contract since bool and uint256 cannot be in the same slot (1 + 32 = 33 bytes, which is bigger than the slot capacity) in total we will be using three slots. Now, why is this so important? SLOAD opcode costs 2100 gas and it is used to read from Storage slots, so if you can store the variables in fewer slots, you will end up saving some gas. Tip #4: uint256 is cheaper than uint8 We have learned in tip #3, that uint256 (256 bits = 32 bytes) occupies by itself a slot and we have learned as well that uint8 is less than 32 bytes. So, while it is kind of straightforward that 8 bits are smaller than 256 bits, how come uint256 is cheaper? In order to understand that it is important to know that if a variable does not fill itself the whole slot and if this slot is not filled by any other variable, the EVM is going to fill the rest of the remaining bits with “0”s in order to be able to manipulate it. This “0” addition performed by the EVM will cost gas, meaning that in order to save transaction gas, it is better to use uint256 instead of uint8. __________________ Hopefully, while finding out about these tips to reduce the gas costs in your smart contracts you have learned as well a bit of how the EVM works. __________________ Twitter @TheBlockChainer to find more daily updates about Smart Contracts, Web3 Security, Solidity, Auditing smart contracts, and more. __________________

Solidity Gas Optimization: Understanding how EVM works can save you gas



You might have come across some Solidity tips to improve your code skills in order to save some gas, but, today I want to focus more on how understanding the Ethereum Virtual Machine can effectively save you gas costs on your smart contracts.

Since we are going to dive into Ethereum, I am going to leave here the snippet of its Yellow Paper which specifies the gas costs of the opcodes, and during the article we will be referring to them.



Tip #1: Cold access VS warm access

Gcoldsload: 2100 gas

Gwarmaccess: 100 gas

There we have our first OPCODES, the first one is specifying how much it costs to access a variable for the first time (or cold access) while the second one specifies how much it costs to access the variable a second time and further (warm access). As you can see the difference in price is quite big, so understanding this can make a big difference in the costs of your smart contract’s transactions. Let’s see an example.





Caching the data inside a function in Solidity can result in lower gas usage, even if it needs more lines of code. In this case, it is by switching the location of the array and instead of using it from storage and hence cold accessing it every time in the loop, it stores the array in memory where is cheaper to access it.

Tip #2: Zero vs non-zero values and gas refunds

Gsset = 20,000 gas

Rsclear = {discount on execution price}

Changing a value from 0 to non-zero on the Ethereum blockchain is expensive as we see in the price of Gsset, but changing a value from non-zero to 0, can give you a refund in gas value as per the opcode Rsclear. In order to not take advantage of the refund, it is established that you can only get refunded by up to a maximum of 20% of the total transaction cost.

You can find such a scenario in a very common scenario on blockchain, which is updating the balance of addresses in smart contracts. Let’s see an example of each:





In the first example ZeroToNonZero contract, non-zero to non-zero (5,000 gas*) + zero to non-zero (20,000 gas) = 25,000 gas

In the second example NonZeroToZero contract, Non-zero to zero (5,000 gas*) + zero to non-zero (20,000 gas) — Refund (4,800 gas) = 21,200 gas

*2,100 (Gcolssload) + 2,900 (Gsreset) = 5,000 gas

Tip #3: Order of state variables matter

The Storage is like a key-value data structure that holds the state variables values of a Solidity smart contract.

You can think of storage as an array which will help to visualize this. Each space in this storage “array” is called a slot and holds 32 bytes (256 bits) of data and each state variable declared in the smart contract will occupy a slot depending on its declaration position and its type.

Not all data types take all the 32 bytes of each slot as there are some data types (bool, uint8, address…) that take less than that.

The trick here is that if two/three or more variables together are 32 bytes or less, solidity’s compiler will try to pack them together in a single slot, but these variables need to be defined next to each other.





Here we are using the data types bool (1 byte), address (20 bytes), and uint256 (32 bytes). So, knowing the size of these variables you can easily understand that in the first example in the TwoSlots contract since we have bool and address together (1 + 20 = 21 bytes, which is less than 32 bytes) they will occupy one slot. On the ThreeSlots contract since bool and uint256 cannot be in the same slot (1 + 32 = 33 bytes, which is bigger than the slot capacity) in total we will be using three slots.

Now, why is this so important?

SLOAD opcode costs 2100 gas and it is used to read from Storage slots, so if you can store the variables in fewer slots, you will end up saving some gas.

Tip #4: uint256 is cheaper than uint8

We have learned in tip #3, that uint256 (256 bits = 32 bytes) occupies by itself a slot and we have learned as well that uint8 is less than 32 bytes. So, while it is kind of straightforward that 8 bits are smaller than 256 bits, how come uint256 is cheaper?

In order to understand that it is important to know that if a variable does not fill itself the whole slot and if this slot is not filled by any other variable, the EVM is going to fill the rest of the remaining bits with “0”s in order to be able to manipulate it.

This “0” addition performed by the EVM will cost gas, meaning that in order to save transaction gas, it is better to use uint256 instead of uint8.

__________________

Hopefully, while finding out about these tips to reduce the gas costs in your smart contracts you have learned as well a bit of how the EVM works.

__________________

Twitter @TheBlockChainer to find more daily updates about Smart Contracts, Web3 Security, Solidity, Auditing smart contracts, and more.

__________________
How do you even start learning about Blockchain?To start, let me mention I am a Software Engineer in Test, aka QA. I have been working on testing mobile apps and writing some automated tests for over 7 years. Now, how does a QA end up involved in the world of Blockchain? Was it through Bitcoin? or Trading? or any kind of crypto investment? Not even close. I have never been interested or involved in anything related to crypto. And I will tell you more I had never even heard the word Blockchain until the day I caught up with a good old friend. You know those moments when you are speaking with someone about what has he/she been up to and mentions a few words you didn’t fully understand but you let him/her continue so that you don’t, both, interrupt or seem -for lack of a better expression- less smart? Well, that time I did actually ask and I must say that doing so, has changed the path and plans I had for my professional life. So, once you discover you are interested by Blockchain, how do you even start learning about it? Most relevant places to find and consume Blockchain material From my experience, the best places to find and consume material about Blockchain are YouTube, like for most of things, and Twitter, yup, that place where in the last decade has lived a bunch of haters also has a growing community of blockchain enthusiasts which are constantly sharing knowledge and material, both in tweets and links to articles from multiple places. So, after some time watching videos and following a few Twitter accounts I realized I had lots of noise on both my Youtube home and in my personal Twitter feed, so what did I do? I created a separate Twitter account to only follow and interact with Blockchain-related tweets and the same with Youtube, I created a new account where I would only watch only Blockchain things. And like that, I would be getting rid of lots of distractions in order to ease the findings in the topic. After setting this up, you will little by little be finding the right and most popular Youtubers and Twitter accounts which will lead you to find the right path, the right places to start. How? You will start discovering what it is all about, and from those things you will start to do research about those that caught your attention, and those that made you slip a “wow” or a “Jesus! I don’t know anything about it but sounds quite interesting”. And that’s just the beginning.

How do you even start learning about Blockchain?

To start, let me mention I am a Software Engineer in Test, aka QA. I have been working on testing mobile apps and writing some automated tests for over 7 years.

Now, how does a QA end up involved in the world of Blockchain?

Was it through Bitcoin? or Trading? or any kind of crypto investment? Not even close. I have never been interested or involved in anything related to crypto. And I will tell you more I had never even heard the word Blockchain until the day I caught up with a good old friend.

You know those moments when you are speaking with someone about what has he/she been up to and mentions a few words you didn’t fully understand but you let him/her continue so that you don’t, both, interrupt or seem -for lack of a better expression- less smart? Well, that time I did actually ask and I must say that doing so, has changed the path and plans I had for my professional life.

So, once you discover you are interested by Blockchain, how do you even start learning about it?

Most relevant places to find and consume Blockchain material

From my experience, the best places to find and consume material about Blockchain are YouTube, like for most of things, and Twitter, yup, that place where in the last decade has lived a bunch of haters also has a growing community of blockchain enthusiasts which are constantly sharing knowledge and material, both in tweets and links to articles from multiple places.

So, after some time watching videos and following a few Twitter accounts I realized I had lots of noise on both my Youtube home and in my personal Twitter feed, so what did I do? I created a separate Twitter account to only follow and interact with Blockchain-related tweets and the same with Youtube, I created a new account where I would only watch only Blockchain things. And like that, I would be getting rid of lots of distractions in order to ease the findings in the topic.

After setting this up, you will little by little be finding the right and most popular Youtubers and Twitter accounts which will lead you to find the right path, the right places to start. How? You will start discovering what it is all about, and from those things you will start to do research about those that caught your attention, and those that made you slip a “wow” or a “Jesus! I don’t know anything about it but sounds quite interesting”.

And that’s just the beginning.
Explore the lastest crypto news
⚡️ Be a part of the latests discussions in crypto
💬 Interact with your favorite creators
👍 Enjoy content that interests you
Email / Phone number

Latest News

--
View More
Sitemap
Cookie Preferences
Platform T&Cs