Unit3 SCSA1615 Smartcontract Final
Unit3 SCSA1615 Smartcontract Final
1
Step 4: Use the Remix browser to write your smart contract.
You can use the editor in Remix browser IDE to write your smart contract in Solidity. Remix
browser is the best option for writing smart contracts as it comes with several features and is
usually used to write basic smart contracts.
A step-by-step guide to creating and deploying Ethereum Smart Contracts with Solidity
Installing Prerequisites
Meta-mask Chrome Extension
MetaMask acts both as an Ethereum browser and a wallet. It allows the user to interact
with smart contracts and dApps on the web without downloading the blockchain or
installing any software. The user only need to add MetaMask as a Chrome Extension,
create a wallet and submit Ether.
Though MetaMask is currently available for Google Chrome browser, it is expected to
launch for Firefox too in the coming years.
Download MetaMask chrome extension before you start writing smart contracts.
Once it is downloaded and added as a Chrome extension, you can either import an already
created wallet or create a new wallet.
The user must have some ethers in your Ethereum wallet to deploy Ethereum smart contract
on the network.
2
Steps to develop an Ethereum Smart Contract
Step 1: Create a wallet at meta-mask
Install MetaMask in your Chrome browser and enable it. Once it is installed, click on its
icon on the top right of the browser page. Clicking on it will open it in a new tab of the
browser.
Click on “Create Wallet” and agree to the terms and conditions by clicking “I agree” to
proceed further. It will ask you to create a password.
After the user create a password, it will send to a secret backup phrase used for backing up
and restoring the account. Do not disclose it or share it with someone, as this phrase can
take away the user Ethers.
The user should either write this phrase on a piece of paper securely or store it safely on an
external encrypted hard drive where no one could find it.
The next step is to ensure that you are in the “Main Ethereum Network.” If you find a
checkmark next to “Main Ethereum Network”, you are in the right place.
3
Step 2: Select any one test network
The user might also find the following test networks in the user MetaMask wallet:
Robsten Test Network
Kovan Test Network
Rinkeby Test Network
Goerli Test Network
The above networks are for testing purposes only; note that these networks’ ethers have no real
value.
4
To proceed, the user need to click “request one ether from the faucet,” and 1 ETH will be added
to the user wallet. The user can add as many Ethers the user want to the test network.
5
Once the dummy ethers are added to the wallet, the user can start writing smart contracts on the
Remix Browser IDE in the Solidity programming language.
6
Step 6: A sample smart contract code to create ERC20 tokens
ERC20.sol is a standard template for ERC20 tokens.
pragma solidity ^0.4.0;
import "./ERC20.sol";
contract myToken is ERC20{
mapping(address =>uint256) public amount;
uint256 totalAmount;
string tokenName;
string tokenSymbol;
uint256 decimal;
constructor() public{
totalAmount = 10000 * 10**18;
amount[msg.sender]=totalAmount;
tokenName="Mytoken";
tokenSymbol="Mytoken";
decimal=18;
}
function totalSupply() public view returns(uint256){
return totalAmount;
}
function balanceOf(address to_who) public view
returns(uint256){
return amount[to_who];
}
function transfer(address to_a,uint256 _value) public
returns(bool){
require(_value<=amount[msg.sender]);
amount[msg.sender]=amount[msg.sender]-_value;
amount[to_a]=amount[to_a]+_value;
return true;
}
}
Select a version of the compiler from Remix to compile the solidity Ethereum smart contract code.
7
Steps to test an Ethereum smart contract
1. Try to run all your smart contract methods like transfer, total supply, and balance (in the
above smart contract example). These methods are present at the right-hand side of the
remix window and you can run all the processes from there itself.
2. Try to transfer some tokens to other ethereum wallet addresses and then check the balance
of that address by calling the balance method.
3. Try to get total supply by running the total supply method.
8
3.2.ACCOUNT TYPES, GAS AND TRANSACTIONS
3.2.1. What is an Ethereum account?
An Ethereum account is an entity with an ether (ETH) balance that can send transactions on the
chain. These accounts are either user-controlled (human) or deployed as smart contracts (code-
dependent). Transactions, which change the state of the Ethereum Virtual Machine (EVM), need
to be broadcast to the network. Any node can broadcast a request for a transaction to be executed
on the EVM. After this happens, a block producer will execute the transaction and propagate the
resulting state change to the rest of the Ethereum network. Transactions require a fee and must be
mined to become valid.
9
a transaction. A public key’s hash acts as the account number to which Ether can be sent. However,
the last 20 bytes of the hash of the public key, also known as the address, are enough to send Ether.
This account also has some other state fields, which make it functional. These fields are explained
below:
Nonce: This represents the number of transactions initiated by the account.
Balance: This represents the balance of the account in Wei.
CodeHash: Empty string as EOA does not have any associated code.
Storage: Empty string as EOA does not have any data to store.
An externally owned address is an account with a public and private key pair holding one’s funds.
It is the ‘public’ address required to receive funds from another party. To access the funds, one
must have its private key. Caution is needed; a private key gives access to all the funds in
an address. A wallet is an interface for managing an Ethereum account—as well as its public and
private key. Get an Ethereum address or account to both send and receive funds. Visit
the Etherscan Directory for a list of wallets.
10
Benefits of EOA:
Zero Cost Creation: Creating an Externally Owned Account (EOA) does not incur any
fees, making it an accessible option for users. This is especially important for Networks
like Ethereum Mainnet, where gas costs are higher.
Versatile Transaction Initiation: EOAs can initiate any transaction on the Ethereum
network, allowing users to interact with various decentralized applications and perform a
wide range of operations.
Limitations of EOA:
Private Key Dependency: EOAs require the secure management of a private key. Users
must protect their private key to ensure the security and control of their EOA, as it grants
access to account functions and funds.
Native Token Dependency for Gas: To perform transactions or execute operations on
the Ethereum network, EOAs must hold native tokens such as Ether (ETH) to cover gas
fees. These tokens must pay for the computational resources utilized during transaction
validation and execution.
11
Contract accounts code execution is triggered by transactions or messages (calls) received from
other contracts.
when executed - perform operations of arbitrary complexity (Turing completeness) -
manipulate its own persistent storage, i.e., can have its own permanent state - can call other
contracts
All action on the Ethereum block chain is set in motion by transactions fired from externally
owned accounts. Every time a contract account receives a transaction, its code is executed as
instructed by the input parameters sent as part of the transaction. The contract code is executed
by the Ethereum Virtual Machine on each node participating in the network as part of their
verification of new blocks.
This execution needs to be completely deterministic, its only context is the position of the
block on the blockchain and all data available. The blocks on the blockchain represent units of
time, the blockchain itself is a temporal dimension and represents the entire history of states at
the discrete time points designated by the blocks on the chain.
All ether balances and values are denominated in units of wei: 1 ether is 1e18 wei.
"Contracts" in Ethereum should not be seen as something that should be "fulfilled" or
"complied with"; rather, they are more like "autonomous agents" that live inside of the
Ethereum execution environment, always executing a specific piece of code when "poked" by
a message or transaction, and having direct control over their own ether balance and their own
key/value store to store their permanent state.
A contract address hosts a collection of code on Ethereum that executes functions. The
functions are executed when a transaction with associated input data (contract interaction)
is made. Such addresses are created when a contract is deployed to the blockchain. Both
the externally owned and contract addresses share the same format of 42-hexadecimal
characters.
12
Etherscan distinguishes between the two types by displaying the contract Creator field for
contract addresses per the example above. Then, for token contracts, there is a Token
Tracker field just below the contract Creator field. We also display Contract instead of
Address and provide a Contract tab for users to view and interact with the contract.
Custom Logic and Functionality: Smart Contract Accounts (SCAs) allow developers to
build custom logic and functionality directly into the account. By deploying smart contracts
to control SCAs, developers can create innovative and customized features, enabling
advanced capabilities and automated operations within the wallet.
Gas Abstraction and Fee Sponsorship: SCAs offer gas abstraction, simplifying gas fee
management for end-users. Developers can implement mechanisms, such as the paymaster
pattern, to sponsor gas fees on behalf of users. This reduces the burden on users to hold
and manage native tokens for gas and enhances the overall user experience by providing a
seamless gas fee payment process.
Gas Tokens Required for Creation: Gas tokens are required when creating SCA wallets.
However, emerging solutions like the one implemented in Programmable Wallets address
this limitation by introducing a lazy deployment mechanism. This process postpones the
gas fee payment until the first outbound transaction, easing the initial cost burden of SCA
wallet creation.
13
Transactions from an external
account to a contract account can
Transactions between externally-
Transferring trigger code, which can execute many
7 owned accounts can only be ETH
Tokens different actions—such as
transfers.
transferring tokens or which can
execute many different.
3.2.2. GAS
What is Gas?
Gas refers to the unit that measures the amount of computational effort required to execute specific
operations on the Ethereum network.
Gas in Ethereum refers to the additional fee required to execute a smart contract or transaction
on the blockchain network.
Since each Ethereum transaction requires computational resources to execute, those resources
have to be paid for to ensure Ethereum is not vulnerable to spam and cannot get stuck in
infinite computational loops. Payment for computation is made in the form of a gas fee.
The gas fee is the amount of gas used to do some operation, multiplied by the cost per unit
gas. The fee is paid regardless of whether a transaction succeeds or fails.
Wei is the smallest unit of ether.
Gas is the name for the execution fee that senders of transactions need to pay for every
operation made on an Ethereum blockchain. The name gas is inspired by the view that this
fee acts as cryptofuel, driving the motion of smart contracts.
Gas is purchased for ether from the miners that execute the code. Gas and ether are decoupled
deliberately since units of gas align with computation units having a natural cost, while the
price of ether generally fluctuates as a result of market forces.
The two are mediated by a free market: the price of gas is actually decided by the miners, who
can refuse to process a transaction with a lower gas price than their minimum limit. To get
gas you simply need to add ether to your account.
The Ethereum clients automatically purchase gas for your ether in the amount you specify as
your maximum expenditure for the transaction.
Types of gas
Different terms associated with gas on a technical level.
Gas price
Start gas/gas limit
Gas price:
It is the amount of Wei the sender of the transaction is willing to pay per unit of gas to get
the transaction processed.
Example: So, if we offer a gas price of 10, that means we are willing to pay 10 * 3 = 30 to add
two numbers.
14
Start gas/gas limit:
It is the maximum units of gas that the sender is willing to pay to perform the transaction.
Example: we say that we need 14 gas limit or start gas for the above code. However, we can't
always compute the gas limit ahead of time. An example would be a for loop over a collection of
records that grow or shrink in size over time. So, the purpose of the gas limit is to say we are
willing to pay at most this many units of gas to call this function.
The important thing is that if our gas limit is more than the actual gas used, we'll be returned
the remaining amount.
But, if the gas limit is less than the actual gas needed to execute the code, we'll lose our
gas, and the transaction will fail.
15
But importantly they are not there for optimal computation. The fact that contract executions
are redundantly replicated across nodes, naturally makes them expensive, which generally
creates an incentive not to use the blockchain for computation that can be done offchain.
When you are running a decentralized application (dapp), it interacts with the blockchain to
read and modify its state, but dapps will typically only put the business logic and state that are
crucial for consensus on the blockchain.
When a contract is executed as a result of being triggered by a message or transaction, every
instruction is executed on every node of the network. This has a cost: for every executed
operation there is a specified cost, expressed in a number of gas units.
How gas is working on Ethereum Protocol?
The Ethereum protocol charges a fee per computational step that is executed in a contract or
transaction to prevent deliberate attacks and abuse on the Ethereum network.
Every transaction is required to include a gas limit and a fee that it is willing to pay per gas.
Miners have the choice of including the transaction and collecting the fee or not.
If the total amount of gas used by the computational steps spawned by the transaction,
including the original message and any sub-messages that may be triggered, is less than or
equal to the gas limit, then the transaction is processed.
If the total gas exceeds the gas limit, then all changes are reverted, except that the transaction
is still valid and the fee can still be collected by the miner.
All excess gas not used by the transaction execution is reimbursed to the sender as Ether.
You do not need to worry about overspending, since you are only charged for the gas you
consume. This means that it is useful as well as safe to send transactions with a gas limit well
above the estimates.
Calculating Gas Costs
For any given program, the total gas used is calculated as the sum of the gas for each operation
executed by the Ethereum Virtual Machine. For example, adding two numbers in a smart contract
costs 3 gas, whereas sending a transaction costs 21,000 gas.
The total cost of gas is found by taking the amount of gas used in by a smart contract and
multiplying by the gas price, a value set by you, the transaction sender.
16
Gas: How does it work?
Transactions are initiated based on contracts deployed to the network, and there is a gas fee
attached to every transaction. Ethereum transactions require computational resources. The amount
of computational power required for a transaction determines the gas fee.
Estimating transaction costs
The total ether cost of a transaction is based on 2 factors:
gasUsed is the total gas that is consumed by the transaction
gasPrice price (in ether) of one unit of gas specified in the transaction
Total cost = gasUsed * gasPrice
gasUsed
Each operation in the EVM was assigned a number of how much gas it consumes. gasUsed is the
sum of all the gas for all the operations executed. There is a spreadsheet which offers a glimpse to
some of the analysis behind this.
For estimating gasUsed , there is an estimateGas API that can be used but has some caveats.
gasPrice
A user constructs and signs a transaction, and each user may specify whatever gasPrice they
desire, which can be zero. However, the Ethereum clients launched at Frontier had a default
gasPrice of 0.05e12 wei. As miners optimize for their revenue, if most transactions are being
submitted with a gasPrice of 0.05e12 wei, it would be difficult to convince a miner to accept a
transaction that specified a lower, or zero, gasPrice.
The approximate cost, using the default gas price (as of January 2016), would be:
17
Since 1 ether is 1e18 wei, the total cost would be 0.00000015 Ether.
This is a simplification since it ignores some costs, such as the cost of passing the 2 numbers to
contract, before they can even be added.
stop 0 free
suicide 0 free
sha3 20
balance 20
18
Major limitations when it comes to running smart contracts:
Every deployed transaction, smart contract, or execution of a smart contract, must be run on
every single full node on the Ethereum blockchain to guarantee validity. This is wildly
inefficient (though newer blockchains are streamlining this)!
Because smart contracts are Turing complete, they can potentially execute forever, locking up
every single node on the blockchain.
1. Any Turing complete language can theoretically be used to represent the logic of another
Turing complete language, though the implementation may be unreasonably long.
2. Turing complete programs can end up looping and executing forever. In fact, there is no
universal way to prove that such a program will not end up running forever (otherwise
known as the "halting problem").
For example, a regular calculator is not Turing complete, because it allows for only a few
types of calculations. However, a computer or scientific calculator is Turing complete because
any type of program can be executed on it.
3.3.3. TRANSACTIONS
What is a transaction?
The term "transaction" is used in Ethereum to refer to the signed data package that stores a message
to be sent from an externally owned account to another account on the blockchain.
Transactions contain:
the recipient of the message,
a signature identifying the sender and proving their intention to send the message via the
blockchain to the recipient,
VALUE field - The amount of wei to transfer from the sender to the recipient,
an optional data field, which can contain the message sent to a contract,
a STARTGAS value, representing the maximum number of computational steps the
0.000000000000000001 Ether.
19
What is a message?
Contracts have the ability to send "messages" to other contracts. Messages are virtual objects that
are never serialized and exist only in the Ethereum execution environment. They can be conceived
of as function calls.
A message contains:
the sender of the message (implicit).
the recipient of the message
VALUE field - The amount of wei to transfer alongside the message to the contract
address,
an optional data field, that is the actual input data to the contract
a STARTGAS value, which limits the maximum amount of gas the code execution
transaction, a message leads to the recipient account running its code. Thus, contracts can have
relationships with other contracts in exactly the same way that external actors can.
Account interactions example - betting contract
As previously mentioned, there are two types of accounts:
Externally owned account (EOAs): an account controlled by a private key, and if you own
the private key associated with the EOA you have the ability to send ether and messages from
it.
Contract: an account that has its own code, and is controlled by code.
By default, the Ethereum execution environment is lifeless; nothing happens and the state of every
account remains the same. However, any user can trigger an action by sending a transaction from
an externally owned account, setting Ethereum's wheels in motion. If the destination of the
transaction is another EOA, then the transaction may transfer some ether but otherwise does
nothing. However, if the destination is a contract, then the contract in turn activates, and
automatically runs its code.
20
The code has the ability to read/write to its own internal storage (a database mapping 32-byte keys
to 32-byte values), read the storage of the received message, and send messages to other contracts,
triggering their execution in turn. Once execution stops, and all sub-executions triggered by a
message sent by a contract stop (this all happens in a deterministic and synchronous order, ie. a
sub-call completes fully before the parent call goes any further), the execution environment halts
once again, until woken by the next transaction.
Maintain a data store representing something which is useful to either other contracts or to the
outside world; one example of this is a contract that simulates a currency, and another is a
contract that records membership in a particular organization.
Serve as a sort of externally-owned account with a more complicated access policy; this is
called a "forwarding contract" and typically involves simply resending incoming messages to
some desired destination only if certain conditions are met; for example, one can have a
forwarding contract that waits until two out of a given three private keys have confirmed a
particular message before resending it (ie. multisig). More complex forwarding contracts have
different conditions based on the nature of the message sent. The simplest use case for this
functionality is a withdrawal limit that is overrideable via some more complicated access
procedure. A wallet contract is a good example of this.
Manage an ongoing contract or relationship between multiple users. Examples of this include
a financial contract, an escrow with some particular set of mediators, or some kind of insurance.
One can also have an open contract that one party leaves open for any other party to engage
with at any time; one example of this is a contract that automatically pays a bounty to whoever
submits a valid solution to some mathematical problem, or proves that it is providing some
computational resource.
Provide functions to other contracts, essentially serving as a software library.
Contracts interact with each other through an activity that is alternately called either "calling" or
"sending messages". A "message" is an object containing some quantity of ether, a byte-array of
data of any size, the addresses of a sender and a recipient. When a contract receives a message, it
has the option of returning some data, which the original sender of the message can then
immediately use. In this way, sending a message is exactly like calling a function.
Because contracts can play such different roles, we expect that contracts will be interacting with
each other. As an example, consider a situation where Alice and Bob are betting 100 GavCoin that
21
the temperature in San Francisco will not exceed 35ºC at any point in the next year. However,
Alice is very security-conscious, and as her primary account uses a forwarding contract which only
sends messages with the approval of two out of three private keys. Bob is paranoid about quantum
cryptography, so he uses a forwarding contract which passes along only messages that have been
signed with Lamport signatures alongside traditional ECDSA (but because he's old fashioned, he
prefers to use a version of Lamport sigs based on SHA256, which is not supported in Ethereum
directly).
The betting contract itself needs to fetch data about the San Francisco weather from some contract,
and it also needs to talk to the GavCoin contract when it wants to actually send the GavCoin to
either Alice or Bob (or, more precisely, Alice or Bob's forwarding contract). We can show the
relationships between the accounts thus:
When Bob wants to finalize the bet, the following steps happen:
1. A transaction is sent, triggering a message from Bob's EOA to his forwarding contract.
2. Bob's forwarding contract sends the hash of the message and the Lamport signature to a
contract which functions as a Lamport signature verification library.
3. The Lamport signature verification library sees that Bob wants a SHA256-based Lamport sig,
so it calls the SHA256 library many times as needed to verify the signature.
4. Once the Lamport signature verification library returns 1, signifying that the signature has been
verified, it sends a message to the contract representing the bet.
22
5. The bet contract checks the contract providing the San Francisco temperature to see what the
temperature is.
6. The bet contract sees that the response to the messages shows that the temperature is above
35ºC, so it sends a message to the GavCoin contract to move the GavCoin from its account to
Bob's forwarding contract.
Note that the GavCoin is all "stored" as entries in the GavCoin contract's database; the word
"account" in the context of step 6 simply means that there is a data entry in the GavCoin contract
storage with a key for the bet contract's address and a value for its balance. After receiving this
message, the GavCoin contract decreases this value by some amount and increases the value in the
entry corresponding to Bob's forwarding contract's address. We can see these steps in the following
diagram:
3.3.CONTRACTS
What is a contract?
A contract is a collection of code (its functions) and data (its state) that resides at a specific address
on the Ethereum blockchain.
Contract accounts are able to pass messages between themselves as well as doing
practically Turing complete computation. Contracts live on the blockchain in a Ethereum-
specific binary format called Ethereum Virtual Machine (EVM) bytecode.
Contracts are typically written in some high level language such as Solidity and then
compiled into bytecode to be uploaded on the blockchain.
Other languages also exist, notably Serpent and LLL, which are described further in
the Ethereum high level languages section of this documentation.
23
Dapp development resources lists the integrated development environments, developer
tools that help you develop in these languages, offering testing, and deployment support
among other features.
Below are the different high level languages developers can use to write smart contracts for
Ethereum.
.
Solidity
Solidity is a language similar to JavaScript which allows you to develop contracts and compile to
EVM bytecode. It is currently the flagship language of Ethereum and the most popular.
Solidity Documentation - Solidity is the flagship Ethereum high level language that is used to
write contracts.
Solidity online realtime compiler
Standardized Contract APIs
Useful Ðapp Patterns - Code snippets which are useful for Ðapp development.
Serpent
Serpent is a language similar to Python which can be used to develop contracts and compile to
EVM bytecode. It is intended to be maximally clean and simple, combining many of the efficiency
benefits of a low-level language with ease-of-use in programming style, and at the same time
adding special domain-specific features for contract programming. Serpent is compiled
using LLL.
LLL
Lisp Like Language (LLL) is a low level language similar to Assembly. It is meant to be very
simple and minimalistic; essentially just a tiny wrapper over coding in EVM directly.
Mutan (deprecated)
Mutan is a statically typed, C-like language designed and developed by Jeffrey Wilcke. It is no
longer maintained.
24
Writing a contract
No language would be complete without a Hello World program. Operating within the Ethereum
environment, Solidity has no obvious way of "outputting" a string. The closest we can do is to use
a log event to place a string into the blockchain:
contract HelloWorld {
event Print(string out);
function() { Print("Hello, World!"); }
}
This contract will create a log entry on the blockchain of type Print with a parameter "Hello,
World!" each time it is executed.
Compiling a contract
Compilation of solidity contracts can be accomplished via a number of mechanisms.
> web3.eth.getCompilers();
["lll", "solidity", "serpent"]
This command returns an array of strings indicating which compilers are currently available.
The solc compiler is installed with cpp-ethereum . Alternatively, you can build it yourself.
If your solc executable is in a non-standard location you can specify a custom path to
the solc executable using th --solc flag.
> admin.setSolc("/usr/local/bin/solc")
25
solc, the solidity compiler commandline interface
Version: 0.2.2-02bb315d/.-Darwin/appleclang/JIT linked to libethereum-1.2.0-8007cef0/.-
Darwin/appleclang/JIT
path: /usr/local/bin/solc
You are ready to compile solidity code in the geth JS console using eth.compile.solidity():
26
},
source: 'contract test { function multiply(uint a) returns(uint d) { return a * 7; } }'
}
}
The compiler is also available via RPC and therefore via web3.js to any in-browser Ðapp
connecting to geth via RPC/IPC.
The following example shows how you interface geth via JSON-RPC to use the compiler.
$ geth --datadir ~/eth/ --loglevel 6 --logtostderr=true --rpc --rpcport 8100 --rpccorsdomain '*' --
mine console 2>> ~/eth/eth.log
$ curl -X POST --data '{"jsonrpc":"2.0","method":"eth_compileSolidity","params":["contract test
{ functio
The compiler output for one source will give you contract objects each representing a single
contract. The actual return value of eth.compile.solidity is a map of contract name to contract
object pairs. Since our contract's name is test , eth.compile.solidity(source).test will give you the
contract object for the test contract containing the following fields:
If your source contains multiple contracts, the output will contain an entry for each contract, the
corresponding contract info object can be retrieved with the name of the contract as attribute name.
You can try this by inspecting the most current GlobalRegistrar code:
27
contracts = eth.compile.solidity(globalRegistrarSrc)
Create and deploy a contract
Before you begin this section, make sure you have both an unlocked account as well as some funds.
You will now create a contract on the blockchain by sending a transaction to the empty address
with the EVM code from the previous section as data.
This can be accomplished much easier using the online Solidity realtime compiler or the Mix
IDE program.
var primaryAddress = eth.accounts[0]
var abi = [{ constant: false, inputs: { name: 'a', type: 'uint256' } }]
var MyContract = eth.contract(abi)
var contract = MyContract.new(arg1, arg2, ..., {from: primaryAddress, data:
evmByteCodeFromPreviousSection})
All binary data is serialised in hexadecimal form. Hex strings always have a hex prefix 0x .
Note that arg1, arg2, ... are the arguments for the contract constructor, in case it accepts any. If
the contract does not require any constructor arguments then these arguments can be omitted.
It is worth pointing out that this step requires you to pay for execution. Your balance on the account
(that you put as sender in the from field) will be reduced according to the gas rules of the EVM
once your transaction makes it into a block. After some time, your transaction should appear
included in a block confirming that the state it brought about is a consensus. Your contract now
lives on the blockchain.
The standard way to describe the available functions of a contract is the ABI definition. This object
is an array which describles the call signature and return values for each available contract
function.
28
var Multiply7 = eth.contract(contract.info.abiDefinition);
var myMultiply7 = Multiply7.at(address);
Now all the function calls specified in the ABI are made available on the contract instance. You
can just call those methods on the contract instance in one of two ways.
When called using call the function is executed locally in the EVM and the return value of the
function is returned with the function. Calls made in this manner are not recorded on the blockchain
and thus, cannot modify the internal state of the contract. This manner of call is referred to as
a constant function call. Calls made in this manner do not cost any ether.
You should use call if you are interested only in the return value and use sendTransaction if you
only care about side effects on the state of the contract.
In the example above, there are no side effects, therefore sendTransaction only burns gas and
increases the entropy of the universe.
Contract metadata
In the previous sections we explained how you create a contract on the blockchain. Now we will
deal with the rest of the compiler output, the contract metadata or contract info.
When interacting with a contract you did not create you might want documentation or to look at
the source code. Contract authors are encouraged to make such information available by
registering it on the blockchain or through a third party service, such as EtherChain.
The admin API provides convenience methods to fetch this bundle for any contract that chose to
register.
29
var abiDef = info.abiDefinition
The underlying mechanism that makes this work is is that:
contract info is uploaded somewhere identifiable by a URI which is publicly accessible
anyone can find out what the URI is only knowing the contracts address
These requirements are achieved using a 2 step blockchain registry. The first step registers the
contract code (hash) with a content hash in a contract called HashReg . The second step registers
a url with the content hash in the UrlHint contract. These registry contracts were part of the
from the contract, write out its json serialisation in the given file, calculates the content hash of the
file and finally registers this content hash to the contract's code hash. Once you deployed that file
to any url, you can use admin.registerUrl to register the url with your content hash on the
blockchain as well. (Note that in case a fixed content addressed model is used as document store,
the url-hint is no longer necessary.)
source = "contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"
// compile with solc
contract = eth.compile.solidity(source).test
// create contract object
var MyContract = eth.contract(contract.info.abiDefinition)
// extracts info from contract, save the json serialisation in the given file,
contenthash = admin.saveInfo(contract.info, "~/dapps/shared/contracts/test/info.json")
// send off the contract to the blockchain
MyContract.new({from: primaryAccount, data: contract.code}, function(error, contract){
if(!error && contract.address) {
// calculates the content hash and registers it with the code hash in `HashReg`
// it uses address to send the transaction.
// returns the content hash that we use to register a url
30
admin.register(primaryAccount, contract.address, contenthash)
// here you deploy ~/dapps/shared/contracts/test/info.json to a url
admin.registerUrl(primaryAccount, hash, url)
}
});
geth --datadir ~/dapps/testing/00/ --port 30310 --rpcport 8110 --networkid 4567890 --nodiscover
--maxpeers
Before you can submit any transactions, you need set up your private test chain. See Test
Networks.
// starting miner
miner.start(4);
// sleep for 10 blocks (this can take quite some time).
admin.sleepBlocks(10);
// then stop mining (just not to burn heat in vain)
miner.stop();
balance = web3.fromWei(eth.getBalance(primary), "ether");
After you create transactions, you can force process them with the following lines:
31
miner.start(1);
admin.sleepBlocks(1);
miner.stop();
If you submitted contract creation transaction, you can check if the desired code actually got
inserted in the current blockchain:
An Ethereum node offers a RPC interface. This interface gives Ðapp's access to the Ethereum
blockchain and functionality that the node provides, such as compiling smart contract code. It uses
a subset of the JSON-RPC 2.0 specification (no support for notifications or named parameters) as
serialisation protocol and is available over HTTP and IPC (unix domain sockets on linux/OSX and
named pipe's on Windows).
If you are not interested in the details but are looking for an easy to use javascript library you can
skip the following sections and continue with Using Web3.
32
Conventions
The RPC interface uses a couple of conventions that are not part of the JSON-RPC 2.0
specification:
Numbers are hex encoded. This decision was made because some languages have no or limited
support for working with extremly large numbers. To prevent these type of errors numbers are
hex encoded and it is up to the developer to parse these numbers and handle them appropriately.
See the hex encoding section on the wiki for examples.
Default block number, several RPC methods accept a block number. In some cases it's not
possible to give a block number or not very convenient. For these cases the default block
number can be one of these strings ["earliest", "latest", "pending"]. See the wiki page for a list
of RPC methods that use the default block parameters.
Deploy contract
We will go through the different steps to deploy the following contract using only the RPC
interface.
contract Multiply7 {
event Print(uint);
function multiply(uint input) returns (uint) {
Print(input * 7);
return input * 7;
}
}
The first thing to do is make sure the HTTP RPC interface is enabled. This means for geth we
supply the --rpc flag on startup and for eth the -j flag. In this example we use the geth node on a
private development chain. Using this approach we don't need ether on the real network.
We can verify that the interface is running by retrieving the coinbase address and balance
using curl. Please note that data in these examples will differ on your local node. If you want to
try these command replace the request params accordingly.
33
when we said that numbers are hex encoded? In this case the balance is returned in wei as a hex
string. If we want to have the balance in ether as a number we can use web3 from the geth console.
The next step is to compile the Multiply7 contract to byte code that can be send to the EVM.
> echo 'pragma solidity ^0.4.16; contract Multiply7 { event Print(uint); function multiply(uint input) public returns
(uint) { Print(input * 7); return input * 7; } }' | solc --bin
======= <stdin>:Multiply7 =======
Binary:
6060604052341561000f57600080fd5b60eb8061001d6000396000f300606060405260043610603f576000357c01
0000000000000000000
Now that we have the compiled code we need to determine how much gas it costs to deploy it. The RPC interface has
an eth_estimateGas method that will give us an estimate.
34
383f19d9f65246752244189b02f56e8d0980ed44e7a56c0b200458caad20bb0029"}], "id": 6}' -H "Content-Type:
application/json" localhost:8545
{"id":6,"jsonrpc":"2.0","result":"0xe1f3095770633ab2b18081658bad475439f6a08c902d0915903bafff06e6febf"}
The transaction is accepted by the node and a transaction hash is returned. We can use this hash to
track the transaction.
The next step is to determine the address where our contract is deployed. Each executed transaction
will create a receipt. This receipt contains various information about the transaction such as in
which block the transaction was included and how much gas was used by the EVM. If a transaction
creates a contract it will also contain the contract address. We can retrieve the receipt with
the eth_getTransactionReceipt RPC method.
If we look at the documentation for the eth_sendTransaction we can see that we need to supply
several arguments. In our case we need to specify the from , to and data arguments. From is
the public address of our account and to the contract address. The data argument is a bit harder.
It contains a payload that defines which method must be called and with which arguments. This is
were the ABI comes into play. The ABI defines how to define and encode data for the EVM. You
can read all the details about the ABI here.
35
The bytes of the payload is the function selector and defines which method is called. This is done
by taking the first 4 bytes from the Keccak hash over the function name and its argument types
and hex encode it. The multiply function accepts an uint which is an alias for uint256. This leaves
us with:
The next step is to encode the arguments. We only have one uint256, lets assume we supply the
value 6. The ABI has a section which specifies how to encode uint256 types.
int<M>: enc(X) is the big-endian two's complement encoding of X, padded on the higher-oder
(left) side with 0xff for negative X and with zero bytes for positive X such that the length is a
multiple of 32 bytes.
This encodes to 0000000000000000000000000000000000000000000000000000000000000006 .
Combining the function selector and the encoded argument our data will
be 0xc6888fa10000000000000000000000000000000000000000000000000000000000000006 .
36
Since we sent a transaction we got the transaction hash returned. If we retrieve the receipt we can
see something new:
{
blockHash: "0x55262092dc46db5c7d3595decd4317780896c765c4db69cf2d5f650e46249b13",
blockNumber: 6,
contractAddress: null,
cumulativeGasUsed: 22774,
from: "0x9b1d35635cc34752ca54713bb99d38614f63c955",
gasUsed: 22774,
logs: [{
address: "0x4d03d617d700cf81935d7f797f4e2ae719648262",
blockHash: "0x55262092dc46db5c7d3595decd4317780896c765c4db69cf2d5f650e46249b13",
blockNumber: 6,
data: "0x000000000000000000000000000000000000000000000000000000000000002a",
logIndex: 0,
removed: false,
topics: ["0x24abdb5865df5079dcc5ac590ff6f01d5c16edbc5fab4e195d9febd1114503da"],
transactionHash: "0x50905bea8043e1166703a2a72390f6e6eb4f23150c8e7d13094a6d82ce89a054",
transactionIndex: 0
}],
logsBloom:
"0x000000000000080000000000000000000000000000000000000000000000000400000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000
000000000000000020000000000000000000000000000000000000000000000000208000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000",
status: "0x1",
to: "0x4d03d617d700cf81935d7f797f4e2ae719648262",
transactionHash: "0x50905bea8043e1166703a2a72390f6e6eb4f23150c8e7d13094a6d82ce89a054",
transactionIndex: 0
}
The receipt contains a log. This log was generated by the EVM on transaction execution and
included in the receipt. If we look at the multipy function we can see that the Print event was raised
with the input times 7. Since the argument for the Print event was a uint256 we can decode it
according to the ABI rules which will leave us with the expected decimal 42.
> echo $((0x000000000000000000000000000000000000000000000000000000000000002a))
42
Apart from the data it is worth noting that topics can be used to determine which event created the
log:
> web3.sha3("Print(uint256)")
"24abdb5865df5079dcc5ac590ff6f01d5c16edbc5fab4e195d9febd1114503da"
You can read more about events, topics and indexing in the Solidity tutorial.
37
This was just a brief introduction into some of the most common tasks. See for a full list of
available RPC methods the RPC wiki page.
Web3.js
As we have seen in the previous example using the JSON-RPC interface can be quite tedious and
error-prone, especially when we have to deal with the ABI. Web3.js is a javascript library that
works on top of the Ethereum RPC interface. Its goal is to provide a more user friendly interface
and reducing the chance for errors.
Deploying the Multiply7 contract using web3 would look like:
var source = 'contract Multiply7 { event Print(uint); function multiply(uint input) returns (uint) {
Print(input * 7); return input * 7; } }';
var compiled = web3.eth.compile.solidity(source);
var code = compiled.Multiply7.code;
var abi = compiled.Multiply7.info.abiDefinition;
38
Console
The geth console offers a command line interface with a javascript runtime. It can connect to a
local or remote geth or eth node. It will load the web3.js library that users can use. This allows
users to deploy and interact with smart contract from the console using web3.js. In fact the
examples in the Web3.js section can by copied into the console.
3.5.MIX
The IDE Mix is intended to help you as a developer to create, debug and deploy contracts and
dapps (both contracts backend and frontend).
Start by creating a new project that consists of
contracts
html files
JavaScript files
style files
image files
Project Editor
You can use projects to manage the creation and testing of a dapp. The project will contain data
related to both backend and frontend as well as the data related to your scenarios (blockchain
interaction) for debugging and testing. The related files will be created and saved automatically in
the project directory.
contract Rating {
function setRating(bytes32 _key, uint256 _value) {
ratings[_key] = _value;
}
mapping (bytes32 => uint256) public ratings;
}
39
Editing frontend html files
Select default index.html file and enter the following code
.... <script>
function getRating() {
var param = document.getElementById(“query”).value;
var res = contracts[“Rating”].contract.ratings(param);
document.getElementById(“queryres”).innerText = res;
}
function setRating() {
var key = document.getElementById("key").value;
var value = parseInt(document.getElementById("value").value);
var res = contracts["Rating"].contract.setRating(key, value);
}
</script>
</head>
<body bgcolor="#E6E6FA">
<h1>Ratings</h1>
<div>
Store:
<input type="string" id="key">
<input type="number" id="value">
<button onclick="setRating()">Save</button>
</div>
<div>
Query:
<input type="string" id="query" onkeyup='getRating()'>
<div id="queryres"></div>
</div>
</body>
</html>
Then it is possible to add many contract files as well as many HTML, JavaScript, css files
Scenarios Editor
In case it’s not open, access the scenario and debugger pane by pressing F7 or Windows > Show
right or the debug button in the upper right corner of the main window.
40
Creating and setting up a new scenario
When you launch Mix for the first time, an empty scenario, i.e. not containing any transactions,
will be created. Add an account named “MyAccount” and set it’s initial balance to 1 ether. Click
OK. Rename the scenario to “Deploy”.
Rebuilding a scenario
Each time a transaction is modified or an account added, the scenario has to be rebuilt for
modifications to become effective. Note that if a scenario is rebuilt the web frontend (local storage)
may also need to be reset (this is not done automatically be Mix).
Creating a transaction
Let’s get some ether sent to Bob. Create another account named “Bob” with zero ether balance.
Create a new transaction in the scenario pane. Click “Add Tx…” and send 300 ether to Bob. Add
a block.
Display calls
A contract call is a function invokation. This is not a transaction as a contract call cannot change
the state. A contract call is not part of the blockchain but for practical and ux design reason, it is
convenient to display calls at the same functional level as a transaction. The JS icon warn you that
this is not a transaction but a call. To show/hide call, click on the menu Scenario -> Display calls.
State Viewer
This panel is located below the block chain panel, in the scenario view. Once the blockchain has
been run, this panel shows the state of the blockchain.
By state we mean all accounts balance (including contract and normal account), and the storage
(global variable of all deployed contract). The content of this panel is not static, it depends on the
41
selected transaction on the blockchain panel. The state shown here is the state resulting of the
execution of the selected transaction.
In that case, 2 contracts are deployed, the selected transaction (deployment of testCtr) is the last
one. so the state view shows the storage of both TestCtr and BasicContract.
Transaction Explorer
Using the transaction pane
The transaction pane enables you to explore transactions receipts, including
Input parameters
Return parameters
Event logs
To display the transaction explorer, click on the down triangle icon which is on the right of each
transaction, this will expand transaction details:
42
Then you can either copy the content of this transaction in the clipboard, Edit the current
transaction (you will have to rerun the blockchain then), or debug the transaction.
JavaScript console
Mix exposes the following objects into the global window context
web3 - Ethereum JavaScript API
contracts: A collection of contract objects. keys represents contracts name. values are is an objects
containing the following properties:
contract: contract object instance (created as in web3.eth.contract)
address: contract address from the last deployed state (see below)
interface: contract ABI
Using the JS console to add transactions and local calls
In case the name of the contract is “Sample” with a function named “set”, it is possible to make a
transaction to call “set” by writing:
contracts["Sample"].contract.set(14)
If a call can be made this will be done by writing:
contracts["Sample"].contract.get.call()
Transaction debugger
Mix supports both Solidity and assembly level contract code debugging. You can toggle between
the two modes to retrieve the relevant information you need.
At any execution point the following information is available:
43
VM stack – See Yellow Paper for VM instruction description
Call stack – Grows when contract is calling into another contract. Double click a stack frame to
view the machine state in that frame
Storage – Storage data associated with the contract
Memory – Machine memory allocated up to this execution point
Call data – Transaction or call parameters
Accessing the debug mode
When transaction details are expanded, you can switch to the debugger view by clicking on the
“Debug Transaction” button
Toggling between debug modes and stepping through transactions
This opens the Solidity debugging mode. Switch between Solidity and EVM debugging mode
using the Menu button (Debug -> Show VM code)
Step through a transaction in solidity debugging mode
Step through a transaction in EVM debugging mode
Dapps deployment
This feature allows users to deploy the current project as a Dapp in the main blockchain.
This will deploy contracts and register frontend resources.
The deployment process includes three steps:
Deploy contract:
This step will deploy contracts in the main blockchain.
Package dapp:
This step is used to package and upload frontend resources.
Register:
To render the Dapp, the Ethereum browser (Mist or AlethZero) needs to access this package.
This step will register the URL where the resources are stored.
44
“Ethereum node URL” is the location where a node is running, there must be a node running in
order to initiate deployment.
“Pick Scenario to deploy” is a mandatory step. Mix will execute transactions that are in the selected
scenario (all transactions except transactions that are not related to contract creation or contract
call). Mix will display all the transactions in the panel below with all associated input parameters.
“Gas Used”: depending on the selected scenario, Mix will display the total gas used.
Deploy Scenario
“Deployment account” allow selecting the account that Mix will use to execute transactions.
“Gas Price” shows the default gas price of the network. You can also specify a different value.
“Deployment cost”: depending on the value of the gas price that you want to use and the selected
scenario. this will display the amount ether that the deployment need.
“Deployed Contract”: before any deployment this part is empty. This will be filled once the
deployment is finished by all contract addresses that have been created.
“Verifications”. This will shows the number of verifications (number of blocks generated on top
of the last block which contains the last deployed transactions). Mix keep track of all the
transactions. If one is missing (unvalidated) it will be displayed in this panel.
Package dapp
The action “Generate Package” will create a new folder named 'www', this folder will contain all
the resources and scripts will be mapped to the current deployed contract. In order to publish your
dapp, you need to host the www folder in a webserver (to be replace soon by IPFS and SWARM).
by default the library web3.js is not included. If you want to be able to use the dapp in a standard
web browser, you wiil need to include this library.
Code Editor
This editor provides basic functionalities of a code editor.
In Solidity or JavaScript mode, an autocompletion plugin is available (Ctrl + Space).
Increasing/decreasing the font size (Ctrl +, Ctrl -)
In Solidity mode, you can display the gas estimation (Tools -> Display Gas Estimation). This
will highlight all statements which requires a minimum amount of gas. Color turns to red if the
gas required becomes important. It will also display the max execution cost of a transaction
(for each function).
45
3.6.DAPPS
A dapp is a service that enables direct interaction between end users and providers (e.g. connecting
buyers and sellers in some marketplace, owners and storers in file storage). Ethereum dapps
typically interface users via an HTML/Javascript web application using a Javascript API to
communicate with the blockchain. Dapps would typically have their own suite of associated
contracts on the blockchain which they use to encode business logic and allow persistent storage
of their consensus-critical state. Remember that because of the redundant nature of computation
on the Ethereum network, the gas costs of execution will always be higher than private execution
offchain. This incentivizes dapp developers to restrict the amount of code they execute and amount
of data they store on the blockchain.
Dapp directories
Dapps that use Ethereum are compiled to the following lists. They are listed in various stages of
development (concept, working prototype, live/deployed). If you are developing a dapp, consider
adding an entry to these listings:
Ethercasts State of the Ðapps
The offered decentralised services listed cover a wide range of areas including finance, insurance,
prediction markets, social networks, distributed computation and storage, gambling, marketplace,
internet of things, governance, collaboration, development and games.
Dapp browsers
Mist - official GUI dapp browser developed by the foundation, alpha stage. Mist as Wallet
dapp is in beta.
Status - Mobile Ethereum browser (alpha)
MetaMask - Aaron Kumavis Davis's in-browser GUI. Epicenter Bitcoin interview on github -
supported by DEVgrants
AlethZero - C++ eth client GUI, (discontinued).
Supernova - (discontinued).
3.7.DEVELOPER TOOLS
Dapp development requires an understanding of the Web3 Javascript API, the JSON RPC API,
and the Solidity programming language.
46
There are developer tools that help you develop, test, and deploy dapps in a way that automatically
utilizes the resources listed below.
Web3 JavaScript API - This is the main JavaScript SDK to use when you want to interact
with an Ethereum node.
JSON RPC API - This is the low level JSON RPC 2.0 interface to interface with a node. This
API is used by the Web3 JavaScript API.
Solidity Docs - Solidity is the Ethereum developed Smart Contract language, which compiles
to EVM (Ethereum Virtual Machine) opcodes.
Solium - Linter to identify and fix style and security issues in Solidity.
Solhint - Solidity linter that provides security, style guide and best practice rules for smart
contract validation.
Test Networks - Test networks help developers develop and test Ethereum code and network
interactions without spending their own ether on the main network. Test network options are
listed below.
Dapp development resources. This assists you in developing, debugging, and deploying
Ethereum applications.
3.8.ETHEREUM TESTS
State Transition test
o Failing a Test
o Yul Tests
o Solidity Tests
o Multitest Files
Blockchain test
o ValidBlocks
o InvalidBlocks
o Transition tests
Ethereum object format test
47
o Expect o Pre Generated Ethereum
Generated State o Blocks Object Format
Transition Tests o Transaction o Test Structure
o Test Structure o Expect
o Info Section Generated Blockchain
o Env Section Tests
o Post Section o Test Structure
o Pre/preState Section o Info Section
o Transaction Section o Pre/preState Section
o GenesisBlockHeader
Section
o Valid Block Section
o Invalid Block Section
o Transaction Section
State transition tests include a single transaction that is supposed to change the state of the
blockchain from the pre state to the expect state.
Test Structure:
You can write tests either in JSON format or in YAML format. All tests are inside a structure with
their name
Format
Format JSON YAML
{
"name-of-test": { name-of-test:
Format Sections go here Sections go here
}
}
Env
This section contains the environment, the block just before the one that runs the VM or executes
the transaction.
48
Format
JSON
{
"name-of-test": {
<other sections>,
"env" : {
"currentCoinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "0x020000",
"currentGasLimit" : "0x05f5e100",
"currentNumber" : "0x01",
"currentTimestamp" : "0x03e8",
"previousHash" :
"0x5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6",,
"currentBaseFee" : "1000"
}
}
}
Fields
Note that this section only contains the fields that are relevant to single transaction tests.
Name in Env
Meaning
Section
random value that is supposed to come from the beacon chain (post
currentRandom
Merge)
Pre
This section contains the initial information of the blockchain.
49
Format
JSON YAML
{
"name-of-test": {
<other sections>,
"pre": {
name-of-test:
"address 1": {
<other sections>
"balance": "0xba1a9ce000",
pre:
"nonce": "0",
address 1:
"code": ":raw
balance: 0xba1a9ce000,
0x600160010160005500"
nonce: 0,
"storage: {
code: :raw
"0": "12345",
0x600160010160005500
"0x12": "0x121212"
storage:
},
0: 12345
"address 2": {
0x12: 0x121212
<address fields go here>
address 2:
}
<address fields go here>
}
}
}
Address Fields
balance: Wei balance at the start of the test
code: The code of the contract. In the expect: section this has to be raw virtual machine code.
nonce: The nonce counter for the address. This value is used to make sure each transaction is
processed only once. The first transaction the address sends has a nonce equal to this value,
the second one is the nonce plus one, etc.
storage: Values in the storage of the address
JSON YAML
storage: {
storage:
"1": 5,
1: 5
"0x20": 0x10
0x20: 0x10
}
50
o If the account is not a contract, this value is 0x
o Raw virtual machine code. This is for cases where it is impossible to provide source code,
or the source code is in a language retesteth does not recognize, such as Vyper.
:raw 0x600160010160005500
Put the solidity code itself in the contract definition (same place as the LLL or Yul code).
Put a :solidity section with the contract source code. In that case, the value
in code: is :solidity <name of contract>.
In either case, you can specify the hardfork to use using this syntax:
// RETESTETH_SOLC_EVM_VERSION=berlin
Transaction
This is the data of the transaction.
Format
JSON
{
"name-of-test": {
51
JSON
<other sections>,
"transaction":
{
"data": ["0xDA7A", "0xDA7A", ":label hex 0xDA7A",
":abi f(uint) 0xDA7A",
{
"data": "0xDA7A",
"accessList": [
{
"address": "0x0000000000000000000000000000000000000101",
"storageKeys": [0x60A7, 0xBEEF]
},
{
"address": "0x0000000000000000000000000000000000000102"
}
]
}
],
"gasLimit": ["0x6a506a50"],
"value": ["1"],
"to": "add13ess01233210add13ess01233210",
"secretKey": "5ec13e7 ... 5ec13e7"
"nonce": '0x909ce'
"maxPriorityFeePerGas": "10",
"maxFeePerGas": "2000",
}
YAML
name-of-test:
<other sections>
transaction:
data:
- 0xDA7A
- 0xDA7A
- :label hex 0xDA7A
- :abi f(uint) 0xDA7A
- data: :label acl 0xDA7A
accessList:
- address: 0x0000000000000000000000000000000000000101
storageKeys:
- 0x60A7
- 0xBEEF
52
JSON
- address: 0x0000000000000000000000000000000000000102
gasLimit:
- '0xga50ga50'
value:
- "1"
to: "add13ess01233210add13ess01233210"
secretKey: "5ec13e7 ... 5ec13e7"
nonce: '0x909ce'
maxPriorityFeePerGas: 10
max
Fields
data: The data, either in hexadecimal or an ABI call with this format: :abi <function
signature> <function parameters separated by spaces>. The value can also be
labeled: :label <value>. This value is specified as a list to enable files with multiple tests
The data can also have an EIP2930 access list. In that case the data field itself is a structure
with two fields: data (the data) and accessList. The accessList is a list of structures, each of
which has to have an address and may have a list of storageKeys.
gasLimit: Gas limit for the transaction. This value is specified as a list to enable files with
multiple tests
gasPrice: Gas price in Wei, only in Berlin and earlier (replaced by maxFeePerGas in London)
value: The value the transaction transmits in Wei. This value is specified as a list to enable files
with multiple tests
to: The destination address, typically a contract. If you want to submit a create transaction, put
an empty string here (and the data segment is the constructor).
secretKey: The secret key for the sending address. That address is derived from the secret key
and therefore does not need to be specified explicitely (see here).
nonce: The nonce value for the transaction. The first transaction for an address has the nonce
value of the address itself, the second transaction has the nonce plus one, etc.
maxPriorityFeePerGas: The maximum priority fee per gas (a.k.a. tip) the transaction is
willing to pay to be included in the block (London and later, added by eip 1559).
maxFeePerGas: The maximum total fee per gas the transaction is willing to pay to be included
in the block
Expect
This section contains the information we expect to see after the test is concluded.
53
Format
JSON
{
"name-of-test": {
<other sections>,
"expect": [
{
"indexes": {
"data": [0, "2-3", ":label foo"],
"gas": -1,
"value": -1
},
"network": ["Istanbul", <other forks, see below>],
"result": {
"address 1": {
"balance": "0xba1a9ce000",
"nonce": "0",
"storage: {
"0x0": 12345,
"10" : "0x121212"
},
"code": "0x00"
},
"address 2": {
<address fields go here>
}
},
{ <forks & results> }
]
}
}
YAML
name-of-test:
<other sections>
expect:
- indexes:
data:
- !!int 0
- 2-3
- :label foo
gas: !!int -1
value: !!int -1
network:
- Istanbul
- <another fork>
result:
address 1:
balance: 0xba1a9ce000,
nonce: 0,
storage:
0x0: 12345
10: 0x121212
code: 0x00
address 2:
<address fields go here>
- <forks & results>
54
The Network Specification
The string that identifies a fork (version) within a network: list is one of three option:
The Indexes
The transaction can have multiple values for data, gasLimit, and value. The indexes: section
specifies which of these values are covered by a particular item in expect, for each field it can be
either a single specification or a list of specifications. Each of those specifications uses any of
these options:
<n> !!int <n> The n’th value in the list (counting from zero)
“:label foo” :label foo Any value in the list that is specified as :label foo <value>
Address Fields
It is not necessary to include all fields for every address. Only include those fields you wish to
test.
balance: Wei balance at the start of the test
code: The code of the contract. In the expect: section this has to be raw virtual machine
code.
nonce: The nonce counter for the address. This value is used to make sure each transaction is
processed only once. The first transaction the address sends has a nonce equal to this value,
the second one is the nonce plus one, etc.
55
JSON YAML
storage: {
storage:
"1": 5,
1: 5
"0x20": 0x10
0x20: 0x10
}
Expect Exception
This field specifies the exception we expect to see raised by for this transaction. It is optional - you
only add it if an exception is expected.
JSON YAML
"expectException": {
expectException:
">=London": TR_TipGtFeeCap
">=London": TR_TipGtFeeCap
}
56
"testname" : {
"_info" : { ... },
"env" : { ... },
"post" : { ... },
"pre" : { ... },
"transaction" : { ... }
}
}
Info Section
"_info" : {
"comment" : "A test for (add 1 1) opcode result",
"filling-rpc-server" : "Geth-1.9.14-unstable-8cf83419-20200512",
"filling-tool-version" : "retesteth-0.0.3+commit.672a84dd.Linux.g++",
"lllcversion" : "Version: 0.5.14-develop.2019.11.27+commit.8f259595.Linux.g++",
"source" : "src/GeneralStateTestsFiller/stExample/add11Filler.json",
"sourceHash" : "e474fc13b1ea4c60efe2ba925dd48d6f9c1b12317dcd631f5eeeb3722a790a37",
"labels" : {
"0" : ":label normal",
"1" : ":label normal",
"2" : ":label normal"
},
},
Info section is generated with the test and contains information about test and it’s generators.
Fields
filling-rpc-server tool that has been used to generate the test (version)
lllcversion lllc version that was used to compile LLL code in test fillers
sourceHash hash of the json of source file (used to track that tests are updated)
Env Section
"env" : {
"currentCoinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "0x020000",
"currentGasLimit" : "0xff112233445566",
"currentNumber" : "0x01",
"currentTimestamp" : "0x03e8",
"previousHash" : "0x5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
57
Env section describe information required to construct a genesis block, or VM env for transaction
execution.
Fields
currentCoinbase author/miner/coinbase address
58
define an index of the transaction in txs vector that has been used for
indexes
this result
expectExcepti
for a transaction that is supposed to fail, the exception
on
Pre/preState Section
"pre" : {
"0x095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"balance" : "0x0de0b6b3a7640000",
"code" : "0x600160010160005500",
"nonce" : "0x00",
"storage" : {
"0x00" : "0x01"
}
},
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x0de0b6b3a7640000",
"code" : "0x",
"nonce" : "0x00",
"storage" : {
}
}
},
Pre section describes a full state of accounts used in test.
Its a map of <Account> => <AccountFields>
AccountFields are always complete (balance, code, nonce, storage must present) in this section
and can not have a missing field.
All values are 0x prefixed hex.
Empty code defined as 0x.
Zero storage record defined as 0x00.
Fields
59
address hash HASH20 is 20 bytes ethereum address 0x prefixed
Size can be limited by the meaning of field in tests. (like gasLimit ceil, tx signature v - value)
Transaction Section
"transaction" : {
"data" : [
"0x"
],
"gasLimit" : [
"0x061a80"
],
"gasPrice" : "0x01",
"nonce" : "0x00",
"secretKey" : "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "0x095e7baea6a6c7c4c2dfeb977efac326af552d87",
"value" : [
"0x0186a0"
]
}
60
Transaction section defines a vector of transaction to be executed in GeneralStateTest From this
section it is possible to construct many transaction using values from data,gasLimit,value array.
Indexes in this array used in the post section to point out which transaction has been used to
calculate the post state hash.
All fields are 0x prefixed HEX of even length (can be like 0x0122)
empty data is defined as 0x
transaction creation to defined as “”
Fields
61
2. The source code of tests doesn’t include all the information required for the test. Instead, you
run retesteth.sh, and it runs a client with the Ethereum Virtual Machine (evm) to fill in the
values. This creates a compiled version in tests/GeneralStateTests/stExample.
./dretesteth.sh -t GeneralStateTests/stExample -- \
--singletest 01_add22 --testpath ~/tests \
--datadir /tests/config --filltests
sudo chown $USER tests/GeneralStateTests/stExample/*
3. Run the test normally, with verbose output:
./dretesteth.sh -t GeneralStateTests/stExample -- \
--singletest 01_add22 --testpath ~/tests \
--datadir /tests/config --clients geth --verbosity 5
The Source Code
# The name of the test
01_add22:
This is the general Ethereum environment before the transaction:
env:
currentCoinbase: 2adc25665018aa1fe0e6bc666dac8fc2697ff9ba
currentDifficulty: '0x20000'
currentGasLimit: 10_000_000
You can put underscores (_) in numbers to make them more readable.
currentNumber: 1
currentTimestamp: "1000"
previousHash: 5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6
This is where you put human readable information. In contrast to # comments, these comment
fields get copied to the compiled JSON file for the test.
_info:
comment: "You can put a comment here"
These are the relevant addresses and their initial states before the test starts:
pre:
62
This is a contract address. As such it has code, which can be in one of three languages:
Ethereum virtual machine (EVM) machine language
Lisp Like Language (lll). One advantage of lll is that it lets us use Ethereum Assembler
almost directly.
Solidity, which is the standard language for Ethereum contracts. Solidity is well known,
but it is not ideal for VM tests because it adds its own code to compiled contracts. Click
here for a test written in Solidity.
The Yul language, which is a low level language for the EVM. Click here for a test written
in Yul.
095e7baea6a6c7c4c2dfeb977efac326af552d87:
balance: '0x0ba1a9ce0ba1a9ce'
LLL code can be very low level. In this case, (ADD 2 2) is translated into three opcodes:
PUSH 2
PUSH 2
ADD (which pops the last two values in the stack, adds them, and pushes the sum into the stack).
This expression [[0]] is short hand for (SSTORE 0 <the value at the top of the stack>). It stores
the value (in this case, four) in location 0.
code: |
{
; Add 2+2
[[0]] (ADD 2 2)
}
nonce: '0'
Every address in Ethereum has associated storage, which is essentially a lookup table. In this case
the storage is initially empty.
storage: {}
This is a “user” address. As such, it does not have code. Note that you still have to specify the
storage.
a94f5374fce5edbc8e2a8697c15331677e6ebf0b:
balance: '0x0ba1a9ce0ba1a9ce'
code: '0x'
nonce: '0'
storage: {}
This is the transaction that will be executed to check the code. There are several scalar fields
here:
gasPrice is the price of gas in Wei. Note that starting with the London fork the block base
fee is ten by default, and a lower gasPrice will get rejected.
nonce has to be the same value as the user address
to is the contract we are testing. If you want to create a contract, keep the to definition, but
leave it empty.
63
Additionally, these are several fields that are lists of values. The reason to have lists instead of
a single value is to be able to run multiple similar tests from the same file (see the Multitest
Files section below).
data is the data we send
gasLimit is the gas limit
value is the amount of Wei we send with the transaction
transaction:
data:
- '0x10'
gasLimit:
- '80000000'
gasPrice: 1000
nonce: '0'
to: 095e7baea6a6c7c4c2dfeb977efac326af552d87
value:
- '1'
This is the state we expect after running the transaction on the pre state. The indexes: subsection
is used for multitest files, for now just copy and paste it into your tests.
expect:
- indexes:
data: !!int -1
gas: !!int -1
value: !!int -1
network:
- '>=London'
We expect the contract’s storage to have the result, in this case 4.
result:
095e7baea6a6c7c4c2dfeb977efac326af552d87:
storage:
0x00: 0x04
Failing a Test
To verify that retesteth really does run tests, lets fail one. The **02_fail** test is almost identical
to 01_add22, except that it expects to see that 2+2=5. Here are the steps to use it.
1. Copy the test to the stExample directory:
cp ~/tests/docs/tutorial_samples/02* ~/tests/src/GeneralStateTestsFiller/stExample
2. Fill the information and run the test:
./dretesteth.sh -t GeneralStateTests/stExample -- \
--singletest 02_fail --testpath ~/tests \
--datadir /tests/config --filltests
3. Delete the test so we won’t see the failure when we run future tests (you can run all the tests in
a directory by omitting the --singletest parameter:
rm ~/tests/src/GeneralStateTestsFiller/stExample/02_*
64
Tests that are Supposed to Fail
When a test transaction is supposed to fail, you add an expectException: section to the result.
You can see a complete example in 10_expectExceptionFiller
expect:
- indexes:
data: !!int -1
gas: !!int -1
value: !!int -1
network:
- '>=London'
expectException:
'>=London': TR_FeeCapLessThanBlocks
result: {} # No point checking the result when no transaction happened
You can see the complete list of supported exceptions either in the config file for the client, or
in the retesteth source code.
Note that running out of gas is not an exception. Technically speaking a transaction that runs out
of gas is successful, it is just reverted.
Yul Tests
Yul is a language that is very close to EVM assembler. As such it is a good language for writing
tests..
This is a sample contract:
cccccccccccccccccccccccccccccccccccccccc:
balance: '0x0ba1a9ce0ba1a9ce'
code: |
:yul {
let cellAddr := sub(10,10)
sstore(cellAddr,add(60,9))
}
nonce: 1
storage: {}
It is very similar to an LLL test, except for having the :yul keyword before the opening curly
bracket ({).
Note that you can specify the fork for which you compile the code. This is important because of the
PUSH0 opcode, which cannot be used in tests that need to run on forks prior to Shanghai.
code: |
:yul <fork, such as berlin or shanghai>
{
<code goes here>
}
65
Solidity Tests
The Solidity compiler adds a lot of extra code that handles ABI encoding, ABI decoding, contract
constructors, etc. This makes tracing and debugging a lot harder, which makes Solidity a bad
choice for most Ethereum client tests.
This feature is available for tests where it is useful, but LLL or Yul is usually a better
choice.
You can have a separate solidity: section for your code. This is useful because Solidity
code tends to be longer than LLL (or Yul) code.
solidity: |
// SPDX-License-Identifier: GPL-3.0
The retesteth docker only includes one version of the Solidity compiler, so it is best not to have
a pragma solidity line.
// RETESTETH_SOLC_EVM_VERSION=<fork, such as london or prague>
Specify the hardfork for the compiler to use. If a test needs to be executed on forks prior to
Shanghai, that needs to be specified because of the PUSH0 opcode added in Shanghai.
contract Test {
Solidity keeps state variables in the storage, starting with location 0. We can use state
variables for the results of operations, and check them in the expect: section
uint256 storageVar = 0xff00ff00ff00ff00;
function val2Storage(uint256 addr, uint256 val) public
{
storageVar = val;
Another possibility is to use the SSTORE opcode directly to write to storage. This is the
format to embed assembly into Solidity.
assembly { sstore(addr, val) }
} // function val2Storage
} // contract Test
To specify a contract’s code you can use :solidity <name of contract>. Alternatively, you can put
the solidity code directly in the account’s code: section if it has pragma solidity (otherwise it is
compiled as LLL).
66
pre:
cccccccccccccccccccccccccccccccccccccccc:
balance: '0x0ba1a9ce0ba1a9ce'
code: ':solidity Test'
nonce: '0'
storage: {}
In contrast to LLL, Solidity handles function signatures and parameters for you. Therefore, the
transaction data has to conform to the Application Binary Interface (ABI). You do not have to
calculate the data on your own, just start it with :abi followed by the function signature and then
the parameters. These parameters can be bool, uint, single dimension arrays, and strings.
ABI support is a new feature, and may be buggy. Please report any bugs you encounter in this
feature.
transaction:
data:
- :abi val2Storage(uint256,uint256) 5 69
gasLimit:
- '80000000'
The other sections of the test are exactly the same as they are in an LLL test.
ABI values
These are examples of the values that :abi can have.
:abi baz(uint32,bool) 69 1: Call baz with a 32 bit value (69) and a true boolean value
:abi bar(bytes3[2]) [“abc”, “def”]: Call bar with a two value array, each value three bytes
:abi sam(bytes,bool,uint256[]) “dave” 0 [1,2,3]: Call sam with a string (“dave”), a false boolean
value, and an array of three 256 bit numbers.
:abi f(uint256,uint32[],bytes10,bytes) 0x123 [0x456, 0x789] “1234567890” “Hello, world”:
Call f with these parameters
An unsigned 256 bit integer
An array of 32 bit values (it can be any size)
A string of ten bytes
A string which could be any size
:abi g(uint256[][],string[]) [[1,2],[3],[4,5] [“one”,”two”,”three”]: Call g with two parameters, a
two dimensional array of uint256 values and an array of strings.
67
:abi h(uint256,uint32[],bytes10,bytes) 291 [1110,1929] “1234567890” “Hello, world!”:
Call h with a uint256, an array of uint32 values of unspecified size, ten bytes, and a parameter with
an unspecified number of bytes.
:abi ff(uint256,address) 324124 “0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826”:
Call ff with a uint256 and an address (Ethererum addresses are twenty bytes).
Multitest Files
It is possible to combine multiple similar tests in one file. Here is an example.
There are two steps to doing that:
Modify the transaction: section. This section has three subsections that are lists. You can add
multiple values to the data:, gasLimit:, and value:.
For example:
transaction:
data:
- :abi val2Storage(uint256,uint256) 0x10 0x10
- :abi val2Storage(uint256,uint256) 0x11 0x11
- :abi val2Storage(uint256,uint256) 0x11 0x12
- :abi val2Storage(uint256,uint256) 0x11 0x11
gasLimit:
- '80000000'
gasPrice: '1'
nonce: '0'
to: cccccccccccccccccccccccccccccccccccccccc
secretKey: "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"
value:
-0
The expect: section is also a list, and can have multiple values. Just put the indexes to the
correct data, gas, and value values, and have the correct response in the result: section.
For example:
expect:
The indexes are integer values. By default YAML values are strings. The !!int overrides
this. These are all the first values in their lists, so the data is equivalent to the
call val2Storage(0x10, 0x10).
- indexes:
data: !!int 0
gas: !!int 0
value: !!int 0
network:
- '>=Istanbul'
result:
cccccccccccccccccccccccccccccccccccccccc:
storage:
0: 0x10
0x10: 0x10
68
This is for the second and fourth items in the data: subsection above. When you have multiple
values that produce the same test results, you can specify data, gas, or value as a list instead of a
single index.
- indexes:
data:
- !!int 1
- !!int 3
gas: !!int 0
value: !!int 0
network:
- '>=Istanbul'
result:
cccccccccccccccccccccccccccccccccccccccc:
storage:
0: 0x11
0x11: 0x11
70
3.8.2.1.Valid Block Tests
There is a valid block test in tests/docs/tutorial_samples/05_simpleTxFiller.yml. We copy it
to bcExample.
mkdir ~/tests/src/Blo*/Val*/bcExample*
cp ~/tests/docs/tu*/05_* ~/tests/src/Blo*/Val*/bcExample*
cd ~
./dretesteth.sh -t BlockchainTests/ValidBlocks/bcExample -- \
--testpath ~/tests --datadir /tests/config --filltests \
--singletest 05_simpleTx
In a lot of existing tests you will see a definition for sealEngine. This is related to getting a proof
of work as part of the test. However, this is no longer part of retesteth, so you can omit it or set it
to NoProof.
71
# sealEngine: NoProof
Instead of a single transaction, we have a list of blocks. In a YAML list you tell different items
apart by the dash character (-). The block list has two items in it.
blocks:
The first block has one field, transactions, a list of transactions. Every individual transaction is
specified with the same fields used in state transition tests. This block only has one transaction,
which transfers 10 Wei.
- transactions:
- data: ''
gasLimit: '50000'
gasPrice: 20
This is the nonce value for the transaction. The first value is the nonce associated with the address
in the pre: section. Each subsequent transaction from the same address increments the nonce.
Alternatively, if you use auto for every transaction of an account, the retesteth tool will provide
the nonce values automatically.
nonce: '0'
secretKey: 45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8
to: 0xde570000de570000de570000de570000de570000
value: '10'
This is the second block. In contrast to the first block, in this one we specify a blockHeader and
override some of the default values.
- blockHeader:
gasLimit: '3141592'
A block can also contain references to uncle blocks (blocks mined at the same time). Note that
writing tests with uncle headers is complicated, because you need to run the test once to get the
correct hash value. Only then can you put the correct value in the test and run it again so it’ll be
successful.
uncleHeaders: []
This block has two transactions.
transactions:
- data: ''
gasLimit: '50000'
gasPrice: '20'
This is another transaction from the same address, so the nonce is one more than it was in the
previous one.
72
nonce: '1'
secretKey: 45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8
to: 0xde570000de570000de570000de570000de570000
value: '20'
- data: ''
gasLimit: '50000'
gasPrice: '30'
This transaction comes from a different address (addresses are uniquely derived from the private
key, and this one is different from the one in the previous transaction). This
transaction’s nonce value is the initial value for that address, zero.
nonce: '0'
secretKey: 41f6e321b31e72173f8ff2e292359e1862f24fba42fe6f97efaf641980eff298
to: 0xde570000de570000de570000de570000de570000
value: '30'
In block tests we can simulate this value by specifying a mixHash as part of blockHeader.
However, the interaction of mixHash and stateRoot makes this process a bit complicated.
First, you write the test normally, using the block header field mixHash for the random value that
in real execution would come from the consensus layer. Note that mixHash has to be a 32 byte
value. Even if most of the bytes are zeros, you have to specify them.
When you run the test, it fails on the first block where the state is a function of the random value
with an error that includes these lines:
/retesteth/retesteth/TestOutputHelper.cpp(227): error: in
"BlockchainTests/ValidBlocks/bcStateTests":
Error: Postmine block tweak expected no exception! Client errors with: 'Error importing raw rlp
block: Block from pending block != t8ntool constructed block!
Error in field: stateRoot
73
parentHash 0x76898c312aea29aa17df32e97399ccdf88e72c544305c9ddc3e76996e35ab951 vs
0x76898c312aea29aa17df32e97399ccdf88e72c544305c9ddc3e76996e35ab951
receiptTrie 0x71043553dd2c4fbc22100a69d47ba3a790f7e428796792c552362b81e6cf5331 vs
0x71043553dd2c4fbc22100a69d47ba3a790f7e428796792c552362b81e6cf5331
stateRoot 0x7a3760ed3aa3e40711b3ecd1cb898a9f37c14cbde7f95b7c5c7af05e6d794864 vs
0x1b5647d3ca49c4b0e9e57e113f85b1be28ac10f0577b6e70c76fb7d767949bf8
In the error there are two separate values of stateRoot. The first, shown in red, is the expected
value. The second, shown in yellow, is the actual value. You need to copy that second value into
the block header.
- blockHeader:
mixHash: 0x0102030405060708091011121314151617181920212223242526272829303131
stateRoot: 0x1b5647d3ca49c4b0e9e57e113f85b1be28ac10f0577b6e70c76fb7d767949bf8
If you use the random value also in another block, you repeat the process, once per block.
Invalid block tests contain invalid blocks, blocks that cause a client to raise an exception. To
tell retesteth which exception should be raised by a block, we add an expectException field to
the blockHeader. In that field we put the different forks the test supports, and the exception we
expect to be raised in them. It is a good idea to have a field that includes future forks.
- blockHeader:
gasLimit: '30'
expectException:
Berlin: TooMuchGasUsed
74
'>=London': TooMuchGasUsed
The expectException field is only used when --filltests is specified. When it is not, retesteth just
expects the processing of the block to fail, without ensuring the exception is the correct one. The
reason for this feature is that not all clients tell us the exact exception type when they reject a block
as invalid.
If you don’t know what exception to expect, run the test without an expectException. The output
will include an error message similar to this one:
Error: Postmine block tweak expected no exception! Client errors with:
'Error importing raw rlp block: Invalid gasUsed: header.gasUsed > header.gasLimit'
(bcBlockGasLimitTest/06_invalidBlock_Berlin, fork: Berlin, chain: default, block: 2)
Then took in tests/conf/<name of client>/config and look for the first few words of the error
message. For example, in tests/conf/tn8tool/config we find this line:
"TooMuchGasUsed" : "Invalid gasUsed:",
This tells us that the exception to expect is TooMuchGasUsed.
3.8.2.3.Transition Tests
Transition Tests start with one fork, which is used to execute blocks 1-4. Then, typically starting
at block 5, it is the following fork. You can see the list of transition networks here or
in …/tests/config/t8ntool/config.
In the case of the ArrowGlacier to Merge transition it happens at a specific difficulty, 0x0C0000.
At the block difficulty most tests use, 0x020000, this happens on block 6.
75
Format
Format JSON YAML
{
"name-of-test": {
name-of-test:
Format Sections go here
Sections go here
}
}
Genesis Block
This section contains the genesis block that starts the chain being tested.
Format
JSON
{
"name-of-test": {
<other sections>,
genesisBlockHeader: {
"bloom" : "0x0 <<lots more 0s>>"
"coinbase" : "0x8888f1f195afa192cfee860698584c030f4c9db1",
"difficulty" : "0x020000",
"extraData" : "0x42",
"gasLimit" : "0x2fefd8",
"gasUsed" : "0x00",
"mixHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce" : "0x0000000000000000",
"number" : "0x00",
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"receiptTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"stateRoot" : "0x14f0692d8daa55f0eb56a1cf1e2b07746d66ddfa3f8bae21fece76d1421b5d47",
"timestamp" : "0x54c98c81",
"transactionsTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
"baseFeePerGas" : "1000"
}
}
}
Fields
76
Name in Block Header
Meaning
Sections
difficulty (post-merge) not used anymore (value zero), identifies a block as pre-merge
77
difficulty is set to zero for proof of stake genesis blocks. If you try to run a PoS test on an
older fork that uses PoW, the default difficulty is 0x020000.
mixHash is used for the random value that in production comes from the beacon chain. If
this value is specified in the genesis block, that value is the “random” value until there is a
blockheader with mixHash. When that happens, that mixHash value is the random value
until the next block with a mixHash.
Pre
This section contains the initial information of the blockchain.
JSON YAML
{
"name-of-test": {
<other sections>,
"pre": { name-of-test:
"address 1": { <other sections>
"balance": "0xba1a9ce000", pre:
"nonce": "0", address 1:
"code": ":raw balance: 0xba1a9ce000,
0x600160010160005500" nonce: 0,
"storage: { code: :raw
"0": "12345", 0x600160010160005500
"0x12": "0x121212" storage:
}, 0: 12345
"address 2": { 0x12: 0x121212
<address fields go here> address 2:
} <address fields go here>
}
}
}
Address Fields
balance: Wei balance at the start of the test
code: The code of the contract. In the expect: section this has to be raw virtual machine
code.
nonce: The nonce counter for the address. This value is used to make sure each transaction is
processed only once. The first transaction the address sends has a nonce equal to this value,
the second one is the nonce plus one, etc.
storage: Values in the storage of the address
78
JSON YAML
storage: { storage:
"1": 5, 1: 5
"0x20": 0x10 0x20: 0x10
}
Put the solidity code itself in the contract definition (same place as the LLL or Yul code).
Put a :solidity section with the contract source code. In that case, the value
in code: is :solidity <name of contract>.
In either case, you can specify the hardfork to use using this syntax:
// RETESTETH_SOLC_EVM_VERSION=berlin
79
Blocks
This section contains the blocks of the blockchain that are supposed to modify the state from the
one in the pre section to the one in the expect section.
Format
JSON YAML
{
"name-of-test": {
<other sections>,
blocks: [
{ transactions: [
{ <transaction> }, name-of-test:
{ <transaction> } <other sections>
] blocks:
}, - transactions:
{ transactions: [ - <transaction>
{ <transaction> }, - <transaction>
{ <transaction> } - blockHeader:
] extraData: 42
blockHeader: { gasLimit: 100_000
"extraData" : "0x42", gasUsed: 2_000
"gasLimit" : "0x2fefd8", uncleHeaders:
"gasUsed" : "0x5208", <values here>
}, transactions:
uncleHeaders: [ <values here> ] - <transaction>
} - <transaction>
]
}
}
Fields
The fields in each block are optional. Only include those fields you need.
blockHeader:
This field contains the block header parameters. Parameters that are missing are copied from
the genesis block.
80
Name in Block Header
Meaning
Sections
mixHash and nonce (pre- used by the proof of work algorithm, ignored
merge) by retesteth.
One field inside the block header which is not standard in Ethereum is expectException.
That field, which is only used in invalid block tests, identifies the exception we expect to
receive for the block on different forks of Ethereum.
Note that starting with London gasLimit cannot be changed by more than 1/1024 from the
previous value because of EIP 1559. You can specify baseFeePerGas, but the block is only
valid if it is the same value that was calculated from the previous block.
blocknumber and chainname:
81
If you are testing behavior in the presence of multiple competing chains, these fields let you
specify the chain and the block’s location within it.
uncleHeaders:
A list of the uncle blocks (blocks mined at the same time). Each item in the list has two
fields:
o chainname: The name of the chain from which the uncle block comes
o populateFromBlock: The block number within that chain for the block that is an uncle
of the block you are specifying.
However, if you write a test with uncles, you need to run it twice, once to get the state hash
values to write them in the test filler file, and again to actually run the test.
transactions:
Format
JSON YAML
{ <test-name>:
"name-of-test": <other sections>
{ blocks:
<other sections> - transactions:
"blocks": [ - data: 0xDA7A
{ gasLimit: '0x6a506a50'
transactions: [ maxFeePerGas: 1000
{ maxPriorityFeePerGas: 10
data: "0xDA7A", value: 1
gasLimit: "0x6a506a50", to:
gasPrice: 1, "add13ess01233210add13ess01233210"
value: 1, secretKey: "5ec13e7 ...
to: 5ec13e7"
"add13ess01233210add13ess01233210", nonce: '0x909ce'
secretKey: "5ec13e7 ... - data: 0xDA7A
5ec13e7" accessList:
nonce: '0x909ce' - address:
}, 0xcccccccccccccccccccccccccccccccccc
{ cccccd
data: "0xDA7A", storageKeys:
accessList: [ - 0x1000
{ - address:
"address": 0xcccccccccccccccccccccccccccccccccc
"0xcccccccccccccccccccccccccccccccccccccccd", cccccc
"storageKeys": ["0x1000", storageKeys: []
"0x60A7"] gasLimit: '0x6a506a50'
82
JSON YAML
}, gasPrice: "1"
{ value: 1
"address": to:
"0xccccccccccccccccccccccccccccccccccccccce", "add13ess01233210add13ess01233210"
"storageKeys": [] secretKey: "5ec13e7 ...
} 5ec13e7"
], nonce: '0x909ce'
gasLimit: "0x6a506a50", - <another transaction>
maxFeePerGas: 1000, <other block fields>
maxPriorityFeePerGas: 10, - <another block>
value: 1,
to:
"add13ess01233210add13ess01233210",
secretKey: "5ec13e7 ...
5ec13e7"
nonce: '0x909ce'
},
<other transactions>
]
<other block fields>
},
<other blocks>
]
}
Fields
data: The data, either in hexadecimal or an ABI call with this format: :abi <function
signature> <function parameters separated by spaces>.
accessList: An optional EIP2930 access list. The accessList is a list of structures, each of
which has to have an address and a list of storageKeys (which may be empty).
gasLimit: Gas limit for the transaction
gasPrice: Gas price in Wei, prior to London (changed by EIP 1559).
maxFeePerGas: Maximum acceptable gas price in Wei. Available in London and later.
maxPriorityFeePerGas: Tip to give the miner (per gas, in Wei). The real tip is either this
value or maxFeePerGas-baseFeePerGas (the lower of the two). Available in London and
later.
value: The value the transaction transmits in Wei
to: The destination address, typically a contract. If you want to submit a create transaction, put
an empty string here (and the data segment is the constructor).
secretKey: The secret key for the sending address. That address is derived from the secret key
and therefore does not need to be specified explicitely (see here).
83
nonce: The nonce value for the transaction. The first transaction for an address has the nonce
value of the address itself, the second transaction has the nonce plus one, etc. Alternatively, if
you replace all the nonce values with auto, the tool does this for you.
invalid: If the transaction is invalid, meaning clients should reject it, set this value to “1”
expectException: .. include:: ../test_filler/test_expect_exception.rst
Expect
This section contains the information we expect to see after the test is concluded.
Format
JSON YAML
{
"name-of-test": {
<other sections>,
"expect": [ name-of-test:
{ <other sections>
"network": ["Istanbul", <other forks, see expect:
below>], - network:
"result": { - Istanbul
"address 1": { - <another fork>
"balance": "0xba1a9ce000", result:
"nonce": "0", address 1:
"storage: { balance:
"0x0": 12345, 0xba1a9ce000,
"10" : "0x121212" nonce: 0,
}, storage:
"code": "0x00" 0x0: 12345
}, 10: 0x121212
"address 2": { code: 0x00
<address fields go here> address 2:
} <address fields go
}, here>
{ <forks & results> } - <forks & results>
]
}
}
84
Address Fields
It is not necessary to include all fields for every address. Only include those fields you wish to
test.
balance: Wei balance at the start of the test
code: The code of the contract. In the expect: section this has to be raw virtual machine
code.
nonce: The nonce counter for the address. This value is used to make sure each transaction is
processed only once. The first transaction the address sends has a nonce equal to this value,
the second one is the nonce plus one, etc.
storage: Values in the storage of the address
JSON YAML
storage: {
storage:
"1": 5,
1: 5
"0x20": 0x10
0x20: 0x10
}
Fillers
The fillers for EOF tests are in …/src/EOFFiller. This tutorial explains the YML
filler, …/src/EOFFiller/efExample/ymlExampleFiller.yml.
Overall Structure
The file includes these sections:
_info: Human readable comments.
data: A list of entries. Each entry is init code that can create a contract
expect: The expected results.
85
020001 # One code segment
000a # Code segment zero length: 10 bytes
030016 # Data segment length (the code being deployed): 0x16=22 bytes
00 # End of header
This is functionally equivalent to
- :raw 0xEF0001010004020001000a03001600
But a lot more readable.
The Expect Section
Here is a sample expect section entry.
- indexes:
data:
- 0-1
network:
- '>=Shanghai'
result: !!bool true
It is very similar to the expect section of a state transition test, except for these differences:
In the indexes subsection there is only data. These tests don’t have gas or value fields to match.
The result can only be one of two values:
!!bool true if the contract is supposed to get created
!!bool false if contract creation is supposed to fail
{
"name-of-test": {
name-of-test:
Format Sections go here
Sections go here
}
}
Transaction
This is the data to be deployed.
86
Format
JSON YAML
{ name-of-test:
"name-of-test": { <other sections>
<other sections>, data:
"data": [ - :raw 0xBAD060A7
":raw 0x112200", -|
":raw 0x223344" :raw # or cooked
] 0xBAD0 # or good
} 60A7
Expect
This section contains the information we expect to see after the test is concluded.
Format
JSON YAML
{
name-of-test:
"name-of-test": {
<other sections>
<other sections>,
expect:
"expect": [
- indexes:
{
data:
"indexes": {
- !!int 0
"data": [0, "2-3", ":label foo"],
- 2-3
},
- :label foo
"network": ["Istanbul", <other forks, see below>],
network:
"result": true
- Istanbul
{ <forks & results> }
- <another fork>
]
result: !!bool true
}
- <forks & results>
}
87
JSON YAML Meaning
!!int
<n> The n’th value in the list (counting from zero)
<n>
“<a>- Everthing from the a’th value to the b’th value (counting from
a-b
<b>” zero)
“:label :label
Any value in the list that is specified as :label foo <value>
foo” foo
The Result
Whether the data should result in a successful contract deployment or not.
88
3.9.WEB3 BASE LAYER SERVICES
In addition to the Ethereum blockchain, more components are being developed that decentralise
other important aspects of web applications.
89
Name registry
Because dapps can be stored anywhere, including the Swarm network, the name registry maps
names to their content or location. This is a decentralised alternative to the Domain Name System
(DNS).
Contract registry
To publish the source code of a specific contract, its address has to be mapped to it. The contract
registry stores this mapping. Users can then look up this mapping and verify the contract byte code.
90
Fig. Diagram Representation of Different types of Nodes in Ethereum
91
Functionality and Features of Light Node:
A light node in Ethereum is a lightweight version of a full node that consumes less storage
and computational resources.
It doesn’t store all of the blockchain data but instead relies on other nodes for transaction
information when needed.
Light nodes perform request serving by requesting specific data from full nodes or archive
nodes on – demand.
They can quickly synchronize with the network because they only need to download
minimal data to verify transactions.
Light nodes are ideal for users who want to interact with decentralized applications (dApps)
without running their own full node.
Benefits and Use Cases of Light Node
Requires less storage space and bandwidth compared to full nodes.
Allows users to quickly sync with the Ethereum network, making it suitable for mobile
devices or low – resource devices.
Provides access to basic transaction information and allows participation in the network
without storing a complete copy of the blockchain.
Enables quick verification of transactions, ensuring trust without extensive resource
requirements.
92
Benefits and Use Cases of Full Node
Provides a complete copy of the Ethereum blockchain, allowing users to independently
verify transactions and participate in network consensus.
Enables secure and trustless interactions with the Ethereum network.
Suitable for developers, miners, and businesses that require full control over their
transactions and data.
93
Light nodes consume significantly less storage space but sacrifice some security guarantees
by relying on other nodes for verification.
Data Storage:
Full nodes store all transaction data on their local devices, providing complete control over
data privacy.
Light nodes retrieve transaction information from other full nodes on demand, reducing
local storage requirements.
Remote Access:
Full nodes enable users to access their own locally stored data securely without relying on
external services.
Light nodes can access transaction data remotely from other nodes but may expose
sensitive information to those external sources.
Verification Process:
Full nodes independently validate every transaction against network consensus rules,
ensuring trustlessness in interactions.
Light nodes rely on full nodes for transaction verification, trusting that the majority of the
network follows the correct consensus rules.
Network Profitability:
Running a full node contributes to network decentralization and fosters a more secure and
resilient Ethereum ecosystem.
Light nodes provide a convenient option for users who want to access Ethereum
functionality without the resource-intensive requirements of running a full node.
Use Cases:
Full nodes are essential for developers testing contracts, miners securing the network, and
businesses requiring direct control over their transactions.
Light nodes are suitable for mobile apps, web wallets, and lightweight applications that
prioritize convenience and lower resource consumption.
Archive nodes support research, data analysis, auditing, or any use case that relies on
historical Ethereum blockchain information.
94
Fig. Working of Ethereum Node
The node incorporates verified transactions into a pool of pending transactions, known
as the “mempool”. Network validators, who also operate nodes, draw transactions from
this pool to create new blocks. So, the node participates in the consensus mechanism to
validate and append new blocks to the blockchain.
Every full Ethereum node maintains a complete copy of the blockchain, which consists
of a chain of interconnected blocks containing transaction data. It continuously
synchronizes with other nodes, updating its copy of the blockchain to reflect the latest
transactions and blocks added to the network.
Furthermore, all Ethereum nodes communicate with one another through a peer-to-peer
(P2P) network, disseminating transaction and block data efficiently. This ensures that
even in the absence of central servers, the network remains robust and resistant to
censorship.
After all, setting up and running your own node in such a manner requires a lot of time, resources,
and technical expertise. It takes commitment and resources that could be spent on development.
As such, we don’t recommend this path to those primarily interested in building awesome dapps.
95
is free and open-source software providing users with an app-like experience while managing their
node.
A step-by-step guide on how to set up your Ethereum node in a few simple steps.
For the simplest onboarding experience, you can purchase plug-and play-devices to run a
node. Ethereum recommends the DAppNode solution. Avado is another well-known
provider.
A cheaper and more customizable option is building or using your own device. Minimum
specs as listed on the Ethereum webpage are: 4–8 GB RAM, 2 TB SSD, Intel NUC, 7th
gen. or higher
Plug and Play: Users having opted for the DAppNode plug-and-play device can find detailed
instructions on how to set up their device in the Installation Guide here and the First Steps
Guide here.
Users running the Ethereum node on their personal computer or self-built device can choose from
at least five different Ethereum client software options. The vast majority (>80%)
uses Geth software to run their nodes.
96
The router and firewall accept connections on listening ports. By default, Ethereum clients
use a listener (TCP) port and a discovery (UDP) port, both on 30303 by default.
97
It operates independently, eliminating the need for an intermediary. The revolutionary
technology is gaining traction due to its efficient reduction of risks and fraud.
But why are decentralized P2P networks like blockchain superior to centralized ones? The
reasons lie in their enhanced reliability, privacy, and scalability, with no single point of
failure.
Blockchain owes its distributed nature to shared communication and distributed processing.
Its P2P architecture has several benefits. For instance, it is more secure than traditional client-
server networks.
Blockchains are shielded from malevolent activities as their distributed P2P networks need
majority consensus.
Key Features of a Blockchain
In this guide, we will delve into the key features of a blockchain. Also, we will explore the unique
characteristics that have made it a game-changer in various industries.
From its decentralized nature to its unparalleled security, prepare to unravel the intricate details
that make blockchain a technological marvel
1. Distributed Ledger Technology
This ledger, available to all network members, holds an immutable transaction record. This
eliminates the need for recording transactions multiple times, as seen in traditional business
networks.
2. Permanent Records
Once your transaction is recorded properly in the shared ledger, it is irreversible. Errors in
transaction records must be corrected by rewriting the record, making both transactions visible.
3. Smart Contracts
These are a set of rules stored and automatically executed on the blockchain to expedite
transactions. They help define transaction terms and conditions.
Why is Private Blockchain Important?
Information is vital to business success. With immediate, shared, transparent, and immutable
information storage accessible only by authorized network members, blockchain is a suitable
technology for storing and retrieving such data.
Blockchain networks can track orders, payments, production, and more. Its shared truth gives
every transaction detail from start to end, instilling confidence and creating new exploration
opportunities.
Enhanced Security: Unlike public blockchains that are open to everyone, private
blockchains are restricted. This means fewer chances for hackers or unauthorized
individuals to cause harm because they simply can’t access it. It’s like having a private
room with a secure lock.
Greater Control: In a blockchain, a company or organization decides who can join, make
transactions, or validate them. This ensures that only trusted members can participate,
98
reducing errors or malicious activities. Think of it as a members-only club where everyone
knows each other.
Increased Efficiency: With fewer participants in the network, transactions can be
processed much quicker. It’s similar to having a shorter line at the checkout counter; you
get through faster.
Privacy Protection: Only selected individuals or entities can view the data in a private
blockchain. This is vital for businesses that maintain sensitive information, like financial
records or personal details. It’s like having a diary that only you and a few trusted friends
can read.
Tailored Solutions: Since a company controls its private blockchain, it can customize it
to fit specific needs or preferences. It’s like building your own house, where you decide
the design, color, and layout.
99
Nonce: An arbitrary number that, combined with the block’s data, produces the block’s
hash. This is important in mining, where miners use computation to find the block’s hash.
Public blockchains are permission less, allowing anyone to participate. All users have equal rights
to see and verify blockchain activities, giving it a self-governing nature. Examples include
Litecoin, Ethereum, and Bitcoin.
Any user can sign up to be a node on these networks, which verify transactions and maintain a
copy of the distributed ledger. Similar to their public counterparts, private blockchains are digital
ledger technologies that are centrally managed.
100
The central authority determines participation, transaction verification, and ledger maintenance.
They’re not entirely decentralized, with restricted public access, serving as a more sensible option
for organizations who see the benefits of blockchain.
101
Transparency and Anonymity: All users can view every activity on the private
blockchain. Specific users can also be anonymized if suitable for your business model.
Performance Coupled with Data Integrity: Blockchain transactions can sometimes take
hours, depending on transaction volume and associated fees.
Steps to build a Private Blockchain Platform:
102
The Procedure for Developing a Private Blockchain
If you prefer not to use a public blockchain for your needs and want to establish your own private
network instead, the following methodology will guide you:
Step 1: Select The Protocol
Firstly, choose a blockchain framework. Here are a few options:
An EVM-based protocol for Ethereum compatibility
The Substrate framework for a secure, rapid, cost-effective, and well-supported blockchain
development experience
Cosmos or Provenance to create a scalable private blockchain ecosystem
Forking an existing protocol
Step 2: Construct The Core Logic
After selecting the protocol, construct the core logic of your private blockchain, which includes:
Modifying the existing logic
Determining the consensus algorithm
Setting the transaction fee
Enhancing header information
Adjusting block height
Building pallets
Selecting an appropriate permission module
Choosing the suitable file storage option for your chain
Step 3: Develop The Logic
Upon establishing the core logic, enter the DevOps phase, which encompasses:
Hosting a test network
Finalizing your chain’s file storage
Creating a Genesis key store
Deciding on the launch node count and their geographical regions
Integrating APIs for free information exchange with external sources
Step 4: Testing
After concluding the DevOps phase, launch your test network. Test your faucet, wallet, block
explorer, and SDKs, employing a dedicated benchmarking and monitoring tool. The
comprehensive testing procedure includes:
Checking the seamless operation of all integrations
Assessing the blockchain network’s scalability
Confirming the blockchain’s functionality
Identifying and rectifying blockchain security vulnerabilities
Resolving network connectivity issues
Testing network migration possibility
Evaluating the chain’s performance
Step 5: Launch the Main Network
Once the testing phase concludes and all detected issues are resolved, you can launch the main
network.
Step 6: Network Integration
103
Finally, integrate your faucet, wallet, block explorer, benchmarking and monitoring tool, and
SDKs with the main net. With this step, your private blockchain network is set and ready.
A Guide to Constructing a Private Blockchain using Ethereum
In the ever-evolving blockchain world, a private blockchain utilizing Ethereum is a powerful tool
for various industries, from finance to healthcare. This in-depth guide takes you through the
creation of your very own private Ethereum blockchain.
The Ethereum network is a mesh of interconnected nodes or EVMs (Ethereum Virtual Machines).
Each node, containing a duplicate of the entire blockchain, can mine the subsequent block. They
are expanding the blockchain and broadcasting the update to the entire network.
To become a node in the Ethereum network, you’ll need to install the complete Ethereum
blockchain on your computer.
This can be accomplished with Ethereum tools that allow your computer to download and interface
with the Ethereum network. An essential tool is Geth, which we’ll discuss further.
Understanding Geth
Geth, the Go implementation for Ethereum, is a Command Line Interface (CLI). It provides a
conduit between your computer, its hardware, and the other nodes within the Ethereum network.
When another node mines a block, Geth alerts your CPU or GPU or to update your blockchain.
Geth enables you to:
Mine Ether, the driving cryptocurrency behind the Ethereum network
Transfer funds between different addresses
Establish smart contracts and send transactions
Examine block history and more
How to Install Geth
On macOS
1. Begin by installing Geth through the Geth Homebrew tap. Check whether Homebrew is installed
on your computer. If not, you can install Homebrew in the system.
2. After installing the Homebrew, you can use the following commands to add the Geth tap and
install Geth:
bash
brew tap Ethereum/Ethereum
brew install ethereum
3. To install the master branch of the Geth repository, use the –devel parameter in the install
command:
CSS brew install Ethereum –devel
4. The above commands install core Geth software and the following developer tools: devp2p,
clef, boot node, evm, rlpdump, puppeth, and abigen. All tool binaries are saved in /usr/local/bin/.
A full list of command-line options can be obtained by running geth –help.
104
To update Geth to its latest version, stop the node and run these commands:
SQL
brew update
brew upgrade
brew reinstall Ethereum
5. Now, you can restart Geth, which will utilize the previous data to sync any unavailable blocks
while it is offline.
Post-Installation Steps
After installing Geth, you can reach to the main Ethereum blockchain network or establish a fully
custom Ethereum network. Even if you don’t own Ether, Geth allows the creation of a private
Ethereum blockchain network.
It functions as a development or staging network mirroring the main Ethereum network. This
private network enables you to create smart contracts, make transactions, and distribute apps
without the need for real Ether.
Creating The Genesis Block
A blockchain is a public, chronological record of transactions stored in blocks. To create a private
blockchain, you first need to create a Genesis block.
For this, you’ll need to create a custom Genesis file and instruct Geth to use it to create your private
blockchain.
Here is an example of what a Genesis file looks like:
JSON
{
“config”: {
“chained”: 15,
“homesteadBlock”: 0,
“eip155Block”: 0,
“eip158Block”: 0
},
“nonce”: “0x0000000000000042”,
“timestamp”: “0x00”,
“parentHash”:
“0x0000000000000000000000000000000000000000000000000000000000000000”,
“extraData”: “0x00”,
“gasLimit”: “0x08000000”,
“difficulty”: “0x400”,
“mixhash”: “0x0000000000000000000000000000000000000000000000000000000000000000”,
“coinbase”: “0x3333333333333333333333333333333333333333”,
“alloc”: {}
}
Next, create a CustomGenesis.json file in a folder on your system and run this command:
105
bash
geth — identity “yourIdentity” — init /path_to_folder/CustomGenesis.json — data-dir
/path_to_your_data_directory/ACP
Generating a Private Network to Share the Blockchain
Having created the genesis of our private blockchain, we’ll now start our private network to mine
new blocks. The following command achieves this:
CSS
geth –data-dir /path_to_your_data_directory/ACPrivateChain –networkid 9876
Upon running this command, your private network will be activated.
Webisoft Private Blockchain
Webisoft offers a unique private blockchain solution tailored to meet the modern businesses’ all
needs. With a focus on simplicity, security, and efficiency, Webisoft’s private blockchain is
designed for those seeking a reliable and easy-to-use platform. Some of our blockchain services
are:
Blockchain Consulting: Our blockchain experts will guide you on everything related to
blockchain. They’ll examine your business needs, study the market, and suggest the latest
ideas.
Smart Contracts Development: We make safe and tailored smart contracts. They also
use less Ethereum gas.
Custom Blockchain Development: We can make special blockchains just for you, along
with other applications and services using blockchain.
DeFi Development: We make financial tools using blockchain. We use platforms like
Ethereum, EOS, Tron, and Bitcoin.
dApp Development: Our skilled team can create secure and big apps that work on a
decentralized system.
106
3.12. METAMASK BROWSER PLUG-IN
What is MetaMask?
MetaMask is a browser plugin that serves as an Ethereum wallet, and is installed like any other
browser plugin. Once it’s installed, it allows users to store Ether and other ERC-20 tokens,
enabling them to transact with any Ethereum address.
By connecting to MetaMask to Ethereum-based dapps, users can spend their coins in games, stake
tokens in gambling applications, and trade them on decentralized exchanges (DEXs). It also
provides users with an entry point into the emerging world of decentralized finance, or DeFi,
providing a way to access DeFi apps such as Compound and PoolTogether.
How to get started with MetaMask
MetaMask is one of the simpler Ethereum wallets and dapp browsers to use, and can be set up in
a couple of minutes in most cases. To use MetaMask, you will need either Chrome, a Chromium-
based browser such as Brave, or Firefox. Follow the steps to then set up your MetaMask Wallet
1. Download and install the official Metamask extension (also known as a plugin or add-on)
for your chosen browser. For most people, this is the Google Chrome extension or
the Firefox addon.
2. Click the ‘Get Started’ button to begin creating your Ethereum wallet using MetaMask.
3. On the next step, click the ‘Create a Wallet’ button.
4. Pick a password and confirm it to create your account.
5. MetaMask will then present you with your 12-word backup phrase. You’ll need to write
this phrase down carefully, with the words recorded in the same order displayed on your
screen. This phrase will be needed to recover your wallet should you ever lose access to
your computer, and should be kept stored somewhere safe. Anybody who has access to
your 12-word backup phrase will have access to the funds in your MetaMask wallet, so
keep it private.
6. Click ‘Next’ and confirm your backup phrase on the next screen by entering the words in
the same order saved previously.
7. You have now almost completed the MetaMask setup process. You can now access your
list of assets in the ‘Assets’ tab and view your transaction history in the ‘Activity’ tab.
107
Using your Wallet
Sending crypto is as simple as clicking the ‘Send’ button, entering the recipient address and amount
to send, and selecting a transaction fee. You can also manually adjust the transaction fee using the
‘Advanced Options’ button.
108
The Mist browser is a user-friendly interface for end users with a feature-rich graphical user
interface that is used to browse Decentralized Applications (DApps) and for account
management and contract management.
Key Features of the Mist Browser:
As the Ethereum ecosystem evolved, the Mist browser aimed to offer a robust set of features,
making it more than just a typical web browser. Some of its key capabilities included:
Generating user selected smart contracts.
Enabling users to pool tokens, creating a trustless decentralized crowdfunding solution.
Facilitating secure information sharing among a select group of participants.
Essentially, the Mist browser aimed to empower users to “do” more within the browser itself,
providing ready-made templates, configurations, customizations, and the ability to perform
actions, making it more than just a simple web browser.
109
1. Download and Install Mist Browser: The first step is to download and install the Mist
Browser on your device. You can find the download link on the Ethereum website. Make
sure to choose the version that is compatible with your operating system.
2. Create a New Wallet: Once you have installed Mist Browser, the next step is to create a
new wallet. Click on the "Launch Application" button, and a new window will open. From
there, click on the "Create a New Wallet" button, and follow the prompts.
3. Backup Your Wallet: It's essential to backup your wallet to ensure that you don't lose
your funds in case of device failure. Mist Browser makes it easy to backup your wallet by
providing a mnemonic phrase. Make sure to store this phrase in a safe place.
4. Connect to the Ethereum Network: To use Mist Browser for cryptocurrency
transactions, you need to connect to the Ethereum network. Click on the "Ethereum
Network" dropdown menu, and choose the network you want to connect to. Mist Browser
supports both the main Ethereum network and test networks like Ropsten and Rinkeby.
5. Send and Receive Ether: With Mist Browser, you can send and receive Ether easily. To
send Ether, click on the "Send" button, and enter the recipient's address and the amount
you want to send. To receive Ether, click on the "Receive" button, and share your wallet
address with the sender.
Creating a Wallet in Mist Browser
A cryptocurrency investor or a beginner, creating a wallet in Mist Browser is an essential task that
can help you manage your cryptocurrency transactions effectively. Once you have created your
wallet, you can start sending and receiving cryptocurrencies, and you can rest assured that your
assets are safe and secure.
110
To create a wallet in Mist Browser, follow the steps below:
1. Download Mist Browser: Before you can create a wallet, you need to download the Mist
Browser. You can download it from the official Ethereum website. Once you have
downloaded and installed the browser, you can launch it and get started.
2. Create a new wallet: To create a new wallet in Mist Browser, click on the 'Accounts' tab
and select 'New Account'. You will be prompted to enter a name for your new account.
This can be anything you like, but it's a good idea to choose a name that is easy to
remember.
3. Set a password: After you have entered a name for your new account, you will be
prompted to set a password. This password will be used to encrypt your private key, so it's
important to choose a strong password that is difficult to guess. Make sure you write down
your password somewhere safe, as you will need it to access your wallet in the future.
4. Save your keystore file: Once you have set a password, you will be asked to save your
keystore file. This file contains your private key, so it's important to keep it safe and secure.
You can save the file to your computer or to an external storage device, such as a USB
drive.
5. Backup your private key: In addition to saving your keystore file, it's a good idea to
backup your private key. You can do this by clicking on the 'Accounts' tab and selecting
'Backup'. Follow the prompts to backup your private key to a safe location.
111
Sending Cryptocurrency Transactions through Mist Browser
Sending cryptocurrency transactions through Mist Browser can be a secure and efficient way to
manage your digital assets. Mist Browser's features and capabilities, you can start managing your
cryptocurrency transactions with confidence and ease.
1. Install Mist Browser: Before you can start sending cryptocurrency transactions through
Mist Browser, you'll need to download and install the software on your computer. Mist
Browser is available for Windows, Mac, and Linux operating systems and can be
downloaded from the official Ethereum website.
2. Create a Wallet: Once you've installed Mist Browser, you'll need to create a wallet to
store your digital assets. Mist Browser supports both single and multi-signature wallets,
which provide different levels of security and control over your digital assets. To create a
wallet, simply follow the on-screen instructions and make sure to securely back up your
wallet's private key.
3. Send a Transaction: To send a cryptocurrency transaction through Mist Browser, you'll
need to have some digital assets in your wallet. Once you have a sufficient balance, click
on the "Send" button in the mist Browser interface and enter the recipient's wallet address
and the amount you wish to send. You can also set a gas limit and gas price to ensure that
your transaction is processed quickly and efficiently.
4. Benefits of Using Mist Browser: One of the main benefits of using mist Browser for
managing cryptocurrency transactions is its security features. Mist Browser is designed
to protect your digital assets from hackers and other threats, and provides advanced
encryption and authentication features to ensure that your transactions are safe and secure.
Additionally, Mist Browser offers a user-friendly interface and a wide range of
customization options to help you manage your digital assets more efficiently.
5. Drawbacks of Using Mist Browser: While mist Browser is a powerful tool for managing
cryptocurrency transactions, it does have some drawbacks. One of the main drawbacks is
its complexity, which can make it difficult for beginners to use. Additionally, Mist Browser
requires a significant amount of computing power and storage space, which can be a
challenge for users with older computers or limited resources.
112
Tracking Transaction History in Mist Browser
As a cryptocurrency enthusiast, keeping track of your transaction history is crucial. It allows you
to monitor your account balance, verify transactions, and detect fraudulent activities. Fortunately,
Mist Browser provides a user-friendly interface that enables you to track your transaction history
with ease. Whether you are a seasoned crypto trader or a newbie, Mist Browser is a reliable tool
that can help you manage your cryptocurrency transactions.
One of the primary features of Mist Browser is its ability to display a detailed transaction history.
To access this feature, you need to navigate to the "Accounts" section, which displays a list of all
the accounts you have created. Once you have selected the account you want to view, you can
click on the "Transactions" tab, which will display a list of all the transactions associated with that
account. The transaction history provides you with valuable information, such as the date and time
of the transaction, the amount transferred, and the recipient's address.
Here are some other ways you can track your transaction history using Mist Browser:
1. Search Transactions: If you want to search for a specific transaction, you can use the search
bar located at the top of the "Transactions" tab. You can search for transactions by date, address,
or transaction hash. This allows you to quickly locate a specific transaction, which can be useful
if you need to verify a payment or check for errors.
2. Export Transactions: Mist Browser also allows you to export your transaction history to a
CSV file. This can be useful if you need to share your transaction history with your accountant or
tax professional. To export your transaction history, simply click on the "Export" button located
at the top of the "Transactions" tab.
3. View Transaction Details: If you want to view more detailed information about a specific
transaction, you can click on the transaction hash. This will display a pop-up window that provides
you with additional details, such as the gas used, the gas price, and the transaction status. You can
also view the transaction on the blockchain explorer by clicking on the "View on Etherscan"
button.
tracking your transaction history is an essential aspect of managing your cryptocurrency
transactions. Mist Browser provides you with the tools you need to monitor your account balance,
verify transactions, and detect fraudulent activities. By utilizing the features discussed above, you
can ensure that your cryptocurrency transactions are secure and transparent.
113
Managing Multiple Wallets in Mist Browser
When it comes to managing cryptocurrency transactions, it is essential to have a reliable and secure
platform. Mist browser is one such platform that has gained popularity among crypto enthusiasts.
One of the significant advantages of Mist browser is that it allows you to manage multiple wallets
from a single interface. This can come in handy when dealing with different cryptocurrencies or
when managing various accounts.
Managing multiple wallets in Mist browser is a robust and straightforward process that ensures
that all your transactions are in one place. Here are some insights on how to manage multiple
wallets effectively:
1. Add a new wallet: To add a new wallet in Mist browser, click on the "Accounts" tab and select
"Create a New Account." You will then be prompted to set a password for the wallet and download
the Keystore file, which is a file that contains your wallet's private key. Once you have done this,
your new wallet will be added to the list of accounts in Mist browser.
2. Switch between wallets: To switch between wallets, click on the "Accounts" tab and select the
wallet you want to use. You can also use the drop-down menu to switch between wallets quickly.
3. Rename your wallets: It's a good idea to rename your wallets to make it easier to identify them.
To rename a wallet, click on the wallet name, and type in the new name.
4. Backup your wallets: Backing up your wallets is critical to ensure that you don't lose your
funds in case of a hardware failure. To backup your wallets, click on the "Accounts" tab, select the
wallet you want to backup, and click on "Backup." You will then be prompted to save a copy of
your Keystore file.
5. Import an existing wallet: If you have an existing wallet that you want to import into Mist
browser, click on the "Accounts" tab and select "Import Accounts." You will then be prompted to
enter your private key or Keystore file.
Managing multiple wallets in Mist browser is an excellent way to keep track of all your
cryptocurrency transactions. With these insights, you can easily add, switch, rename, backup, and
import your wallets, ensuring that your transactions are safe and secure.
114
network, there are several security measures in place to ensure that cryptocurrency transactions
are safe and secure. These security measures are designed to protect your private keys and prevent
unauthorized access to your account. In this section, we will explore the different security
measures implemented in Mist browser to secure cryptocurrency transactions.
1. Passwords and Private Keys:
When you first create your wallet in Mist browser, you will be prompted to create a password.
This password is used to encrypt your wallet and keep it secure. Additionally, when you create a
new account, Mist browser will generate a private key, which is a unique cryptographic code that
is used to sign transactions. It is crucial to keep your private key secure, as it is used to access your
funds. You should never share your private key with anyone, and you should also make sure to
keep it in a safe place.
2. Two-Factor Authentication:
In addition to passwords and private keys, Mist browser also supports two-factor authentication.
This means that you can set up an additional layer of security, which requires you to enter a code
sent to your mobile device or email before you can access your account. Two-factor authentication
is an effective way to prevent unauthorized access to your account, even if someone has your
password.
3. Secure Network:
Mist browser is designed to run on the Ethereum network, which is a decentralized network of
computers. This means that there is no central point of failure, and the network is highly secure.
Transactions on the Ethereum network are confirmed using a consensus mechanism called Proof
of Stake, which ensures that transactions are legitimate and secure.
4. Smart Contracts:
One of the unique features of the Ethereum network is the ability to create and execute smart
contracts. Smart contracts are self-executing contracts with the terms of the agreement written into
code. They can be used to automate transactions and ensure that they are executed according to
the agreed-upon terms. Smart contracts are highly secure, as they are executed on the Ethereum
network and cannot be altered once they have been deployed.
Mist browser offers several security measures to ensure that your cryptocurrency transactions are
safe and secure. By using passwords and private keys, two-factor authentication, a secure network,
and smart contracts, you can be confident that your funds are protected. It is essential to follow
115
best practices for cryptocurrency security, such as keeping your private keys safe and using strong
passwords, to ensure that your assets are secure.
Future of Cryptocurrency Transactions with Mist Browser
To help you get the most out of this powerful tool, we've compiled a list of some of the most
important features and capabilities offered by Mist Browser:
1. Wallet management: One of the main features of Mist Browser is its built-in wallet
management system. This allows users to easily create and manage their own digital wallets, which
can be used to store various types of cryptocurrencies.
2. Transaction tracking: Mist Browser also allows users to track their cryptocurrency
transactions, providing real-time updates on the status of each transaction.
3. Smart contract deployment: For more advanced users, Mist Browser also supports the
deployment of smart contracts on the Ethereum blockchain. This allows users to create and execute
their own decentralized applications.
4. DApp browsing: Additionally, Mist Browser provides support for browsing decentralized
applications (DApps) directly within the platform. This allows users to easily discover and interact
with a wide range of different DApps.
5. Community support: Finally, Mist Browser has a large and active community of developers
and users, providing a wealth of resources and support for those looking to get the most out of the
platform.
Pros and Cons of a Mist Browser:
Sl.No Pros Cons
1 Introduced a graphical user interface for Susceptible to security vulnerabilities
Ethereum dApps due to delayed updates.
2 Integrated Ethereum wallet for convenient Resource intensive requirements for
crypto management blockchain synchronization
3 Paved the way for future developments in the Discontinued in March 2019 due to
blockchain ecosystem. insurmountable challenges
116
Metamask: A popular Ethereum wallet and dApp browser
Metamask quickly gained popularity as a browser extension and mobile app, offering users a
convenient way to manage their Ethereum assets and interact with dApps. It provides a secure and
user-friendly experience, making it a preferred choice among Ethereum enthusiasts.
MetaMask boasts a simple interface that integrates with popular browsers like Chrome and
Firefox, allowing users to seamlessly access dApps and manage their Ethereum accounts. It also
provides a secure and user-friendly experience, making it a preferred choice among Ethereum
enthusiasts.
Trust Wallet: Mobile focused Ethereum Wallet
Trust Wallet is a mobile-centric Ethereum wallet that allows users to store and manage Ethereum
and various other cryptocurrencies. With a user-friendly design and an emphasis on security, Trust
Wallet has become a popular choice for those who prefer managing their assets on their mobile
devices.
Trust Wallet provides an intuitive and straightforward experience for users to access their
Ethereum accounts, making it ideal for those who primarily interact with the Ethereum ecosystem
on their smartphones.
117
Ethereum wallets are controlled through a private key, or a “password,” that allows users
to move the funds within the wallet. These private keys are only supposed to be known to
the wallet’s creator, as anyone who knows them can access their funds.
There are several types of Ethereum wallets to choose from including some that are held on your
desktop or mobile device and some that are held offline through a piece of paper, titanium, or
hardware.
Typically, your crypto wallet will provide you with a secret recovery phrase when you set
it up initially. While this is not true for all Ethereum wallets (such as Ethereum paper
wallets) most crypto wallets today follow a hierarchical deterministic model, meaning
they allow you to generate a near infinite number of Ethereum accounts with a single
wallet. The standardized secret recovery phrases, they also allow you to restore all of these
accounts with any HD wallet provider.
your Ethereum wallet can typically generate and store private keys for a range of accounts.
Each new account in your wallet is controlled by a separate key pair. The public key is the
unique identifier of the account, allowing people to find your account details and send you
funds. The private key, on the other hand, is what you use to sign transactions: it allows
you to control the funds at a specific address.
Your Ethereum wallet’s job is to store that private key and keep it safe from potential
onlookers. Some Ethereum wallets will store those keys on your laptop or smartphone,
others will store them on a separate physical device.
118
The final step is allowing you to sign transactions. To sign a transaction, your wallet uses
your private key, thus verifying you agree to the terms of what you’re signing.
Beyond these simple workings, there’s a lot more to it. For example, some wallets don’t
allow you to manage your private keys yourself, and private key storage can also vary
greatly from wallet to wallet.
Hot and cold wallets
In the cryptocurrency sector, there are two main types of wallets: hot and cold. Hot wallets are
those stored on devices connected to the internet such as a desktop PC or Mac and a mobile device.
Cold wallets, on the other hand, store the user’s private keys offline. Being offline eliminates
several attack spots that hackers could take advantage of such as infecting other people’s devices
with malware to access their keys. Malware is software designed to either damage or gain
unauthorized access.
Hot wallets are often more user-friendly and allow users to access their funds anytime from
anywhere. On the other hand, cold wallets are typically less intuitive and can make it a tad harder
to move your funds.
Sl.No Description Hot Wallets Cold Wallets
1 Connectivity Connected to internet Stored offline
2 User Experience Most user friendly Loss intuitive
3 Security Less secure Harder to hack and exploit
4 Storage Pieces of software stored on Pieces of hardware stored
mobile or desktop devices. physically.
Due to security concerns, users should keep most of their cryptocurrency offline in cold wallets,
while moving only what they need to meet short-term obligations in hot wallets.
The process of storing most cryptocurrency offline in cold wallets could be similar to what is
already common with fiat currencies. Bank accounts and safe deposit boxes are safer and people
rely on them to store their savings (just like cold wallets). And just like with checking accounts,
the crypto people carry for daily transactions should be kept in hot wallets.
Types of Ethereum wallets
Some use cryptocurrency exchanges and other services including marketplaces and lending
services offered by wallets for users to store their Ethereum holdings. These are called custodial
wallets, which are wallets that hold users’ private keys for them. These have a trade-off as the
119
service controls the private keys to the wallet and lets the user access the funds in them instead of
the user controlling the funds directly.
Storing funds with a third-party through custodial wallets increases counterparty risk — the risk
of another party defaulting on their obligations. The service holding the private keys may get
hacked or go rogue, for example.
To take full advantage of the decentralized applications (DApps) built on Ethereum, users need
access to their own private keys. Decentralized applications are digital applications that run on
blockchains.
Different wallets may be useful for different types of users. Most wallets only let users send and
receive Ethereum or tokens built on the network using the ERC-20 standard. The ERC-20 token
standard defines a list of rules for issuing tokens on the Ethereum network. However, not all
Ethereum wallets share the same features.
Some Ethereum wallets can be connected to a credit or debit card to let users buy cryptocurrency
directly to their wallets. Other features include allowing users to hold nonfungible tokens (NFTs),
which are cryptographic assets on the blockchain with unique identification data. While Ether, for
example, is fungible as 1 ETH will always be worth 1 ETH, no two NFTs are alike.
With Ethereum wallets, it may also be possible to use DApps, or digital programs on the
blockchain. Social media platforms, games, marketplaces and financial services platforms have
been built on Ethereum and other blockchains. Ethereum wallets with built-in browsers compatible
with DApps let users access them directly.
Ethereum wallets also make it easier to buy crypto directly by letting users connect their bank
accounts. Bank account transfers often charge lower fees and make it easier to buy and sell crypto
through recurring payments.
To bolster security, Ethereum wallets may let users choose addresses to move their funds. If
anyone tries to transfer funds to an address not on the list, the transaction is blocked. Ethereum
accounts may also offer multisignature (multisig) accounts that require more than one signature to
move funds. Multisig accounts are common in several blockchain platforms and even in the
traditional financial system.
Some wallets have several of the features described above, while others only have one. More
advanced wallets even let users hold Ethereum, ERC-20 tokens and other cryptocurrencies to
explore decentralized applications on various networks.
120
It is worth pointing out that you do not have to choose one out of all the Ethereum wallets available.
Private keys give you access to your wallet, which can be accessed via mobile phones, desktops,
browsers or in printed form like paper wallets all at the same time.
The interface used to connect to the Ethereum blockchain changes, but addresses, transactions and
other data remain the same, similar to the way that different browsers may be used to access the
same website. Limiting your exposure by using only one type of wallet may nevertheless be better
to ensure that your funds are safe.
Mobile wallets
Mobile wallets are light nodes that do not require users to download the entire blockchain.
Mobile wallets are applications that can be installed on mobile devices as easily as any
other application from Apple’s App Store or Google Play and can be used to access your
funds using a cellular connection.
They rely on miners to relay precise information about the network’s present state. One of
the disadvantages of a mobile wallet is that it is easy to hack and if your mobile device is
lost, you may lose access to your Ethereum funds. However, having backups can keep you
safe from any loss arising out of hacks or unintentionally losing your keys.
Most popular mobile wallets support Ethereum and ERC-20 tokens and come with built-
in browsers ready to interact with decentralized applications and the decentralized
finance (DeFi) sector, built out of decentralized applications offering financial services.
Desktop wallets
Desktop wallets run on operating systems (OS) like macOS, Microsoft Windows, or Linux
OS. Desktop wallets are ideal for those who prefer to handle their finances on desktops.
Because most desktop wallets keep keys locally, users will need to use their computers to
access their Ethereum wallets.
Users can use a light client or download a full client with the entire Ethereum blockchain
with such wallets. Downloading a full client is considered to be a preferable alternative
because it eliminates the need for miners to feed them accurate data. Instead, they validate
transactions themselves, resulting in increased security.
Similar to mobile wallets, desktop wallets not only allow users to send and receive
Ethereum but can provide a number of advanced features to allow users to create smart
121
contracts or run a full node, effectively giving users more functionalities within their
wallets.
Since desktop wallets are connected to the internet, they are considered hot wallets. The
private keys to these wallets are stored on users’ machines and not on any external servers,
making them vulnerable to hacking.
Web interfaces
Web interface wallets are a popular alternative to both mobile and desktop wallets and are
essentially websites that let users interact with the Ethereum blockchain after connecting
their wallets to the interfaces.
Web wallets allow users to use a web browser to connect with their accounts. These wallets
take advantage of cloud storage and can be accessed from anywhere in the world. Cloud
storage makes use of the enormous computer servers housed in data centers that physically
store data and make it accessible to customers via the internet. The stored data can be
delivered on-demand with just-in-time capacity and costs, eliminating the need to purchase
and manage data storage equipment.
Using web interface wallets directly can be risky, as users have to trust a website with their
private keys. While some web interfaces are considered trustworthy, users may still be
vulnerable to a number of attacks unrelated to the wallets themselves.
These attacks include phishing schemes in which hackers can access a website
impersonating the legitimate web interface. Similarly, domain name system (DNS) attacks
may occur where users’ internet activity is redirected to a malicious server that uses
collected data like login credentials to access their information.
Browser extensions
Browser extensions are used on desktop browsers to interact with decentralized
applications and can store both ETH and ERC-20 tokens, all while supporting a nearly
infinite number of addresses. To more advanced users, browser wallets are also useful
because they can be used to interact with other blockchains.
Browser extensions are seen as a safer alternative to web interfaces, as they store users’
private keys on their browsers in an encrypted way. To access their wallets, users will need
to protect them with a password which bolsters security.
122
Like mobile wallets, installing browser extensions is easy and is done in the same way
users install any other browser extension. Some browsers already come with built-in
Ethereum wallets that make it even easier to interact with DApps.
Hardware wallets
Hardware wallets are pieces of hardware that store users’ private keys offline and are, as
such, cold wallets. Hardware wallets have to be connected to a computer for the funds to
be moved and are password or PIN protected.
To gain access to the funds, a malicious party would need physical access to the device and
know the password protecting the funds. However, hardware wallets can be expensive for
users with smaller amounts of funds to store.
It is important to never buy a used hardware wallet nor buy one from a third-party vendor.
After being used for the first time, these wallets could be compromised to trick users into
believing that they are sending funds to a wallet only they control, while the initial owner
of the hardware wallet may already have access to it.
Paper wallets
Paper wallets are a more basic type of cold wallet and essentially involve printing out the
private keys that control the funds onto a piece of paper and storing it. To access the funds,
malicious actors would need access to that piece of paper. The main advantage of this type
of wallet is its accessibility, as all that is needed is a pen and a piece of paper.
Because of the fragile nature of the material they are printed on, these wallets may not be
suitable to hold long-term, as there have been cases of the paper getting destroyed or
mistakenly thrown out. Alternatives include pricier titanium plaques that could even resist
natural disasters because of the material they are made of.
Funding your ETH wallet
After choosing an Ethereum wallet to use and explore the network, it is necessary to add funds to
it. To interact with decentralized applications on Ethereum, users will need Ether, the native
cryptocurrency of the network that is used to pay for transactions.
Ether can be bought on centralized exchanges and withdrawn to a user’s wallet. Doing so will
involve sending the funds to a public wallet address, which can be seen as the equivalent of an
international bank account number (IBAN) used in the traditional financial system.
123
Every transaction on Ethereum incurs a transaction fee that is paid to network validators who help
maintain its integrity. The amount of fees can vary according to demand for block space on the
blockchain. Block space refers to the amount of space available in each block of data added to the
network. Software wallets provide fee estimates to help users avoid overpaying by estimating
network transaction fees according to the latest demand for block space.
It is worth noting that EOAs communicate with each other and with smart contracts through
messages. The term transaction refers to a signed package of data that stores a message, which can
be sent between accounts. These communications are “wrapped” in transactions funded with Ether.
Contracts can also send messages to other contracts. For this to happen, a transaction creating a
new contract has to first occur so the contract can then be triggered.
Keeping your ETH safe
Users often do not worry about how safe their funds are while they are stored in a bank
account, nor do they worry about a third-party accessing their bank account and draining
it without authorization.
When it comes to Ethereum wallets and other cryptocurrency wallets in general, the above-
mentioned scenarios are a possibility, and avoiding them is fundamental to the protection
of funds. The Ethereum community recommends that users triple check everything to
ensure they always send funds to the right address, always interact with the applications
they intend to and write down the private key as they should.
Bookmarking your web wallet and the websites of any decentralized applications you
regularly use is also a known best practice to help avoid phishing schemes. Some browser
extension wallets have a list of known phishing schemes and will automatically block
undesirable websites to protect users.
When dealing with DeFi protocols, it is always important to find out whether the service
is legitimate and audited to ensure that security experts have reviewed its code. To find
out, simply search the web for the name of the service and the word “audit” or “review.”
Finally, keep in mind that if it looks too good to be true, it probably is. Scammers often
hijack verified social media accounts to promote fake giveaway scams and other schemes
to trick users into sending them Ethereum. Avoiding such schemes is simply a matter of
ignoring what looks too good to be true and doing your own research into newer projects.
124
Wallet Top coins Type of Price Why We Chose It Pros Cons
Name supported wallet
Guarda Ethereum (ETH), Non- Free Guarda Wallet has established itself First-rate security High in-app crypto
Wallet Bitcoin (BTC), custodial as a highly secure, multi-asset Supports 400,000+ assets across 50+ purchase fees
Tether USD crypto wallet that enables users to blockchain networks
(USDT), Cardano securely store, send, and receive Enables users to earn, borrow, and
(ADA), Solana Ethereum (ETH) and Ethereum- swap crypto
(SOL) based tokens. Fiat on-ramp
High-quality customer service
Exodus Ethereum (ETH), Non- Free Exodus Wallet is a beginner- User-friendly interface Not an open-source
Bitcoin (BTC), custodial friendly, multi-asset cryptocurrency Supports a wide range of Ethereum- wallet
Litecoin (LTC), wallet that enables investors to based tokens
Tether USD securely manage Ethereum (ETH) Enables users to earn staking
(USDT), Dogecoin and a range of Ethereum-based rewards
(DOGE) tokens, including NFTs, in one Fiat-to-crypto on-ramp
place. In-app asset swapping
Metamask Ethereum (ETH), Non- Free MetaMask is one of the most Supports all Ethereum tokens Doesn’t support
Shiba Inu (SHIB), custodial popular Ethereum wallets in the Supports NFTs Bitcoin
Uniswap (UNI), market, with over 30 million users Beginner-friendly interface
Aave (AAVE), Dai globally utilizing the wallet to Access to decentralized applications
(DAI) manage their Ethereum-based assets
and interact with dApps in the
Ethereum ecosystem.5
Trust Ethereum (ETH), Non- Free Trust Wallet is a popular multi-asset Easy-to-use mobile wallet No desktop wallet
Wallet Bitcoin (BTC), custodial mobile crypto wallet that supports Supports over 10 million digital
Binance Coin over 10 million digital assets across currencies and tokens
(BNB), Solana 70+ blockchains. Additionally, In-app staking
(SOL), Litecoin Trust Wallet comes with a mobile Access decentralized applications on
(LTC) dApp browser that enables users to the go
explore the Ethereum dApp Fiat on-ramp and token swapping
ecosystem, including DeFi and
NFTs, on the go.
Myetherw Ethereum (ETH), Non- Free MyEtherWallet (MEW) is a Extensive smart contract Somewhat
allet Tether USD custodial popular open-source, client-side functionality advanced for
(MEW) (USDT), Dai (DAI), Ethereum wallet that stands out for Supports all Ethereum tokens beginners
Shiba Inu (SHIB), its broad functionalities around the Ethereum NFT support
Wrapped Bitcoin creation, development, and use In-app asset swapping
(WBTC) of smart contracts.
125
How do I create an Ethereum wallet?
Creating an Ethereum wallet is as easy as installing software on your mobile device or
laptop/desktop. When you install the app, your Ethereum wallet is automatically created. You can
then receive ether (ETH) to your wallet immediately, store it safely, and use it as you please.
Why do I need an Ethereum wallet?
Centralized cryptocurrency exchanges are a popular place for many newcomers to buy their first
ETH. However, when you buy ETH on a cryptocurrency exchange, the exchange retains control
over your ETH. Not only does this expose you to the risk of the exchange getting hacked or going
bankrupt, it also means you have to ask for permission to withdraw your ETH, wait longer to
withdraw, and generally pay higher transaction fees for withdrawals. Furthermore, by holding your
ETH on a centralized exchange, you won't be able to put it to use in the wide range
of dApps available on the Ethereum network. Cryptocurrency exchanges are best used only for
trading—not for storing or using your ETH.
126
APIs can be used to retrieve data, send data, modify data, and perform various other functions,
depending on the capabilities exposed by the API.
APIs can be found in various contexts, including Web Development, Mobile App Development,
Operating Systems, Databases, and Cloud Services. They are essential for enabling integration
between different software systems, facilitating interoperability, and promoting the development
of robust and scalable applications.
Why are APIs Important in Blockchain?
APIs are of paramount importance in the realm of blockchain technology as they serve as a
standardized gateway for applications to interact with blockchain networks. By providing a
simplified interface, APIs enable developers to access and utilize blockchain data, execute
transactions, and engage with smart contracts.
hey abstract the complex protocols and intricacies of blockchain technology, allowing
developers to focus on building innovative applications without needing an in-depth
understanding of the underlying blockchain infrastructure.
APIs promote interoperability, simplify integration efforts and provide secure and efficient
means for applications to interact with blockchain networks, ultimately driving the adoption
and widespread use of blockchain technology across various industries.
What is Ethereum API?
The Ethereum API, or Ethereum Application Programming Interface, refers to the collection of
protocols, methods and tools that allow developers to interact with the Ethereum Blockchain
network. It serves as a standardized interface that enables developers to access and utilize various
features and functionalities of the Ethereum platform.
There are two main types of Ethereum APIs:
Management APIs
Web3 APIs
Management APIs
Management APIs play a crucial role in Ethereum by empowering developers to administer and
control various aspects of the network. These APIs facilitate seamless interactions with
Ethereum nodes and offer essential functionalities for network management. Notable
Management APIs include the JSON-RPC API, which allows developers to query and
manipulate blockchain data, create transactions, and deploy smart contracts. The WebSockets
127
API provides real-time data streaming capabilities, enabling developers to receive instant
notifications about blockchain events. Additionally, The GraphQL API streamlines the process
of retrieving specific information from the blockchain, optimizing application performance and
reducing data redundancy.
1. JSON-RPC API
The JSON-RPC (Remote Procedure Call) API acts as a remote interface for developers to
interact with Ethereum nodes. It enables them to query and manipulate blockchain data by
making remote procedure calls. Developers can retrieve account balances, create transactions,
deploy smart contracts, and perform other operations through this API. JSON-RPC API allows
seamless integration with Ethereum nodes and Facilitates efficient data retrieval and
manipulation.
2. Websockets API
The Websockets API offers real-time data streaming capabilities, enabling developers to
subscribe to events on the Ethereum network. This API is particularly valuable for building
applications that require immediate updates, such as decentralized exchanges or Decentralized
Finance (DeFi) platforms. By using WebSockets, developers can receive instant notifications
about blockchain events, transaction confirmations, or contract state changes.
3. GraphQL API
The GraphQL API provides a flexible and efficient way to query and retrieve data from the
Ethereum Blockchain. It allows developers to specify the exact data they need using a query
language. By defining the required fields and relationships, Developers can minimize network
overhead and optimize data fetching. GraphQL API streamlines the process of retrieving specific
information from the blockchain, enhancing application performance and reducing data
redundancy.
Web3 APIs
Web3 APIs are tailored to meet the requirements of Decentralized Applications (DApps) that
interact with the Ethereum network. These APIs provide a comprehensive set of functionalities
for smooth integration with smart contracts, user account management, and various other
blockchain-related operations. One prominent web3 API is Web3.js, a widely adopted JavaScript
library that acts as a bridge between applications and the Ethereum network. With Web3.js,
developers can easily connect their applications to Ethereum, interact with smart contract
128
functions, and retrieve real-time information from the blockchain. Another important web3 API
is the Ethereum Contract ABI (Application Binary Interface), which defines the structure and
methods of a smart contract, facilitating seamless interaction with its functions and data.
Additionally, the Ethereum Name Service (ENS) API offers a decentralized domain name system
for Ethereum addresses, simplifying user experiences by replacing complex hexadecimal
addresses with memorable domain names.
These web3 APIs provide essential tools for building decentralized applications on the Ethereum
platform.
1. Ethereum JavaScript API (Web3.js)
Web3.js is a widely adopted JavaScript library that serves as a crucial bridge between
Applications and the Ethereum Network. It provides a comprehensive set of functions for
interacting with smart contracts, sending transactions, and retrieving blockchain data. With
Web3.js developers can easily connect their Applications to Ethereum, interact with smart
contract functions, and retrieve real-time information from the blockchain.
2. Ethereum Contract ABI (Application Binary Interface)
The Contract ABI specification defines the structure and methods of a smart contract, enabling
seamless interaction with the contract’s functions and data. It allows developers to encode and
decode function calls and data, making it easier to interact with smart contracts. By utilizing the
Contract ABI, Developers can accurately interact with smart contracts and retrieve relevant
Information from their deployed instances.
3. Ethereum Name Service (ENS) API
The ENS API offers a decentralized domain name system for Ethereum Addresses. It allows
developers to map human-readable domain names to Ethereum Addresses, simplifying the user
experience by replacing long and complex hexadecimal addresses with memorable and readable
domain names. The ENS API enables developers to associate domain names with their contracts,
wallets, or Decentralized Applications, making it easier for users to interact with the Ethereum
ecosystem.
What is Ethereum API Used for?
The Ethereum API is a versatile tool with numerous use cases in blockchain development. It is
utilized for reading blockchain data, sending transactions, interacting with smart contracts,
monitoring events, integrating cryptocurrency wallets and enabling Decentralized Finance
129
(DeFi) applications. With its capabilities, the Ethereum API plays a crucial role in enhancing the
functionality and utility of blockchain-based applications across various domains. Below are
some common scenarios where the Ethereum API is utilized:
1. Reading Blockchain Data
Ethereum API enables developers to retrieve essential blockchain data, such as account balances,
transaction history, and contract states. This information is crucial for building applications that
require real-time access to up-to-date data from the Ethereum blockchain. Developers can
leverage this data to provide users with accurate information about their accounts, transactions,
and other on-chain activities.
2. Sending Transactions
With the Ethereum API, Developers can initiate and send transactions to the Ethereum network.
This functionality is vital for applications that involve token transfers, interacting with smart
contracts, or executing other on-chain operations. Developers can programmatically create and
send transactions, allowing users to perform various actions such as sending tokens, executing
contract functions, or participating in token sales.
3. Smart Contract Interactions
Ethereum API provides methods to interact with smart contracts deployed on the Ethereum
blockchain. Developers can call contract functions, read data from contracts and even deploy
new contracts programmatically. This allows the integration of smart contract functionality into
applications, enabling the execution of complex business logic and the automation of processes
on the Ethereum network.
4. Event Monitoring
The Ethereum API allows developers to subscribe to specific events emitted by smart contracts.
This feature enables applications to listen to specific events and trigger actions based on those
events. For Example, developers can subscribe to events related to token transfers, contract state
changes, or other custom events. This real-time event monitoring capability is essential for
applications that require instant updates and automation based on on-chain events.
5. Wallet Integration
Ethereum API can be utilized to integrate cryptocurrency wallets into applications, enabling
users to manage their Ethereum accounts, sign transactions securely, and interact with
Decentralized Applications (DApps). Developers can leverage the Ethereum API to create
130
seamless user experiences by integrating wallet functionalities, such as account management,
transaction signing, and balance inquiries, directly into their applications.
6. Decentralized Finance (DeFi)
Ethereum’s API is extensively used in DeFi Applications, which encompass various financial
protocols built on the Ethereum blockchain. DeFi protocols include Decentralized Exchanges
(DEXs), lending platforms, yield farming, and liquidity mining. By utilizing the Ethereum API,
developers can integrate their applications with these DeFi protocols, allowing users to trade
assets, lend and borrow funds, participate in yield generation strategies, and engage in other
innovative financial activities.
131
Remix Plugin Manager:
Remix IDE only loads required features. The Plugin Manager is where you control which plugins
are activated. This plugin design allowed the Remix team to add technologies from other teams.
Also, Remix or elements of Remix may be merged into other projects.
Remix File Explorer:
By default, Remix IDE stores files in Workspaces which are folders in your browser’s local
storage.
Important - Clearing the browser storage will permanently delete all the files stored there.
Important - All the solidity files are stored under the ‘contracts’ folder in the current workspace.
To create a new solidity file, add a new file inside the contracts folder with .sol extension. To edit
a solidity file, click on the required .sol file.
132
Remix Solidity Compiler:
The Solidity Compiler may be accessed from the icon panel by clicking the Solidity icon. When
you click the compile button, the program compiles. If you want the file to be compiled each time
the file is saved or when another file is selected - check the auto compile checkbox.
Deploying Smart Contracts and running transactions:
Remix IDE is a convenient tool for building and testing your solidity smart contracts online. This
short tutorial will explain how we can build and deploy our smart contract from Remix.
// SPDX-License-Identifier: GPL-3.0
Above we have a simple Destructor contract which was built and tested using the online Remix
IDE. To deploy this contract select the Deploy & Run Transactions tab; select injected Web3` as
your environment. This will connect to the network that your wallet is connected to.
133
Set the input value of the constructor function if your contract has one before deploying it. Clicking
on deploy will open Metamask which will ask you to confirm the transaction. After confirming
the transaction, the contract will be deployed to the network.
The Remix IDE interface. It is divided into different panels like File Explorer, Editor, Terminal,
etc.
Remix IDE Basic Overview
After navigating to the Remix home page and getting able to access your Remix IDE, you will
shown a lot of buttons and features presented by the Remix IDE. Some of them are,
1. File Explorer: This section displays all the folders and files present in the IDE. It is possible
to create new folders and files using the Add button provided in the interface. It also allows
us to Publish all files to GitHub along with uploading files and folders from your personal
computer to the IDE.
2. Editor: It is the area that allows us to write and update or edit our smart contract according
to our needs. It is the black area that is displayed when we create a new file. To open up the
editor area, create a new file and add the .sol extension at the end of its name. The editor
comes with added features like code highlighting, auto-completion of code, and error
highlighting, which makes writing smart contracts more easy and fun.
134
3. Compiler: It is the section where the compiler version and compiler-related information are
present, which helps us to compile our solidity code successfully, which can be afterward
deployed to any mainnet or any testnet. You will find the solidity compiler in the left
navigation pane of the IDLE.
4. Deploy & Run: This section is found just below the solidity compiler, and it helps to deploy
the smart contract to various test nets and main nets after a successful compilation. Remix
also has its testing network where we can test our smart contracts as much as we want without
jeopardizing our real money.
Creating your First Smart Contract
Now after getting familiarized with the Remix IDE, it's time to create and write our very own first
smart contract. In this tutorial, we will be creating a simple "Hello World" smart contract where
we will be creating a function to print the message. This tutorial will help you understand how
smart contracts are created, compiled, and deployed on Remix. Using this knowledge, you will be
able to deploy any type of contract using Remix.
Opening a new file
On the file explorer panel on the left, click on the contracts folder. Now to create a new file inside
the contracts folder, click on the Create New File button. Name the file with something
like Greetings.sol.
135
Writing your smart contract code
After you create a file, you will get to see the editor panel. Inside the editor's panel start writing the
basic structure of the smart contract along with its state variables and functions. Here you can use
the below code to work on.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0; // Version of the Solidity compiler this code will use
// Contract definition
contract Greetings{
// State variable
string greeting;
// Constructor
constructor() {
greeting = "Hello, World!";
}
// Function to get the greeting
function getGreeting() public view returns (string memory) {
return greeting;
}
}
Explanation
This is a basic smart contract where we have used a single state variable and a function to retrieve
the value of that variable. Let's break down the code for more simpler understanding.
SPDX-License-Identifier: It defines the license version that is used for the contract. Since
all the contract codes are open source, it is advisable to have a license version. This prevents
legal complications regarding copyright.
pragma solidity ^0.8.0: This sets the version of the solidity compiler that is to be used in
the smart contract. This line tells the solidity compiler to use solidity version 0.8.0 or greater
to compile the above solidity code.
contract Greetings {...}: This is where the contract code is defined. Just as class is used in
Java programming, we use contract in solidity programming.
136
string greeting: This is how a variable is declared in solidity. In solidity, the variables are
called state variables as they decide the state of the contract. In the above code, the greeting
variable is used to store the greeting message.
constructor() {...}: This is a special function that runs once during the time of contract
deployment. We are setting a value to the greeting variable inside this constructor for the
above code.
function getGreeting(): This is a function that can be called by anyone to get the greeting
message.
Compiling your Smart Contract
After creating your smart contract, the next step is to compile the smart contract. Compilation is
the process of translating your Solidity code into machine-readable bytecode that can be executed
on the blockchain. Remix IDE makes this process simple. Here's how to do it.
Open the Solidity Compiler
In Remix IDE, you'll find the "Solidity Compiler" tab on the right sidebar. Click on it to open the
compiler panel.
Select Compiler Version
At the top of the compiler panel, you'll see a dropdown menu. This allows you to choose the
version of the Solidity compiler you want to use. If you're not sure, select the latest stable version.
Compile Your Contract
In the compiler panel, you'll see a button labeled "Compile Greetings.sol" (or whatever you named
your file). Click on it.
Review Compiler Output
Below the button, you'll see the compilation output. If your code has no errors, you'll see a green
checkmark with "Compilation successful". If there are any errors, they will be listed with line
numbers.
Explore Compiled Artifacts
If your contract compiles successfully, Remix IDE will generate a set of compiled artifacts. These
include the bytecode (which gets deployed to the blockchain) and the Application Binary Interface
(ABI), which defines how to interact with the contract.
137
Debugging Compiler Errors (if any)
If there are errors during compilation, review the error messages to identify what needs to be fixed.
Common issues include syntax errors, incorrect data types, or missing semicolons.
That's it. Our smart contract is now compiled and ready to be deployed.
138
Selecting a network
Before deploying, decide which blockchain network you want to use. For beginners, starting with
a testnet is recommended. This allows us to deploy and test our contract without using real
cryptocurrency. There are many testnet available. You can select one of the available test networks
and add it to your wallet, like Metamask. After adding the testnet to your wallet, you can get some
faucets to it. These faucets will be required during the deployment of the smart contract.
Connecting Remix IDE to a Network
In the Remix IDE, navigate to deploy and run transaction panel, and there, choose the network on
which you want to deploy the smart contract.
Here you will able to select the network environment as well as the account address and its balance
in ether. By default, the environment selected by the Remix IDE is its own test environment. Remix
IDE provides the user with its own test environment to test the smart contract before deploying it
to the main network. But when deployed on the Remix test environment, the smart contract is not
visible outside the Remix Ide. You will not be able to see the contract outside the Remix
environment.
139
To prevent this, we can deploy the smart contract on a publically available testnet like the Polygon
Mumbai testnet, Goerli Testnet, or any other testnet. All we need to do is connect to the wallet on
which we have connected with these networks.
For example, to connect to Metamask, we can select Injected Provider - MetaMask. By
selecting this, it will try to connect to your metamask wallet. Allow the connection, and you are
ready to deploy on your desired network.
Deploying your Contract
It's time to deploy the smart contract. You will find the latest successfully compiled contract on
the contract tab, ready to be deployed. Once you have selected the environment to which the
contract is to be deployed. Click the Deploy button. This will open up your metamask transaction
builder if you are using any other network rather than the default environment provided by the
Remix. Sign the transaction, and the Remix IDE will do the rest of the work automatically.
Please remember that for signing a transaction, you should have some faucet in your account if
you are using a testnet.
After the transaction is successful, you can see it on the block explorer using its transaction hash.
Interacting with the smart contract
Once the smart contract is deployed, its functions are ready to be used and interacted with. Once
the smart contract is successfully deployed, you will be able to interact with its function in the
deploy and run transaction panel. The deployed contract will be visible under the Deployed
Contracts panel.
Expand the deployed contract view to see all the functions available inside it. In this tutorial, the
Greetings contract has only one function getGreeting, which you can see in the picture above.
140
To call the function, click on the button with the function name. In the above example, when we
click on the getGreeting function button, the message Hello World is reflected on the screen.
141
Ethereum network and build decentralized applications using the Go programming
language.
Applications of Ethereum Go include building decentralized applications, interacting
with smart contracts, and deploying and managing Ethereum nodes. The Ethereum
network has a wide range of use cases, including decentralized finance (DeFi), non-
fungible tokens (NFTs), and supply chain management.
Key features and functionalities of geth:
Node Management: Geth provides the ability to run an Ethereum node on your local
machine. By running a node, you can participate in the Ethereum network, synchronize with
the blockchain, and contribute to network consensus.
Account Management: With geth, you can create Ethereum accounts to send and receive
Ether (the native cryptocurrency of Ethereum) and interact with smart contracts. It allows
you to manage multiple accounts, import existing accounts, and securely store your account
information.
Blockchain Interaction: Geth enables users to interact with the Ethereum blockchain. You
can query blockchain data, retrieve transaction information, and explore block details using
the CLI commands. This functionality is valuable for developers and researchers who need
to access on-chain data.
Smart Contract Deployment and Interaction: Geth allows you to deploy and interact with
smart contracts on the Ethereum network. You can compile and deploy your own smart
contracts using Solidity (the most widely used smart contract programming language for
Ethereum) and interact with them through the CLI.
Network Configuration: Geth offers various configuration options to customize your
Ethereum node’s behavior. You can specify network parameters, set up mining operations,
define peer connections, and configure security features to suit your requirements.
Development and Testing: Geth provides developer-friendly features for testing and local
development. It includes features like private chains, test networks, and mining simulation,
allowing developers to experiment and test their DApps and smart contracts in a controlled
environment.
142
geth Command Examples
1. Connect to the main Ethereum network and automatically download the full node:
# geth
2. Connect to the Ropsten test network:
# geth --testnet
3. Create a new account:
# geth account new
4. Enable mining:
# geth --mine
143
Creating an Ethereum Wallet with Go-Ethereum:
Step 1: We begin by importing all the important packages:
import (
“context”
“fmt”
“log”
“github.com/ethereum/go-ethereum”
“github.com/ethereum/go-ethereum/accounts”
“github.com/ethereum/go-ethereum/common”
“github.com/ethereum/go-ethereum/crypto”
“github.com/ethereum/go-ethereum/ethclient”
)
Step 2: Generate a new Ethereum account by creating a new private key and deriving the
corresponding public key and address. In this code, we generate a new private key using
crypto.GenerateKey() function. If there’s an error, the program exits with a fatal error log
message.
privateKey, err := crypto.GenerateKey()
if err != nil {
log.Fatal(err)
}
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
log.Fatal("Error casting public key to ECDSA")
}
address := crypto.PubkeyToAddress(*publicKeyECDSA)
Step 3: Print the newly created Ethereum address:
fmt.Println(“New Wallet Address:”, address.Hex())
Making Ethereum Transactions in Go using Go-Ethereum:
Step 1: Import the following required packages to do this.
import (
“context”
“log”
“github.com/ethereum/go-ethereum/ethclient”
)
Step 2: We will create a new transaction by specifying the recipient address, value, gas price,
gas limit, and nonce in the go code. Also, replace YOUR_PRIVATE_KEY with the private key
of the account making the transaction and 0xRECIPIENT_ADDRESS with the recipient’s
Ethereum address.
Step 3: Sign the transaction using the private key by replacing chainID with the appropriate
chain ID and send it to the Ethereum network.
144
//Sing the transaction
signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey)
if err != nil {
log.Fatal(err)
}
References:
https://www.leewayhertz.com/ethereum-smart-contract-tutorial/
https://moralis.io/what-is-an-ethereum-node-and-how-to-set-one-up/
https://www.doubloin.com/learn/types-of-ethereum-nodes
https://www.coindesk.com/learn/ethereum-nodes-and-clients-a-complete-guide/
https://ethereum-tests.readthedocs.io/en/latest/state-transition-tutorial.html
https://www.ledger.com/academy/topics/crypto/what-is-an-ethereum-wallet-and-how-
does-it-work
https://ethereum.org/en/developers/docs/gas/
https://ethereum-tests.readthedocs.io/en/latest/state-transition-tutorial.html
https://ethereum-tests.readthedocs.io/en/latest/test_filler/blockchain_filler.html#test-
structure
https://ethereum-tests.readthedocs.io/en/latest/test_filler/eof_filler.html#test-structure
https://ethereum-tests.readthedocs.io/en/latest/state-transition-tutorial.html
145