Smart Contract Development
  • Introduction
    • What is a Transaction
    • Accounts and Signing
    • What is a smart contract
  • Learning Solidity
    • Introduction
    • Module 1
      • Variable Types
      • Variable Scope: State & Local variables
      • Global variables
      • Functions
        • View and Pure
        • Shadowing in Fuctions
      • Mapping
      • Require
      • Events
    • Project #1: Simple Registry
    • Module 2
      • Constructor
      • Data Location: Value & Reference
      • Interface
      • Import
        • Importing in Foundry
      • Inheritance
      • ERC-20
      • Checks-effect-interaction pattern
    • Project #2: Basic Vault
    • Module 3
      • Payable
      • Receive
      • Fallback
      • Returns
    • Project #3: ERC20+ETH Wrapper
    • Module 4
      • Immutable and Constant
      • Fixed-point Math
      • Abstract contracts
      • ERC-4626
      • Modifier + Inheritance +Ownable
      • Type
    • Project #4: Fractional Wrapper
    • Module 5
      • If-else
      • Libraries
        • TransferHelper
      • Chainlink Oracle
    • Project #5: Collateralized Vault
  • Compendium
    • Solidity Basics
      • Variable Types
      • Value Types
        • address
        • enum
      • Reference Types
        • strings
        • mappings
        • struct
        • Arrays
        • Multi-Dimensional arrays
      • Global Objects
      • Functions
        • Function types
        • Constructor Function
        • Transaction vs Call
        • Require, Revert, Assert
      • Function signature + selectors
      • Payable
        • Payable + withdraw
        • msg.value & payable functions
      • Receive
      • Fallback function (sol v 0.8)
        • Fallback function (sol v 0.6)
      • call, staticcall, delegatecall
    • Return & Events
    • Control Variable Visibility
    • Local Variables (Storage v Memory)
    • Data Location and Assignment Behaviors
    • Modifiers & Inheritance & Import
      • import styles
    • Interface & Abstract Contracts
    • ABI & Debugging
    • Libraries
    • Conditional(ternary) operators
    • Smart Contract Life-cycle
      • Pausing Smart Contracts
      • Destroying Smart Contracts
    • Merkle Trie and MPT
    • Merkle Tree Airdrop
  • Try & catch
  • Ethereum Signatures
  • EVM, Storage, Opcodes
    • EVM
    • Wei, Ether, Gas
    • Storage
    • ByteCode and Opcodes
    • Transaction costs & Execution costs
  • Reading txn input data
  • Data Representation
  • Yul
    • Yul
      • Intro
      • Basic operations
      • Storage Slots
      • Storage of Arrays and Mappings
      • Memory Operations
      • Memory: how solidity uses memory
      • Memory: Return, Require, Tuples and Keccak256
      • Memory: Logs and Events
      • Inter-contract calls
      • calldata
      • free memory pointer
    • Yul Exercises
      • read state variable
      • read mapping
      • iterate Array, Return Sum
    • memory-safe
  • Upgradable Contracts
    • Upgradability & Proxies
    • UUPS Example
    • Minimal Proxy Example
    • TPP Example
    • 🚧Diamond
      • On Storage
  • Gas Opt
    • Block Limit
    • gasLimit & min cost
    • Solidity Optimiser
    • Memory v calldata
    • Memory caching vs direct storage vs pointers
    • < vs <=
    • reverting early
    • X && Y, ||
    • constant and immutable
    • caching sload into mload
    • Syntactic Sugar
    • using unchecked w/o require
    • Compact Strings
    • Calling a view function
    • Custom errors over require
    • usage of this.
      • multiple address(this)
  • ERCs & EIPs
    • ERC-20.sol
      • Core functions
      • transfer()
      • transferFrom()
      • TLDR transfer vs transferFrom
    • Landing
      • ERC721.sol
      • EIP-721
        • LooksRare
        • Page 1
      • ERC-1271
      • EIP-2981
      • ERC-165
      • EIP-1167: Minimal Proxy Contract
    • VRFConsumerBase
    • UniswapV2Library
  • Yield Mentorship 2022
    • Projects
      • #1 Simple Registry
      • #2 Basic Vault
      • #3 ERC20+ETH Wrapper
        • setFailTransferTrue
      • #4 Fractional Wrapper
      • #5 Collateralized Vault
        • Process
        • Vault.sol
        • Testing
        • Chainlink Oracles
        • Pricing + Decimal scaling
        • Refactor for Simplicity
      • #9 Flash Loan Vault
        • Implementing ERC3156
        • Full code for lender
        • Ex-rate calculation
    • State Inheritance Testing
    • Testing w/ Mocks
    • Yield Style Guide
    • Github Actions
    • TransferHelper.sol
    • math logic + internal fn
    • Interfaces: IERC20
  • Foundry
    • Overview
    • Importing Contracts
    • Testing
      • stdError.arithmeticError
      • assume vs bound
      • Traces
      • label & console2
      • std-storage
  • Smart Contract Security
    • Damn Vulnerable Defi
      • 1. Unstoppable
      • 2. Naive receiver
      • 3. Truster
      • 4. Side Entrance
      • 5. The Rewarder
      • 6. Selfie
      • 7. Compromised
      • 8. Puppet
      • 9. Puppet V2
      • 10 - Free Rider
    • Merkle Tree: shortened proof attack
  • Fixed-Point Math
    • AMM Math
  • Solidity Patterns
    • checks-effects-interactions pattern
    • Router // batch
    • claimDelegate: stack unique owners
    • claimDelegate: cache previous user
  • Array: dup/ascending check
  • Deployment
    • Behind the Scenes
    • Interacting with External Contracts
    • Logging, Events, Solidity, Bloom Filter
  • Misc
    • Mnemonic Phrases
    • Bidul Ideas
  • Archive
    • Brownie Framework
      • Brownie basics
        • storing wallets in .env
        • Deployment to ganache
        • Interacting with contract
        • Unit Testing
        • Testnet deployment
        • Interacting w/ deployed contract
        • Brownie console
      • Brownie Advanced
        • Dependencies: import contracts
        • helpful_scripts.py
        • verify and publish
        • Forking and Mocking
        • Mocking
        • Forking
      • Testing
      • Scripts Framework
        • deploy.py
        • get_accounts
        • deploy_mocks()
        • fund_with_<token>()
      • Brownie Networks
    • Brownie Projects
      • SharedWallet
        • Multiple Beneficiaries
        • Common Code Contract
        • Adding Events
        • Renounce Ownership
        • Separate Files
      • Supply Chain
        • ItemManager()
        • Adding Events
        • Adding unique address to each item
      • Lottery
      • Aave - Lending and Borrowing
        • Approve & Deposit
        • Borrow
      • NFT
      • Advanced Collectible
        • adv_deploy() + Testing
        • Create Metadata
        • Setting the TokenURI
    • node npm
    • Ganache
    • Truffle
    • Remix
    • Installing Env
Powered by GitBook
On this page
  • Gas v Gas Price
  • gasPrice
  • Mining
  1. EVM, Storage, Opcodes

Wei, Ether, Gas

PreviousEVMNextStorage

Last updated 2 years ago

Gas v Gas Price

  • 1 Eth = 10**18 Wei

  • 1 Eth = 10**9 gwei (giga-wei)

Each operation in a contract costs gas: Gas Costs from Yellow Paper

💡 ADD .... 3

MUL .... 5

SUB .... 3

DIV .... 5

So to do a+b, I would need 3 units of gas. But this doesn't tell me how much eth I would pay. That would be determined by gasPrice.

gasPrice

The gasPrice is the value that the transaction sender is willing to pay per unit of gas.

  • Transaction sender is capable of choosing how much he wants to pay per unit of gas.

  • If our transaction needs 3 gas and we are willing to pay 10 Wei per unit of gas, our transaction cost would be 30 Wei in total.

  • unit = wei/gas

💡 The real-world costs of 30 Wei would be determined in the open market -> ETH/USDT

startGas/gasLimit

This is the total units of gas we would want to spend on a specific transaction. Our max total spend.

Why do we need to specify this?

It is not easy to calculate gas costs for certain functions/operations ahead of time. For example, a for loop that runs over a collection of items that could grow or shrink over time.

Example

  • We need to spend 14 gas, and are willing to spend 20 gas. Transaction will be successfully processed.

  • Since we decided to pay 300 wei/gas (gasPrice), our total cost comes to 300 * 14 = 4,200 wei

💡 If we had opted for gasLimit = 10, the function would have halted after the second step, as that is as far as it could go. <Transaction Failed>

Mining

In Ethereum, when a miner mines a new block, it receives the fees from all transactions included in this block. Therefore, the higher the gasPrice in the transactions, the higher the fees that the miner receives will be. The miner also receives a fixed reward per block and a reward for including uncles in the block.

Bob creates the transaction with gasLimit = 100 and gasPrice = 2. Unfortunately, John only has 100 Wei, he can’t set the gasLimit to 200 because that would make the transaction intrinsic cost higher than his current balance. John creates the transaction with gasLimit = 100 and gasPrice = 1.

When it is time to pick a transaction to include in the next block, the miner node is likely to choose the transaction that will reward him more fees. In our example, Bob has set a gasPrice twice as high as John’s gasPrice. Since both transactions have the same gas cost, the miner will receive twice as much Wei as a reward if it chooses Bob’s transaction.

This mechanism of charging the transaction sender and rewarding the miner creates a self-regulated economy. The senders are always trying to minimise fees and the miners always trying to maximize their reward. When sending a transaction, you can set a higher gasPrice to make mining this transaction more interesting to miners, resulting in the transaction being mined faster.

Some miners even have a minimum gasPrice, meaning they ignore any transactions with a gasPrice lower than what they want.

Describe the difference between gas cost and gas price.

  • Gas is the number of units of computational effort required to execute specific operations on Ethereum

  • Gas price is the cost of each unit of gas

What is the max gas of each block?

  • Each block has a target size of 15 million gas, but the size of blocks will increase or decrease according to network demand, up until the block limit of 30 million gas

What happens when the gas limit specified is more than the gas consumed?

  • Gas limit refers to the maximum amount of gas you are willing to consume on a transaction. Any gas not used in a transaction is refunded to the user.

What happens to gas when a transaction fails / if there is not enough gas in a transaction?

  • If too little gas is specified, the EVM will consume all the gas units attempting to fulfill the transaction, but it will not complete. The EVM then reverts any changes, but since the validator has already done 20k gas units worth of work, that gas is consumed.

What are some methods to optimize gas?

  • Compared to regular state variables, the gas costs of constant and immutable variables are much lower. For a constant variable, the expression assigned to it is copied to all the places where it is accessed and also re-evaluated each time. This allows for local optimizations. Immutable variables are evaluated once at construction time and their value is copied to all the places in the code where they are accessed.

Valid uncle blocks are rewarded to neutralize the effect of network lag on the distribution of mining rewards.

When sending a transaction, it can be hard to know what is the minimum gasPrice at that moment. that scan the network and the average gasPrice used in recent transactions to help with choosing a fair gasPrice that is likely to be accepted by miners.

https://github.com/ethereum/wiki/wiki/Mining#mining-rewards
There are some tools