This video is available to students only

There's one major constraint of EVM smart contracts that we've swept under the rug so far, and that is the issue of gas.

So far we've acted as if we have infinite ether and unlimited computing resources available to us. But in reality, this isn't the case.

When we write Solidity smart contracts, we're writing code that will be executed on someone else's computer. Actually, our code will be executed on thousands of computers.

We have to ask, what happens if we wrote malicious code? For example, what if we wrote code that went into an infinite loop and submitted it to the network? If every node on the network were to fall into an infinite loop, the entire Ethereum network would halt.

Could we analyze a program before we run it and check to see if it will terminate? As you probably already know, this is referred to as the halting problem, and the answer is "no". The halting problem is undecidable over turning-complete languages.

The only way to tell if a program will finish is to run it. So what can we do?

The EVM gives resource constraints on our programs. Essentially, it costs you money (or Ether) to run any program. If you make your program run for a long time, you'll pay a lot of ether.

The constraint on running our programs is called gas. It can be a little confusing at first because it's both called gas and denominated in gas. That gas is a unit. Let me explain.

Remember that the EVM runs bytecode operations, called opcodes, not our Solidity code. Each opcode costs a certain amount of gas to run. Some opcodes are cheap, like adding two numbers together, and some opcodes are very expensive, like storing data on the blockchain.

But the gas cost for each opcode is essentially fixed. It's always going to cost 3 gas to add two numbers together.

When we submit a transaction that calls a function on our smart contract, the sum total of all opcodes that run will be the sum total of our gas spent.

But, we don't pay in gas, we pay in Ether. So how do we convert between the two? Well, the miners decide the price per gas they'll accept. So for example, if the price is 5 wei per gas, and we add two numbers together (which costs 3 gas) then we'll pay 15 wei for that operation.

Maybe an analogy will help.

Say that I have a gas guzzling camper and I want to drive from L.A. to San Francisco. It is 374 miles, but let's round up to 400. My camper gets 10 miles to the gallon. It's 400 miles, so divided by 10 -- I will use 40 gallons of gas on my trip.

But how much will I pay for those gallons? Well, it depends on the price of gas. So let's say the price is the same at every gas station along the way and I pay $4/gal., so my cost is $160 dollars.


This page is a preview of Million Ether Homepage

Start a new discussion. All notification go to the author.