# Gas golfing - Real-world example — Andrej Rakic | Chainlink

- Channel: [ETH Belgrade Community](https://streameth.org/eth-belgrade-community)
- Date: 2024-10-07
- Duration: 33:44
- Watch: https://streameth.org/watch/yt-ZjjnUSTeRB4
- YouTube: https://www.youtube.com/watch?v=ZjjnUSTeRB4

## Description

Recording from ETH Belgrade Meetup #6

## Transcript

uh yeah so yeah my name is Andre I work at chain clabs basically building U chain link which is a blockchain Services platform if you're already not not familiar with it basically on whatever blockchain you're working uh we have all the services and tools for you to just combine it and do our things so it's like a platform so for example for cloud computing you have AWS for blockchains you have chain link uh the reason why I'm here today is because these lovely people from it Belgrade called me to talk something solidity so so I'm not going to sh any project on or any protocol or whatever this is a 2-year-old tweet basically a write up I had a discussion uh with my team uh about uh ba ba YC nft collection basically why this orange monkey to transfer from one one externally owned account to another externally account cost more than to transfer this green with this red hat or whatever uh uh so yeah that'll be our main topic uh basically if you work with me cuz I work with some of you guys and you or you saw this tweet don't ruin ruin the presentation but the idea is basically to have like a dialogue instead of monologue basically imagine that we are all like the same solidity team or Dev team and we want to figure it out why this thing trans to transfer this thing cost more than to trans transfer this thing both transfers happen on ethereum main at in less than 1 hour cool that'll be it I'm going to scroll through through this thread so basically any ideas what will be your starting point to figure it out why the cost was different because this was during the bull market uh prices are high so like it really matter like if it's like a dollar or five ideas yes over there perhaps you were touching different bits of states or manipulating state and it was a different state from the first transfer to the second transfer some bigger operation had to be done yeah cool so this is actually really really good guess so what I'm going to repeat just for for the for the for the audience online basically what James said was uh maybe uh during these two transfers uh we touch different storage variables or different parts of storage and because that potentially can cost different amount of gas in units can result in higher uh in higher thing one thing that I didn't mention is that this orange thing uh its ID is like 6,500 to 21 while this one is like 724 so does anyone think that matters I I I see a couple of not heading do you think why like why it matters the ones who nod their head like yeah that matters like ID matters maybe why yep the number is larger so there are more to display that number yeah totally while guess we had that as well like the L the number is larger so consumes more like btes or bits under the hood we will see when we uh Swap this to hex representation so maybe because of that uh this costs more do we have any more guesses maybe before we continue what else what else yes I a question question yeah sure when you say costs more yeah you're talking about like native token or you're saying okay this is like this amount of gas this is this amount because it's different time period so yeah sure so I'm going to repeat the question question is are we talking about gas units or the actual fee we're talking about gas units so we had that discussion as well so there was like one Junior guy says like yeah but you transfer this at like 3:00 p.m. this was at 4:00 p.m. like gas price were different like that's different but no so we don't care about gas fee at that particular moment we care about gas unit and to be more precisely to transfer this uh nft with higher token ID it cost 12 gas units more than to transfer this one okay um actually I should start with this one can some do we all know what 10 nft collection is like technically can someone tell me really quickly what an nft collection is yes it's a smart contract on eum which contains connected the yeah it's a smart contract on this one particular interior Manet uh which means that the code is the same all of these different monkeys or whatever are just some uh some um um as you said like um objects in Array but we can interpret like that basically what I want to say is the Smart contract is the same so the transfer from function is the same right that's why James had a good guess maybe we touch different types of storage okay cool before we have couple ideas so we have a a storage access we had the length of the ID and we have a question had a question about gas units versus gas prices uh we uh we uh said yeah this is on gas units okay what next next so let's now dig into it what will be our next step well our next step will be to actually go to um transaction cashes right so I put like two transaction hashes for these two transfers and we can see them here let's do here okay so do I need to zoom it a bit or you can see it Zoom yeah I'll going to zoom oh I clicked and had okay first thing just let me say when to stop good okay okay cool uh oh this is the same Okay cool so first uh if we want to figure it out uh the James uh solution uh actually approach about touching different uh different types of storage where should we look right this is it scan for but I guess you're all familiar with it and if I scroll down a bit we can see this is the transfer of a orange one and the transfer of a green one and as I said these are the fees so we can see okay gas price different different but we don't care about that so gas price and gas price we don't care about that we're caring about gas units so if you want to see gas units we need to let me see yeah we need to click more details Okay cool so I'm going to open more details and we're going to focus on this part now so we can also see that transfer from transfer from two exact functions SO gas uh gas limit and gas usage by transaction we can see that this one consumed this amount of gas unit units and this one consumed this amount of gas units and the difference is 12 so we're looking for those Famous 12 guas units to see why they're different because the same smart contract same functions same blockchain everything's the same just the IDS or the actual nfts are different okay cool now we want to start with Jam solution how should I uh now you know like I only I only have these two transactions nothing nothing more nothing less so what should I do to figure it out uh which storage slots uh have I touched or not I but uh the the transaction during these two transactions what should I do now any ideas please raise your hand we can continue y should trace the transaction exactly we should trace the transaction uh does anyone know actually does anyone not know what the tracing of transaction is feel free to raise your hand I'll explain anyways what mean by tracing like tracing a transaction I don't know you don't know okay cool fair enough so tracing a transaction means that we want to follow every single step from the moment you sign up uh you send or sign it to the moment of the transaction actually being included in the next block and finalized on blockchain so there is like multiple steps involved uh first and foremost when you're talking about transactions does anyone know uh how much the because this is ethereum mayet how much uh does a transfer of any amount of eat costs on ethereum May it yes 21 21,000 21,000 so we're starting with 21,000 okay so transfer of e like a native coin for paying gases on E ethereum inet costs 21,000 so we know that we must start with 21,000 and then there's some extra costs involved uh when working with smart car contracts basically we are going to populate this input data or call data field this call data over here will be empty for Native transfers of heat but when work with smart contracts we will have something like this this is decoded input original input data is something like this it's a giant HEX number basically so that giant HEX number tells us a lot if we know how to decode it and also uh the receiver of a transaction tells us a lot so if a receiver is a smart contract and this call data is correct then that smart contract will execute some computation which will cost some gas are we all know why that costs more no yeah because ethereum is a decentralized blockchain de centralized Network so you need to have an incentive uh to participate in a network so the more work you your node or computer does the more you need to be rewarded that's simple as that so transferring an an e or doing some infinite Loops or not not infinite but some huge competition on Smart contract is basically not the same so it costs more okay cool uh do we all know how to decode uh how to read this call data at least we don't we don't okay cool when we start with call data uh we first need to uh take a look at these four bytes over here and these four bytes over here 23 bh7 2dd 23 B8 72 DD that's not an coincidence four bytes at the beginning on call data basically uh tells the E virtual machine which function to call so if we again decode this input data uh what I just did let me see if we yeah this default view we can see that that okay cool uh we can see that again we here is this HEX number 33 B8 72 DD so this is a function selector for transfer from function which accepts three parameters two addresses and one un 256 on this B ba YC smart contract so function selector uh means that now evm will jump through bite code to find the exact function selector and then to continue with the computation right how we get this number basically we are going to uh get the function signature that means like transfer from address address un 256 going to Hash it with cat 256 hash which is a hash hashing algorithm on etherum mayet and we are going to get from that value the F first four bytes and that's it and uh does anyone know why is this important actually I said you're going to stop you're going to jump from function signature to function signature to function signature Etc is this important in terms of like gas consumption yeah you so basically the is going to look for the function sign that is this for the F that Mees this signature so the more it Loops to find it the more exactly so he said basically uh the more so evm will go jump from function signature to function signature to function signature until it finds the right one or or it will just revert if there is one another one so each of these jumps costs four gas so the more jumps more gas so we have 21,000 + 4+ 4+ 4 plus 4 wh let's continue okay so that's already like 16 more gas right uh is this relevant for our use case no no because they're the same uh the same two functions okay let's trace it out so for tracing a transaction there are a couple of uh good good websites I'm not going to Shield the the domestic product but that's the one that I'm using often time often times that's obviously tenderly so should I zoom this a bit right Zoom more on tender the logo Okay cool so yeah tenderly uh yeah great guys they created this um basically Swiss knife debugging tool for all evm and I think now non evm blockchains nevertheless what we can do here here is that we can actually as James said trace the transaction see all the details about these two transactions so basically let's let's Zoom it a bit so what do we have here we have all the details from meter scan uh receiver is the Smart contract blah blah and then this is the actual Trace right so these are all the functions called that happened both internal and external function calls for this transaction and for this and for the other one okay so what we assume is going to be the same is the function phace right because transfer from function is the same we expect all the internal and external calls to be the same and like if we quickly analyze this screen is that correct yeah okay so we we agree on that but what we're specifically looking is are actually storage axes accesses why storage is important when working with solidity and this is really important question actually so to to roll back a bit I'm going to talk for like two minutes so to start with solidity is extremely easy solidity is extremely easy language extremely readable extremely easy to write like syntax is is Javascript like under the hood is kind of like C++ or some kind of structural language because it is written in C++ and the only reason why exist is because it produce so tiny bite code uh and it's more cheaper than to write in I don't know like typ script rust or whatever there are also other uh evm compatible languages like wiper Fe huff and others but they're not really a competitor solidity because their ecosystems are really small wiper has a wiper is B probably the second best like but 20 extremely smart people is not then ecosystem basically so solidity is like a dominant player at the moment not not but not because it's like the the greatest language ever just be so just let be real so to start with solidity is extremely easy right but to master it is extremely hard actually so like pareta principle really applies to solidity like you'll learn like 80% of the language like this maybe in the afternoon but to really master and craft those final 20% percentage is hard and it get harder and harder why if we have like cross chain so if you're typing in Java you need to know how Java Virtual Machine Works under the hood if you want to write an efficient code Ean virtual machine evm is many smart people told me I'm not that experienced I'm still young that this is the most simplest uh virtual machine they ever saw so simple language simple virtual machine all good but the thing is that we need to know we need to learn how that Virtual Machine Works under the hood and also this especially is important for like cross chain applications we kind of need to know all the tiny details of a blockchain of or underlying blockchains under the hood so the most obvious example is probably ethereum mayet has like push zero op code majority of layer two layer 2s do not so that's that's the difference right so um so yeah to sum it up like to to learn solidities to start with it's extremely easy but to master it you kind of need to know all these tiny details and we are now tackling those tiny tiny details so when it comes to ethereum mayet right uh that happened I think like two or 3 years ago there was like a probably three Berlin hard Fork so I'm going to share a repo actually with you I think I have it over here uh this is the repo I use to to learn about all about um Berlin hard Fork where is that yeah here it is so it's called Berlin gas cots so let me let's see what are the differ difference so differences actually uh basically uh before Berlin we had um we had op codes that were like extremely straightforward so if you're writing or reading to memory that's extremely cheap if you're reading and writing from Storage that's expensive so what you want to do is to do really ugly thing is that if you need your to access storage that was before Merlin multiple times what you will do is you will copy the variable from Storage to memory which is extremely ugly piece of code you have like two two line two unnecessary lines and then you're going to read from that memory until you need to write something back to storage so M load cost three gas M store cost three gas and that was it SL load was always 800 which is a lot so just to read one thing from a storage will cost much much more than to read from Emily from memory and when it comes to sore there are a bunch of bunch of different op options after Berlin well memory kind of remain the same same through three but uh we got uh a change regarding the SL load so the first read the first SL load costs uh 2,00 gas 2100 gas while each single slot costs like 100 gas because now we have like the terms of cold cold axis and warm axess right so it got it got cheaper right uh so what the new gas golfing technique became to pack your variables instructs or uh declare them in a way that they will fit in a storage right so if you have like address Boolean and number you will not and U 256 you will not do U 256 Boolean oh that's a poor example you will not do address unit 256 and bullion you will for example do address and bullion because they'll fit in the same storage slot and unit 256 to another you already Pro probably know about that but the reason why this change is also important is because in some other blockchain you don't have Berlin uh you don't have like Warman uh called access uh but for this one particular if we take a look at at this thing over here so in Berlin we also got the thing that if we have like something written in a storage but we're uh writing we are changing the value back to the default one so for numbers that's zero for addresses that's address zero for booleans that's false and for Strings that's empty strings I think bytes empty bytes whatever the thing is that you will have you will get some kind of gas refund right why is that important because now nodes in a in a blockchain in ethereum blockchain uh doesn't need to store that extra info in their internal database basis so it's cheaper for them so you get like a gas refund so what we can do now we can trace the function signature to see storage accesses right to see what James said because because of these different token IDs maybe like did we I don't know like um access some particular storage which was like I don't know like we'll see that's a long shot actually because the difference is only 12 gas but we'll see and we can look for gas refunds so we can look for gas refunds gas refunds are important so for example if I um if I you know like um I don't know like uh if there is in that smart contract somewhere to be written in storage this is also long shot how many nfts I do have and I now transfer it and I don't have any so now it's became one to zero for example this is DB example but you get a point so maybe something wrong with there with that so what I'm going to do now is um and also yeah I forgot but where is that uh for up code stuff like evm codes is extremely good website so if you want to bookm Market or whatever like you have playground everything like op codes so what I was talking about uh for interconnection slow but for any any given up code you have um you have yeah here it is so for any given op code let's say um SL load here is if I expand it bunch of details ET such never mind uh we are kind of R around out of time so I'm going to speed myself up so in thunderly you can and let me see now it's really big to find like this is the full Trace we can yeah yeah here it is we can select storage access so now we have storage access and you know you can see with red bunch of s loads red s loads how can I slow Swap this um maybe up I don't know I need to okay no uh story jaes let's refresh this thing so long story short I because we are kind of running out of time we checked for story jaes and the thing is that uh there was no like different uh storage included so for each for both transfers they touched they used exactly same set of op codes exactly the same uh when it comes to storage they accessed exactly the same uh storage slots so uh that wasn't the issue the next issue which which I was talking about is about gas refund so in tenderly if you click on this gas profiler you can see um you can see the details about gas usage for this transaction um I need to now yeah gas profiler so what we're interested in is our gas refunds so if you click on this tab we can see gas refunds so from something to default to zero and is this the issue no yeah the same value so 14,400 14,400 so gas refence again um great we we save some some some guess but that that's not the issue okay what's next do we have any ideas like what what can also uh what can also be the reason why uh why we have that difference of 12 gas yes was the upgrade in between the two transactions what do you mean by upgrade the upgrade about uh no no was the hard for happened in between those transactions no highly likely good shot but yeah know and it'll probably cost much much more because like yeah something with something with SC data okay this is actually a really good shot because if you are transferring e like from one externally owned account to another externally account we said it cost 20 1,000 and I can put whatever I want in that call call data and if it's like a legit thing my receiver AKA smart contract will know how to interpret it but I can actually show that to you now let's do like a quick demo so let's switch to sepolia I hope you can see this uh so I'm going to send just a tiny so I'm going to just swap with my other account doesn't matter I'm going to send like a tiny be bit of sepolia so this is extremely tiny I hope you can see this I don't know if I can zoom it a bit no I can't and optionally I'll put some Hax data so this is call data here I'm going to put it manually so let's say one okay and if I click next how much of gas in units will this transfer cost 21 21,000 anyone else plus something a a little bit more why so you said 21,000 you said 21,000 plus something you data but why is that relevant I mean is it relevant let's check what's what's your guess it is is it relevant because I add this tiny HEX number in call data yes yes why I think data cost two gas b or something like that so you said it'll cost two gas more more it actually cost this amount of gas actually 16 why is it going on is it going on chain uh call data is visible on chain yeah but it's not like it's going to be stored on but yeah you get a point like uh validators will need to process that extra call data no matter if it's us used or not so your guess was actually correct it got to be something with C data but what okay cool if we go back to original transaction hashes how can I see the actual call data as I said Here original original okay we are looking for something unusual here can someone spot a difference or something excuse me length is different length is different no I don't think so I think it's just the font excuse me at the end three numbers and on the left you have four so you have zero on that one yeah but that's the same bite so bite is actually two characters so that's like two D4 okay so yeah search let's search more okay but do we know what we're searching like this is kind of like needle in a CL right because because like okay we'll find some different okay let's stick for with these four characters okay 1 979 02 D4 what's the difference right why why do we care about that can someone tell me St excuse me storage type uh this is call data so call data is not a storage so you have like six different places from where evm can read stuff so you have storage memory logs call data so they're all different so storage is a lot more expensive so this is just we're dealing with call data because we're looking only for 12 guas units yes both options uh involve the same smart contract same code same choices for storage sense that it's there so it would be it wouldn't make sense if they're reming maybe it's has something to do with a Senter of transaction Okay cool so we have another idea maybe something with sender transaction because he is convinced we have the same contract same function same call set of up codes so it doesn't uh doesn't extra it's doesn't necessary with the c data okay cool how many of you are convinced that something with call data okay couple of hands how many are you think it's something else 1 2 3 four five okay for you you thought it's think it's something else do can we have more ideas because like we have like oh we're out of time already so I'm going to speed it up more ideas to ask I have a question to be honest I'm not so proficient okay can we do questions after I question that is a guess okay oh it's a guess okay yeah if you go with a trace okay if I go and check if for example I saw in the trace that you have function that checks does the token ID exists okay that works and the Computing part to just find some location of token ID in the storage my guess is that it can cost some gas a bit more so what he said by basically was uh if we go back to full trace and if there is a check for if this token ID exists maybe there will be different different uh uh different places in storage um that's not the that's not it because again storage here now that we know there like only 12 uh gas Units Storage is much more expensive yes no just a hand okay any more ideas priority priority block position block position uh priority and block position uh yeah that's that's not it okay anything transfer to contract what do you mean by transfer to contract I mean uh destination of dispens yeah destination in both in both cases is the same it's the address of B biy smart contract so whenever you want to call a functional smart contract you're going to exe you're going to perform the regular e transfer like a regular transtion 21,000 the destination will be the address of a smart contract and then you'll put something in a Cod data like I did any ideas with call data should wrap it up okay cool so if I go back to my earlier transaction over here when I put that hex number in a call data we can see now the the transfer is not 21,000 it is actually 21,6 because of that extra stuff so what we did is we comp compared actually I compared uh call datas of both these transactions so if I open this thing and I'm going to zoom it a bit if I can there is one anomaly over there you can see we have one bite one extra all zeros bite okay this is an anomaly right because here if you scroll that function seel function selector this is an address you can see so whenever you see 20 bytes so whenever you see like 20 bytes uh on the right and couple of leading zeros that's probably an address so an address um an address and then this third thing these are token IDs and that was actually a valid guess because this number is greater than this one in terms of hex right and that was or our premise at the beginning with Igor's suggestion like maybe because their token IDs are different that will somehow mess the Cod data the trick is it that was wasn't the case because of these two so if here was like another zero that would make a difference but no this is just a regular uh hex numers hex Valu so if we go back here basically the thing is that because of these different address so this is the address of a sender so from address this one has like some one extra all zero byte in it and the answer is always when it comes at least to ethereum main at is always in yellow paper so if I now collapse this and go to yellow paper and take a look at this we can see that give it a give it a bit we can see that cost of storing data in Co data is different so if we have zero byte it costs four units of gas if we have non zero BTE it costs 16 so 16 minus 4 equals difference of our two gas units 12 and yeah that's it that's how we found it in ethereum yellow paper and yeah that'll be it for for today's talk dialog
