RandomWits

life is too short for a diary




Mastering Ethereum: Implementing Smart Contracts

Tags: blockchain ethereum books

Author
Written by: Tushar Sharma
Featured image for Mastering Ethereum: Implementing Smart Contracts
These are my rough notes while reading the book.

Aug 15, 2026

Ethereum is an unbounded state machine.

Unbounded means the state is not a fixed small table. Ethereum's global state can keep growing as accounts, balances, contract code, and contract storage change. In practice it is still bounded by gas, storage cost, and protocol limits.

Ethereum has the EVM (Ethereum Virtual Machine), which applies valid transactions to the current state and produces the next state.

A state machine is a system where current state + input gives the next state. In Ethereum, the input is a transaction, and the output is the updated global state.

Comparison between Bitcoin and Ethereum

  1. Both are permissionless and open.

  2. Participants use a P2P network to communicate without a trusted third party. Each node can act as both a client and a server. There is no dedicated central server.

HTTP is commonly used in a client-server model. Browser sends a request and server returns a response. The payload can follow different conventions, such as JSON for REST APIs, XML for SOAP, or binary formats for gRPC.

A gossip protocol is a way for nodes in a P2P network to spread information by forwarding it to some of their peers, who then forward it to more peers. Instead of one central server broadcasting to everyone, information propagates through the network.

  1. Both need consensus because nodes have to agree on valid writes to the ledger.

Byzantine means faulty or malicious behavior in a distributed system. Bitcoin uses Nakamoto consensus with proof-of-work. Ethereum now uses proof-of-stake, with validators and finality rules. Both systems are designed for a network where some nodes cannot be trusted.

  1. Both use a native digital currency. Ethereum uses ether (ETH), and Bitcoin uses bitcoin (BTC).

Bitcoin is the network/protocol, and bitcoin is the currency unit used on that network. The ticker symbol is BTC.

  1. Both use digital signatures and hashes. A hash is a one-way function that generates a fixed-length output from arbitrary input. It is easy to compute the hash from the input, but infeasible to recover the original input from only the hash.

Types of blockchain

  Permissionless Permissioned
Private Usually not useful Canton
Open Bitcoin, Ethereum Hedera

Permissioned: Only authorized validators can participate in consensus.

Permissionless: Anyone can participate in consensus.

Open: Anyone can view the data.

Private: Only authorized parties can view the data.

Ethereum components

  1. P2P network.

  2. Ethereum nodes run two main clients: a consensus client and an execution client. Validators also run validator client software. The consensus client handles proof-of-stake consensus. The execution client executes transactions and smart contracts. Contract code and storage are part of Ethereum state, and transactions change this singleton global state.

  3. The EVM executes EVM bytecode. A high-level language like Solidity can be compiled into this bytecode.

Turing Complete

Ethereum is often described as a Turing-complete distributed state machine. More precisely, the EVM instruction set is Turing complete, but every real transaction is bounded by gas. Let's understand Turing completeness.

Alan Turing described a state machine that can change symbols by reading from and writing to sequential memory. This model is called a Turing machine. Universal computability is the idea that a machine can compute anything that is computable, given enough time and memory.

Not all questions about programs are decidable. For example, the halting problem asks whether, given any arbitrary program and input, we can always determine whether that program will eventually stop. In other words, can we build a perfect function like this?

halts(program, input) -> True if program(input) stops, else False

Turing's idea was proof by contradiction. Suppose this perfect halts function exists. Now create another program that uses halts and then does the opposite:

def strange(program):
  if halts(program, program):
    while True:
      pass
  else:
    return

Now ask: what happens if we run strange(strange)?

If halts(strange, strange) says it will halt, then strange goes into an infinite loop. So the prediction is wrong.

If halts(strange, strange) says it will not halt, then strange returns immediately. So the prediction is wrong again.

This contradiction means the perfect halts function cannot exist. It is not that we cannot decide simple programs. We can. The point is that there is no one general algorithm that works for every possible program and input.

The system that can simulate a Turing machine is called Turing complete. A machine that can simulate any other Turing machine is called a Universal Turing Machine.

Universal means it is not built for only one specific computation. It can take another machine's description and input, then simulate that machine's behavior.

So Ethereum is not literally an unlimited Universal Turing Machine while executing a transaction. Better way to say it: EVM programs can express arbitrary computation, but execution stops when gas runs out.

Turing completeness can be implemented with a surprisingly small machine. Even SQL can be Turing complete in some forms. This creates a problem: if Ethereum can execute arbitrary programs, it cannot know in general whether a program will end.

Ethereum adds gas. Gas is the unit used to meter computation, storage, and transaction execution. Each transaction includes a gas limit, which is the maximum gas the sender is willing to spend. Gas is paid for using ether. This prevents a smart contract from running forever because execution stops when gas runs out.

Dapp

Dapp means decentralized application. In practice it usually means smart contracts plus a web interface, so users interact with blockchain logic through a browser and wallet.

Web1 generally means the early read-only web: mostly static pages connected by hyperlinks. It was created by Tim Berners-Lee at CERN around 1989-1991. Web2 refers to the interactive and social web, where users create content and platforms manage much of the data. Web3 refers to applications that use blockchains, wallets, tokens, and decentralized protocols.

Aug 16, 2026

Ether is the native currency of Etherium. It is used to pay gas fees and transfer value. Every transcation that is sent to Ethereum and executed by EVM needs gas, even if it fails. Read only operations are free when called locally, because they are not stored on-chain.

After EIP-1559, gas fee has base fee and priority fee. Base fee is burned and priority fee goes to the validator.

1 gwei = 10^9 wei

1 ETH = 10^9 gwei = 10^18 wei

Wallets stores keys. It could be software or hardware. Software wallets can also create and broadcast transcations.

Private keys authorize the ownership of the address. They also authorize transcations by signing them.

Funds are not inside the wallet. Funds are in Ethereum state. Wallet just stores the key that can sign transcations from that address.

Metamask is one such wallet. There's a chrome extension or from their website.

Wallet generates a private key. Next you can generate public key from your private key. The last 20 bytes of hash of your public key is your address.

private key is generated randomly

public key is generated from private key using elliptic curve cryptography (secp256k1)

address = last 20 bytes of Keccak-256 hash(public key)

In Ethereum, public key is usually hashed without the 0x04 uncompressed public key prefix. The rightmost 20 bytes of the Keccak-256 hash becomes the address.

Transcations use addresses to transfer ether or interact with contracts. to is inside the transcation. from is recovered from the digital signature. Transcations are stored inside blocks, and blocks are cryptographically linked using the parent block hash.

An address can logically look like 0x23..1bc
   ETH balance
   transcations count nonce
   contract storage
   Smart contract code

Nonce is number used once. Different blockchain uses nonce differently. In Ethereum, nonce is not a block id. For EOA, nonce counts the number of transcations sent from that account. For contract account, nonce counts the number of contracts created by that account.

Bitcoin uses UXTO model, where miners use nonce to perform proof of work.

What's differnce between private and public key? Previously you had one private key that was used to encryptt and decrypt messages. However it causes isses to securely distribute private key.

Public key solves that. Every use will have a pair of (public and private key). Public key can be broadcasted to all.

For scenario 1, Alice wants to send secure message to Bob. Alice will take just use Bob's public key to encrypt the message. Now Bob can decrypt the message with his private key. Bob didn't had to send ALice his private key.

Alice does not need her private key for encryption to Bob. She only needs Bob's public key. Her private key is needed when she wants to sign something.

For scenario 2, Alice can digital signed the message with her private key, and anyone can verify using her public key that it was signed by Alice.

Etherium has various neetwork

  1. Main network
  2. private network like localhost
  3. Testnet like Sepolia
  4. Holešky network

Gas fees are paid by the Sender. There are 3 types of transcations

  1. Ether transfer : It has to, value, nonce, gas limit, gas fee fields and signature. Data field is empty. from is recovered from signature. Used for transfer ether

  2. Contract deployment: To is empty, & data load is contract bytecode

To is empty/null, not the zero address. Data contains init code and contract bytecode.

  1. Contract Interaction: Transcation has encoded function call in the data field.

EVM is the execution environment for Ethereum. Each full node runs the EVM and maintains the same world state after processing the same chain of blocks. There are two types of accounts in Ethereum

  1. Externaly owned account (EOA) : IT has a private key. Used for sending ether or accessing contract code

  2. Contract Account: It doens't have private key. canot initiate transcations.

Contract account cannot initiate top-level transcations because it has no private key to sign a transcation. But contract code can call other contracts during execution when an EOA or another contract triggers it.

What's a facuet? A service or smart contract in testnet that gives out test ether to any address and can be refilled. Faucets exist because developers need testnet ETH to deploy and test contracts without spending real ETH.

Aug 22, 2026

Lets revise a smart contract is written in high lelel programing language like Solidity and is converted to bytecode. A simple program:

pragma solidity 0.8.34;

//SPDX-License-Identifier: GPL-3.0

contract Faucet {
    function withdraw(uint256 _withdrawAmount, address payable _to) public {
        require(_withdrawAmount <= 100000000000);

        _to.transfer(_withdrawAmount);
    }

    // Function to receive ether when msg.data is empty
    receive() external payable {}

    // Function called when msg.data is not empty or no function matches
    fallback() external payable {}
}

Faucet is a smart contract that can transfer ether to another payable address.

How do you register a smart contract?

Create a special transaction called a contract-creation transaction. It does not have a normal destination address (to is empty / null); instead, the contract's initialization bytecode goes in the transaction data.

Example shape:

{
  "from": "0xYourEOA...",
  "to": null,
  "value": "0x0",
  "data": "0x<contract init bytecode>"
}

Deploying a smart contract is not free. You pay gas for executing the initialization code and for storing the contract bytecode on-chain.

After successful deployment, the contract address is determined automatically by Ethereum. The deployer does not manually choose a normal contract address.

Internal calls: calls made by a smart contract while executing a top-level transaction. Top-level transactions are created and signed by externally owned accounts (EOAs).

Ethereum node

You can run full ethereum node. For that you need to download two clients :

  1. for execution e.g. Geth
  2. for consensus e.g. Prysm

Other alternative is to use remote clients that can be connected to other ethereum node. They are also called wallets. e.g. metamask, coinbase wallet, etc.

Etherum clients can execute set of RPC commands over API. This is called JSON-RPC API and it follows specification

Remote clients don't validate block headers or transcations. This is done by light client in Bitcoin.

Cool trick , on termianl you can convert hexadecimal to decimal

echo $((0x123234))

Sep 20, 2026

Ethereum has two types of accounts, and each account is identified by an address:

  1. EOA

  2. Contract

An EOA is controlled by a private key, so it can create and sign transactions. Both EOAs and contract accounts can hold ether. A blockchain links blocks using cryptographic hashes. A simplified view of an Ethereum transaction looks like this:

Field Value
From Address recovered from the signature
To Recipient address, or empty for contract creation
Value Amount of ether to transfer
Data Input data or contract initialization code

For contract creation, the data field contains initialization bytecode. A smart contract is code stored on the ledger. It runs in the EVM when invoked by a transaction or another contract.

A contract account holds smart contract code and storage once it is created.

Public-key cryptography

With symmetric cryptography, if Alice wants to send a secret message to Bob, she encrypts it with a secret key and must securely share that key with Bob. This creates a key-distribution risk.

In a public-key encryption system, Bob creates a pair of private and public keys. He shares his public key, which Alice can use to encrypt a message that Bob can decrypt using his private key. This is a general cryptography example; Ethereum uses its key pairs to sign transactions rather than encrypt them.

A private key is just a long random number. In Ethereum, it is a 256-bit number within the valid secp256k1 key range.

Ethereum uses an elliptic curve over a finite field to derive a public key from a private key. Public keys are points on the elliptic curve, and their coordinates are elements of the finite field.

The curve equation is:

y^2 = x^3 + 7  (mod p)

There is a generator point that is fixed for everyone. The private key is multiplied by it to get a new point, which is the public key.

Ethereum transactions can:

  1. Transfer ether to an EOA or contract

  2. Call a smart contract, optionally transferring ether

  3. Create a smart contract by leaving the to field empty and putting initialization code in the data field

Reading from a smart contract does not require a transaction or cost gas. The call is executed locally by a node without changing blockchain state, although an RPC provider may charge for access.

Oct 3, 2026

Wallets, keys, and ownership

A wallet is like a keychain: it manages private keys and the addresses derived from them. The keys let me authorize actions; the wallet does not hold the ether or tokens themselves. Native ether is recorded in Ethereum account balances. Token balances or ownership are usually recorded in a token contract's state.

What's a token? Is it a transaction that lives on the blockchain?

No. A token is an asset represented by a smart contract. For example, an ERC-20 contract tracks balances, while an ERC-721 contract tracks which address owns each token ID. Transactions can change that state; they are not the tokens.

How do I prove ownership of a token?

First check the token contract's current state to see which address holds the balance or owns the token ID. To prove I control that address, I can sign a message with its private key (or satisfy the authorization rules of a smart contract account). A valid signature alone proves control of an address, not that the address currently owns a particular token. To transfer a token from an EOA, I sign a transaction that calls the token contract; the contract checks its rules and updates its state.

Where wallet keys come from

  1. Nondeterministic wallet: Its private keys are generated independently, so each key needs its own backup.
  2. Deterministic wallet: Its keys are derived from one starting secret, so the same starting secret and derivation paths can recreate them.

What's a mnemonic code?

A mnemonic (seed phrase) is a human-readable way to back up the starting secret. In the common BIP-39 scheme, the words plus an optional passphrase produce a seed; an HD wallet then derives keys from it. The words, passphrase (if used), and derivation paths must match to recover the same accounts. The seed phrase is not a public address and must stay secret.

An HD (hierarchical deterministic) wallet organizes derived keys into a tree, so I can use different accounts and addresses from one backup. The hierarchy is useful for organization and recovery; it does not make an exposed seed phrase safer. Anyone with that phrase (and the passphrase, if one was used) can derive the keys.

How do I make a disaster-recovery copy of my seed?

Record the phrase accurately on a durable offline medium, keep the backup in a separate secure place, and verify that recovery works. If I use a BIP-39 passphrase, I need to back that up securely too: the same words with a different passphrase produce different accounts. I should never put the phrase in these notes, a screenshot, cloud storage, or a website.

Proposals and accounts

  • EIP (Ethereum Improvement Proposal): The umbrella process for proposing Ethereum standards and changes. Some EIPs change the protocol; others specify standards used by applications.
  • ERC (Ethereum Request for Comments): An application-level standards category within the EIP process, such as ERC-20 or ERC-721. An ERC is therefore also an EIP.
  • RIP (Rollup Improvement Proposal): A proposal for standards or improvements shared across Ethereum rollups. It does not automatically change Ethereum mainnet.

Ethereum has two basic account types:

  1. EOA (externally owned account): An account controlled by a private key. Its key can sign transactions.
  2. Contract account: An account with code. Its code defines what it does when called; it does not have its own private key.

What is account abstraction (AA), and why use a smart wallet?

Account abstraction lets an account use programmable authorization instead of relying only on one EOA key. A smart wallet is wallet logic implemented in a contract. Depending on its design, it can support multiple signers, spending limits, batched actions, sponsored fees, or recovery rules. These are possible features, not guarantees of every smart wallet. ERC-4337 is one approach: a user submits a UserOperation that is validated and executed by a smart account through an EntryPoint contract.

EIP-7702 lets an EOA execute smart contract code. How does that work?

Think of A as my existing EOA address and B as an already deployed contract containing wallet logic:

  1. A signs an EIP-7702 authorization naming B as its delegate.
  2. A type-4 transaction includes that authorization. The transaction sender can be A or someone else submitting it for A.
  3. Ethereum stores a delegation marker in A's code, pointing to B. When A is called, Ethereum executes B's code in A's context: A's address, balance, and storage are used.

So A does not become B, and A's ether and tokens do not move to B. A keeps its address and private key; the delegated code adds programmable behavior at A. The choice of B matters because its code can act with A's assets. A's private key can still send transactions and change the delegation, so code-based spending limits cannot protect against someone who has that key. Revoking or changing the delegation requires a new authorization and transaction.

What's a guardian? Does it have to be another EOA?

A guardian is an address or other authority that a particular wallet's recovery design trusts to help approve recovery. It might be an EOA or a smart contract account, depending on that wallet's rules. Ethereum does not assign guardians to all accounts, and a guardian cannot recover an ordinary EOA just because it is named as one.

Other notes

ENS: Similar to DNS in that a readable name can resolve to an address. The name's owner configures its records; I still need to verify that a name resolves to the intended address before sending assets.

ERtool: Emergency tool used by Blockdaemon to get the original master private key and RSA decryption key. This is separate from the Ethereum wallet concepts above; I need to check the tool's documentation for its exact recovery process.

Oct 10, 2026

The Ethereum blockchain is:

  1. open = anyone can read it
  2. permissionless = anyone who meets the protocol requirements can become a validator

Transactions

Ethereum is a global singleton state machine. You need to create a transaction to change its state.

Transactions are signed messages included in the blockchain. They can originate only from EOAs because only EOAs have private keys.

A transaction can:

  1. Transfer ETH from one account to another

ETH can be held by an EOA or a smart contract.

  1. Invoke a smart contract

To read a smart contract without changing state, we can use eth_call, which is simulated by a node and does not create an on-chain transaction or require a gas fee.

Components of a transaction

Usually, it looks like:

to: <EOA or contract address>
gasLimit
maxFeePerGas
maxPriorityFeePerGas
data
value
nonce
chainId

Chain ID identifies a blockchain network. It prevents a transaction signed for one chain from being replayed on another chain.

Nonce: It is a sequential number. EOAs use it to order transactions and prevent replay.

Data: calldata for a contract call, or initialization bytecode for contract creation.

Value: ETH, denominated in wei.

How to create a new smart contract?

You send a special transaction with an empty to field. The data contains the contract's initialization bytecode.

Bytecode is commonly displayed in hexadecimal, but it is machine-readable rather than human-readable.

For CREATE, the contract address is deterministic and is derived from the creator's address and nonce. CREATE2 instead uses the creator's address, a salt, and a hash of the initialization code.

How to invoke a smart contract?

For a local read that does not change stored state, use eth_call. To change state, create a transaction:

to: contract address
data: function selector + ABI-encoded function arguments

The function selector is the first 4 bytes of the Keccak-256 hash of the function signature.

The function signature is not a digital signature. A function signature consists of the function name and its parameter types.

Foundry

Cast is a tool included with Foundry. You can create a new account:

cast wallet new

This creates a new private-public key pair. The public key is a point on the secp256k1 elliptic curve. It is derived by multiplying the private key by the curve's generator point.

The account address is derived from the last 20 bytes of the Keccak-256 hash of the uncompressed public key, excluding its 0x04 prefix.

For CREATE: contract address = last 20 bytes of keccak256(rlp([creator address, nonce])).

You can import a private key into Foundry's encrypted keystore:

cast wallet import example --private-key

Check the ETH balance of an EOA or contract address:

cast balance 0x...

Digital signature: Created with a private key, but anyone can validate it using the public key.

Multisig: Safe is an example of an on-chain smart wallet that supports multiple signers.


comments powered by Disqus