Solidity Beginner To Advanced Guides

Download as pdf or txt
Download as pdf or txt
You are on page 1of 787

2/12/23, 3:14 PM Learn Solidity lesson 3. The compiler.

| by João Paulo Morais | Coinmonks | Medium

Published in Coinmonks

João Paulo Morais Follow

Jul 18, 2022 · 5 min read · Listen

Save

Learn Solidity lesson 3. The compiler.

When a contract is saved in Remix, it is automatically compiled. In this section, we will


see how the compilation takes place and its result. First, let’s see about the Solidity
compiler and how to use it.

Solc

https://medium.com/coinmonks/learn-solidity-lesson-3-the-compiler-a9a6b8da1e70 1/8
2/12/23, 3:14 PM Learn Solidity lesson 3. The compiler. | by João Paulo Morais | Coinmonks | Medium

The Solidity compiler is named solc, it is written mostly in C++ and is currently at
version 0.8.15. The source code can be found at github.com/ethereum/solidity. There is
a wrapper written in JavaScript (TypeScript to be more precise) that can be installed
via npm (or yarn), named solc-js. Let’s use solc-js, which is easier to install and use.

To show the use of solc, let’s temporarily step away from Remix. Using any text editor
of your choice, paste the contract you wrote and save the file as HelloWorld.sol. I’m
using VS Code, as can be seen in the image bellow.

HelloWorld.sol

Let’s run solc to compile the contract. For this, we will use npx, which run node
packages without installing then. Npx is installed together with node.js, and if you
don’t have it installed on your computer, please go to nodejs.dev and follow the
instructions.

To compile the contract, i.e., to generate its bytecode, run the following command line
in your shell. I’m using the Windows command prompt.

npx solc --bin HelloWorld.sol

Solc accepts several parameters, but we will restrict ourselves to what is strictly
necessary. It is necessary to indicate whether we want to generate the bytecode or the
ABI of the contract, using the options — bin or — abi. We use — bin to generate the
bytecode, which is the EVM machine code.

https://medium.com/coinmonks/learn-solidity-lesson-3-the-compiler-a9a6b8da1e70 2/8
2/12/23, 3:14 PM Learn Solidity lesson 3. The compiler. | by João Paulo Morais | Coinmonks | Medium

In figure bellow, we see that the compiler warns us about the lack of a license
declaration, just like Remix. Just a warning does not prevent the compiler from
compiling, generating a file named HelloWorld_sol_HelloWorld.bin.

Generating the bytecode using solc.

The .bin file contains the bytecode that must be sent to the blockchain in a transaction.
It is a binary code, but in hexadecimal base, therefore it can contain numbers and
letters between ‘a’ and ‘f’. We can see this in the image bellow.

The bytecode of HelloWorld.sol.

The other option, to generate the ABI, will be explained later. Now let’s see where we
can find the bytecode using Remix. In the tab named Solidity Compiler, at the bottom of
the screen, notice the presence of two buttons: ABI and Bytecode. See the image
bellow.

https://medium.com/coinmonks/learn-solidity-lesson-3-the-compiler-a9a6b8da1e70 3/8
2/12/23, 3:14 PM Learn Solidity lesson 3. The compiler. | by João Paulo Morais | Coinmonks | Medium

Bytecode and ABI in Remix.

You can click Bytecode to copy the content generated by Remix, and paste it into a text
file. You may notice, however, that it is not just a hexadecimal number, but a JSON file.
The real bytecode is found almost at the end of the JSON, in a property named object, as
one can see in the figure bellow.

The ‘Bytecode’ generated by Remix is a JSON file.

This question may seem confusing at first, but let’s be clear: the bytecode is a large
hexadecimal number, which is EVM machine code. Remix also displays the opcodes,
which is the assembly code translated from the bytecode. While it is interesting to see
the opcodes generated by the contract, they are not required for publication. To
publish a contract is to send the bytecode to the blockchain in a transaction.

This is exactly what we do when we use the deploy option in Remix. It writes us a
transaction where the transaction data includes the bytecode, and this transaction is

https://medium.com/coinmonks/learn-solidity-lesson-3-the-compiler-a9a6b8da1e70 4/8
2/12/23, 3:14 PM Learn Solidity lesson 3. The compiler. | by João Paulo Morais | Coinmonks | Medium

sent to a node in the network. In the case of Remix’s own test local network, the node
is Remix itself.

New to trading? Try crypto trading bots or copy trading

Artifacts
Artifacts are by-products that help describe the architecture of a software. When we
build a smart contract in Remix, it generates an artifact, saved in a folder named
contracts/artifacts/build-info. This can be seen in the figure bellow.

Artifacts generated by Remix.

Two files were generated: HelloWorld_metadata.json and HelloWorld.json. Both contain


information not only about the contract, but also about the compiler. The same
contract, compiled by different versions of solc, can generate different bytecodes, so it
is necessary to know which version of the compiler was used.

Other development environments for Solidity, such as Truffle and HardHat, also
generate their own artifacts. They are not necessarily the same, but they all contain
both the bytecode and the ABI. They are the information needed to publish and
interact with the contract.

https://medium.com/coinmonks/learn-solidity-lesson-3-the-compiler-a9a6b8da1e70 5/8
2/12/23, 3:14 PM Learn Solidity lesson 3. The compiler. | by João Paulo Morais | Coinmonks | Medium

An issue that we should call attention is that Remix (and also the other IDEs) usually
generate two bytecodes. Remix calls them Bytecode and ‘Deployed Bytecode’. Although
they are related, they are not the same.

The bytecode is the code that is sent in the transaction to the network, when the
contract is created. The deployed bytecode (other IDEs use a different nomenclature) is
the code that is actually written to the blockchain.

The difference between them is that the code that is sent to the blockchain contains, in
addition to the code that will be saved, an initial code, which will be executed at the
time of deployment. After executed, the initial code is discarded.

The bytecode will always be larger than the deployed bytecode, and will contain it. We
can see this in figure bellow. I copied, on notepad, both bytecodes. Above, we have the
bytecode, and separated by a blank line, the deployed bytecode. In blue, the part of the
bytecode that is exactly the same as the deployed bytecode is marked. The initial part
of the bytecode, which is not marked in blue, will be executed at the time of
deploynment and then discarded.

The bytecode and the deployed Bytecode.

https://medium.com/coinmonks/learn-solidity-lesson-3-the-compiler-a9a6b8da1e70 6/8
2/12/23, 3:14 PM Learn Solidity lesson 3. The compiler. | by João Paulo Morais | Coinmonks | Medium

Thanks for reading!

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also, Read
OKEx vs KuCoin | Celsius Alternatives | How to Buy VeChain

ProfitFarmers Review | How to use Cornix Trading Bot

How to buy Bitcoin Anonymously | Bitcoin Cash Wallets

WazirX NFT Review | Bitsgap vs Pionex | Tangem Review

How to Create a DApp on Ethereum using Solidity?

Solidity Ethereum Blockchain

Enjoy the read? Reward the writer.Beta


Your tip will go to João Paulo Morais through a third-party platform of their choice, letting them know you appreciate
their story.

Give a tip

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

O i Si Si I
https://medium.com/coinmonks/learn-solidity-lesson-3-the-compiler-a9a6b8da1e70 7/8
2/12/23, 3:14 PM Learn Solidity lesson 3. The compiler. | by João Paulo Morais | Coinmonks | Medium
Open in app Sign up Sign In
Your email

Search Medium
Get this newsletter

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

About Help Terms Privacy

Get the Medium app

https://medium.com/coinmonks/learn-solidity-lesson-3-the-compiler-a9a6b8da1e70 8/8
2/12/23, 3:17 PM Solidity Code Compilation. Web3.JS web3.eth.compile.solidity… | by 林瑋宸 Albert Lin | Coinmonks | Medium

Published in Coinmonks

林瑋宸 Albert Lin Follow

May 20, 2018 · 2 min read · Listen

Save

Solidity Code Compilation


Web3.JS web3.eth.compile.solidity alternatives

source

Before deploy smart contract, we need to compile solidity code to Bytecode for
EVM(Ethereum Virtual Machine). You got two stuff after compiling solidity code:

https://medium.com/coinmonks/solidity-code-compilation-334dc3b3784e 1/4
2/12/23, 3:17 PM Solidity Code Compilation. Web3.JS web3.eth.compile.solidity… | by 林瑋宸 Albert Lin | Coinmonks | Medium

Bytecode/EVM code

ABI(Application Binary Interface)

Bytecode is code EVM execute in blockchain network. ABI defines the actions you
interact with smart contract. The actions in ABI mean the functions of smart contract.

Bad New
Geth does not support compile solidity code feature (web3.eth.compile.solidity()) since
1.5.9 version above.if you use web3.eth.compile.solidity() in Geth 1.5.9 version above,
you will get the error exception. Metamask and TestRPC are also not support compile
solidity code.

Alternatives
Here are two ways to solve this problems. The first direct compile solidity code
inlocalhost by using Solc(Solidity compiler). it is easy to install Solc in localhost. If your
system is ubuntu, you can use apt-get to install Solc. You can reference here if yours is
other system.

sudo add-apt-repository ppa:ethereum/ethereum


sudo apt-get update
sudo apt-get install solc

You can compile solidity code after installing Solc.

solc [options] [input file …]


solc — bin sample.sol > sample.bin
solc — abi sample.sol > sample.abi
solc — combined-json abi,bin sample.sol > sample.json

Browser Solc
The second way is browser-solc. you can use browser-solc to compile solidity code
online. browser-solc is like online solc. I write a simple Online Solc website by using
browser-solc here. You can see how it work if you interested. You can put you solidity
https://medium.com/coinmonks/solidity-code-compilation-334dc3b3784e 2/4
2/12/23, 3:17 PM Solidity Code Compilation. Web3.JS web3.eth.compile.solidity… | by 林瑋宸 Albert Lin | Coinmonks | Medium

code into left column and pick the solc version you want to compile.You can see the
Bytecode and ABI after enter Compile Code button. source code is here.

Reference:
[1] https://www.udemy.com/ethereum-dapp/
[2] https://github.com/ericxtang/browser-solc
[3] https://github.com/ksin751119/OnlineSolCompiler.git
Open in app Sign up Sign In
[4] https://solidity.readthedocs.io/en/latest/installing-solidity.html
Search Medium

Ethereum Solidity Web 3 Tutorial Solidity Tutorial

Sign up for Coinmonks


https://medium.com/coinmonks/solidity-code-compilation-334dc3b3784e 3/4
2/12/23, 3:17 PM Solidity Code Compilation. Web3.JS web3.eth.compile.solidity… | by 林瑋宸 Albert Lin | Coinmonks | Medium

By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Your email

Get this newsletter

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

About Help Terms Privacy

Get the Medium app

https://medium.com/coinmonks/solidity-code-compilation-334dc3b3784e 4/4
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Published in Coinmonks

Hemant Juyal Follow

Jun 10, 2022 · 7 min read · Listen

Save

Creating and Deploying a Solidity Smart


Contract on a Blockchain

If you are in the world of Blockchain and Cryptocurrencies then you would have heard
about Smart Contract and If you haven’t then it’s ok as I will cover in an easy way what
is a Smart Contract and how to create one and deploy it on a blockchain.

But as a First step you have to be in sync with me like this ;-)

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 1/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Building Smart Contract: First Step

For newbies,

A blockchain is a (form) of distributed ledger having growing list of blocks (or records) which
are linked together cryptographically.

In simple words we can describe a Smart Contract as a computer code that comprises a set of
rules and executes on a blockchain.

Smart Contract: A typical Tenancy Agreement

Let’s understand it in a better way with the an example. In our real world the way we
have a printed Tenancy Agreement or Tenancy Contract that comprises of all the
agreement clauses and have to be adhered by both the signing parties. In blockchain
world we can have the same Tenancy Contract in its pure digital form through a Smart
Contract. While stating pure digital form means in form of a computer program or
code where this computer code inherently holds the programmatic representation of
all the Tenancy Contract clauses agreed by the involved parties and the super
interesting part is no one can alter this contract not even the involved signing parties.

It can be Illustrated as

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 2/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Smart Contract: A typical Tenant Agreement / Contract flow

Smart Contract: A typical Smart Contract flow on Blockchain

Now we have good understanding about Smart Contract lets move to some real stuff
i.e. How to create a smart contract and get it deployed. As I have mentioned it’s a
computer program that automatically executes so we will use some coding and
leverage some tools to build and deploy our Smart Contract.

We will be using Solidity, Hardhat, Alchemy and Metamask. Don’t worry we will know
about these as we move forward.

For newbies

Solidity: Solidity is an object-oriented programming language for implementing smart


contracts on blockchain platforms. It’s influenced by C++, JavaScript and Python.

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 3/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Hardhat: Hardhat is a development environment to compile, deploy, test, and debug


Ethereum based softwares.

Alchemy: Alchemy develops and markets tools and infrastructure services for blockchain
companies. Alchemy has wide range of products that provides a powerful blockchain
developer platform providing a suite of developer tools.

Metamask: MetaMask is a crypto wallet that allows users to store and swap Ether and other
Ether-related tokens.

Let’s quickly setup these on our machine / system to develop and deploy our Smart
Contract. Lets do it

Installing Metamask
Go to MetaMask and install MetaMask for your browser (through available browser
extensions) and follow the mentioned easy steps to create your MetaMask wallet
Account.

For newbies, MetaMask is a crypto wallet that allows users to store and swap Ether and other
Ether-related tokens.

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 4/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Smart Contract: Install MetaMask for your browser: Go to MetaMask Download page

Setting up MetaMask
After creating our wallet we will set-it up by adding ether from a faucet as to deploy
our smart contract to the test network, we’ll need some fake ETH. Why because to
deploy and execute a code on Blockchain require a Gas Fee that typically gets paid
using cryptocurrencies and tokens. In our case we will paying the Gas fee using ETH.

Follow the below steps into your MetaMask Wallet

1. Change the Network to Goerli Test Network

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 5/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Smart Contract: Step1 MetaMask Wallet set-up

2. Go to Goreli Faucet and enter your MetaMask wallet address and send some test Eth

Smart Contract: Step2 send test eth to you MetaMask Wallet

After sending test Eth your MetaMask wallet should start reflecting the updated
amount.

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 6/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Smart Contract: MetaMask wallet with test Eth

Using Alchemy
To run our Smart Contract we will use Alchemy through which we will be able to
communicate with Ethereum chain and has developer tools for analytics and
monitoring. Use sign-up to create free account

Smart Contract: Create app on Alchemy

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 7/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Once you are done with the sign-up process then create an app by selecting giving app
name something like ‘SmartContract-GreetingsMessage’ and Chain as Ethereum and
Network as Goreli

You can view the API keys from the view section once the app is created. Keep it handy
as we will be using it in doing our Smart Contract configuration.

Smart Contract: View API key on Alchemy

Smart Contract Project Setup


Check out the greetings smart-contract project code from Github into your local
directory. You will see following project structure. Don’t worry I will explain the
important files.

Note: If you have Github installed on your local machine then follow the official installer
page and install it on your system

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 8/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Smart Contract: Github project set-up

We will use node and CLI terminal to execute our commands. Install LTS version of
node if you haven’t installed it already on your machine.

For newbies, Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine and LTS
release status is “long-term support”, which typically guarantees that critical bugs will be
fixed for a total of 30 months.

Run the following command from the root folder of the project and it will install all the
project dependencies

npm install

The contract folder has a file GreetingMessages.sol which is a Solidity file and has the
set of logic. It’s a simple Smart Contract that will be initialised with a default greeting
https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 9/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

message and has an update function to update the messages.

1 // SPDX-License-Identifier: GPL-3.0
2
3 pragma solidity >=0.7.3;
4
5 // Defines a contract named `GreetingMessages`.
6 contract GreetingMessages {
7 //Emitted when update function is called
8 event UpdatedMessages(string oldStr, string newStr);
9 // Declares a state variable `message` of type `string`.
10
11 string public message;
12 constructor(string memory initMessage) {
13 message = initMessage;
14 }
15
16 // A public function that accepts a string argument and updates the `message` storage variable.
17 function update(string memory newMessage) public {
18 string memory oldMsg = message;
19 message = newMessage;
20 emit UpdatedMessages(oldMsg, newMessage);
21 }
22 }

GreetingMessages.sol hosted with ❤ by GitHub view raw

Smart Contract: GreetingMessages .sol smart contract

.env Configuration
Within the Github cloned project root folder, create a new file and name it as ‘.env’
which will be having our env configuration parameters that will be required. Enter the
relevant details

#.env file configuration for deploying our Smart Contract


API_URL = Copy HTTP value from your Alchemy app key details section
API_KEY = Copy API_KEY value from your Alchemy app key details section

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 10/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

PRIVATE_KEY = Your MetaMask wallet private key

Smart Contract: View API key and HTTP configuration on Alchemy

Refer to How to export your MetaMask account’s private key to follow the steps and to
get the value of `PRIVATE_KEY` configuration

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 11/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Smart Contract: Export you MetaMask wallet private keys

Fully configured .env file will look something like this

1 #.env file configuration for deploying our Smart Contract


2
3 API_URL = "https://eth-goerli.alchemyapi.io/v2/NNSC4vzqU_.......vIDTEU"
4 API_KEY = "NNSC4vzqU_.......vIDTEU"
5 PRIVATE_KEY = "8b4640dac7c...........................c6e77ea68bc7d7"

.env hosted with ❤ by GitHub view raw

Smart Contract: .env file configuration

Deploy your Smart Contract


Run the following command from project root folder to compile our solidity code

npx hardhat compile

If all the node packages are installed properly as per the previous steps, then you will
received success message stating something like “Compiled 1 Solidity file successfully”

To deploy the compile code, navigate to scripts/deploy.js and you will find the code
as

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 12/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

1 async function main() {


2 const GreetingMessages = await ethers.getContractFactory("GreetingMessages");
3
4 //Start deployment, returning a promise that resolves to a contract object
5 const greeting_messages = await GreetingMessages.deploy("Hello and Welcome");
6 console.log("Contract deployed to address:", greeting_messages.address);
7 }
8
9 main()
10 .then(() => process.exit(0))
11 .catch(error => {
12 console.error(error);
13 process.exit(1);
14 });

deploy.js hosted with ❤ by GitHub view raw

A ContractFactory in ethers.js is an abstraction used to deploy new smart contracts, so


GreetingMessages here is a factory for instances of our GreetingMessages contract.
Calling deploy on a ContractFactory will start the deployment.

Run the command to execute the deployment process

npx hardhat run scripts/deploy.js

On successful deployment you will receive message as ‘Contract deployed to address:


0xeD0B03aD1C49……’

Note: I have mentioned the partial address that I have received during my command
execution on CLI terminal. Your local code execution will give you a different address
as per your configuration. So make a note of this

Deployed Smart Contract Validation


Above command output shows that deployed on the Blockchain successfully. Copy this
address and save it to a file as we will be referring to it in other scenarios that will be
covered in the next stage. To validate the deployed Smart Contract, go to Goreli Testnet

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 13/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Explorer and enter your contract address. You will find the GreetingMessages contract
creation entry as part of the contract details thus our deployed contract is validated.

Smart Contract: Deployed contract details

Congratulations!!! we have deployed our smart contract successfully. Time for some
celebration ;-)

Smart Contract: Deployment successful and now it’s time for celebration

Images Credit: Paramount Pictures and Leonardo DiCaprio

Glossary:

Gas: Gas is a unit of account within the EVM used in the calculation of a transaction fee,
which is the amount of ETH a transaction’s sender must pay to the miner who includes the
transaction in the blockchain. From Wikipedia

NFT: NFTs or Non-fungible tokens typically contain references to digital files such as photos,
videos, and audio. From Wikipedia

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 14/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Other recommended articles

How to Create and Sell your NFT on OpenSea in Real without Gas Fee
in 10 mins
Trust me … I will make it very simple and straightforward …. it’s very easy
to create your NFT and sell it in real…
medium.com/@hemantjuyal

How I did my First Crypto Mining Successfully


For successful Cryptocurrency mining, follow the steps. Step1 is to
Install Monero Wallet. Step2 is to Install XMRig…
medium.com/@hemantjuyal

Interacting with your Deployed Smart Contract on Blockchain using


Hardhat
We will learn how to interact with our deployed Solidity Smart Contract
using Hardhat, MetaMask and Alchemy
medium.com/@hemantjuyal

Publish and Verify your Smart Contract for it’s Authenticity on


Etherscan
We will learn how to verify our deployed solidity Smart Contract on
Etherscan for its Authenticity.
medium.com/@hemantjuyal

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 15/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also, Read
Huobi Review | OKEx Margin Trading | Futures Trading

Grid Trading Bots | Cryptohopper Review | Bexplus Review

7 Best Zero Fee Crypto Exchange Platforms


Open in app Sign up Sign In

Anny Trade Review | Huobi Margin Trading


Search Medium
Decentralized Exchanges | Bitbns FIP | Pionex Review

Smart Contracts Alchemy Metamask Solidity Blockchain

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Your email

Get this newsletter

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 16/17
2/12/23, 3:34 PM Creating and Deploying a Solidity Smart Contract on a Blockchain | by Hemant Juyal | Coinmonks | Medium

About Help Terms Privacy

Get the Medium app

https://medium.com/coinmonks/creating-and-deploying-a-smart-contract-on-a-blockchain-c97e9edcc065 17/17
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

Published in Upstate Interactive

Kseniya Lifanova Follow

Mar 13, 2019 · 7 min read · Listen

Save

Creating a contract with a smart contract

There are two ways a contract can be created in Solidity.

1. They can be created “from outside” by a creator — a developer who is deploying the
contract or a user that is interacting with a dApp which deploys the contract on
their behalf.

2. They can also be created by another smart contract.

Today I’m going to focus on #2.

There are a lot of great articles out there about using a factory to create smart
contracts. These articles focus on creating multiple instances of the same contract. In
my case, I needed a very simple factory. A parent contract that would deploy one

https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 1/11
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

instance of a child contract. Just once. We don’t want twins, triplets, quadruplets… that
is more then we can handle.

Whether you want to create many instances of the same contract or you only want to
create one, you can use the new keyword as described briefly here in the Solidity docs.
In my case, I decided to have my parent contract create the child contract in it’s
constructor. That way it would all happen at once on deployment.

A family example
Let’s take a look at an example.

In this example, we are going to have our parent contract that we will call MomContract

deploy a child contract called DaughterContract.

:)

pragma solidity ^0.5.0;


import "./DaughterContract.sol";
contract MomContract {
string public name;
uint public age;
DaughterContract public daughter;
constructor(
string memory _momsName,
uint _momsAge,
string memory _daughtersName,
uint _daughtersAge
)
public
{
daughter = new DaughterContract(_daughtersName, _daughtersAge);
name = _momsName;
age = _momsAge;
}
}

We are starting with the MomContract and creating the DaughterContract using the new

keyword. We pass the parameters needed to create the DaughterContract to the


https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 2/11
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

MomContract so we can pass them on. We have a variable daughter of type


DaughterContract , which will allow us to call that contract.

Now let’s take a look at the DaughterContract.

pragma solidity ^0.5.0;


contract DaughterContract {
string public name;
uint public age;
constructor(
string memory _daughtersName,
uint _daughtersAge
)
public
{
name = _daughtersName;
age = _daughtersAge;
}
}

The name and age that is passed from the MomContract is used to create the
DaughterContract , and we set those arguments to the name and age variable.

Now we know how a contract can create another contract. Great.

Let’s take it a step further.

Creating a contract from another contract is particularly useful when you want to
restrict access of the child contract functions to it’s parent contract. To do this, I
recommend using Open Zeppelin’s library. They have several ways you can control
access, as written in this guide. I’m going to use the well known and popular
Ownable.sol file, which is perfect when you only need to provide access to one address.
To use the Ownable.sol file, you’ll need to import it and inherit it in your child contract.

pragma solidity ^0.5.0;


import "openzeppelin-solidity/contracts/ownership/Ownable.sol";

https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 3/11
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

contract DaughterContract is Ownable {


// contract code
}

Let’s add a function that is restricted to the MomContract .

pragma solidity ^0.5.0;


import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./MomContract.sol";
contract DaughterContract is Ownable {

string public name;


uint public age;
bool public canDate;
constructor(
string memory _daughtersName,
uint _daughtersAge
)
public
{
name = _daughtersName;
age = _daughtersAge;
canDate = false;
}
}
function permissionToDate() onlyOwner {
canDate = true;
}

We added a canDate variable and set it false (we don’t want the daughter to date without
her mom’s permission). Next, we added a permissionToDate function and added the
onlyOwner modifier available to us from the Ownable contract. Now, the only contract
that can call this function is the MomContract . To test this, I added a function in the
MomContract that calls the permissionToDate function in the DaughterContract .

function allowDaughterToDate() public {


daughter.permissionToDate();
}

https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 4/11
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

Now, when you call the allowDaughterToDate function in the MomContract , it will call the
permissionToDate function and update the canDate variable to true. If you try to call the
permissionToDate function from any other contract or address, the function will revert.
Yay!

Now, let’s say we want our MomContract to create another contract and we want that
contract to access functions in the MomContract and the DaughterContract. This scenario
is possible!

We will call our second child contract SonContract (of course).

We will import it into MomContract , pass additional parameters, and use new to create
it. Along with the name and age variables, we are going to pass it the instance of the
DaughterContract that we created right before creating the SonContract and we are
going to pass it address(this) . address(this) is the address of the contract itself. Yes,
you can access the address of the contract you are creating in it’s constructor. You won’t
be able to access its functions because the contract has not finished initializing, but
you can at least pass around its address (look here).

pragma solidity ^0.5.0;


import "./DaughterContract.sol";
import "./SonContract.sol";
contract MomContract {
string public name;
uint public age;
DaughterContract public daughter;
SonContract public son;
constructor(
string memory _momsName,
uint _momsAge,
string memory _daughtersName,
uint _daughtersAge,
string memory _sonsName,
uint _sonsAge

https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 5/11
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

)
public
{
daughter = new DaughterContract(_daughtersName, _daughtersAge);
son = new SonContract(_sonsName, _sonsAge, daughter,
address(this));
name = _momsName;
age = _momsAge;
}
}

Now, let’s take a look at the SonContract.

pragma solidity ^0.5.0;


import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./MomContract.sol";
import "./DaughterContract.sol";
contract SonContract is Ownable {

string public name;


uint public age;
DaughterContract public daughter;
MomContract public mom;
constructor(
string memory _sonsName,
uint _sonsAge
DaughterContract _daughter,
address _mom
)
public
{
name = _sonsName;
age = _sonsAge;
daughter = _daughter;
mom = MomContract(_mom);
}
}

Because we are passing the instance of DaughterContract , we can simply set our
daughter variable to the _daughter that is being passed in the constructor. Because we
are passing the address of the MomContract rather than the instance itself, we need to
set it using MomContract(_mom) .

https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 6/11
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

Now, the MomContract can access functions in the SonContract and the SonContract can
access functions in the MomContract and the DaughterContract . Let’s see an example of
this. Add these three functions to the SonContract :

function permissionToDate() public onlyOwner {


canDate = true;
}
function howMuchIsYourAllowance() public returns (uint) {
return daughter.howMuch();
}
function howOldAreYou() public returns (uint) {
return mom.getAge();
}

We’ll add the permissionToDate function that only the owner (Mom) can call. The son,
ever so rudely, wants to know how much his sister’s allowance is and how old his mom
is because he forgot. Since we have access to both the MomContract and the
DaughterContract , he is able to access functions within those contracts.

In the MomContract I’ve added:

function getAge() public returns (uint) {


return age;
}

And in the DaughterContract I’ve added a variable called allowance , and set it to equal
100. I’ve also added:

function howMuch() public returns (uint) {


return allowance;
}

The son can call those functions and find out the age of his Mom and the allowance of
his Sister.

https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 7/11
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

You can see the code for all three contracts and the tests here.

Let’s get real


Maybe some of you are thinking — why would you ever need to do this? You can simply
access the functions of another contract by passing its address in the constructor of
your contract. In the example above, we could have deployed the DaughterContract and
SonContract first, and passed the addresses to the MomContract so she could call their
functions.

I initially used this method because I wanted to use the onlyOwner modifier. In our real
world project, we had a MultiSig contract that would call the functions of ContractA
and ContractB once everyone signed off. In ContractA and ContractB, we wanted to
check that only the MultiSig wallet was calling those functions. So I thought, great, let’s
https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 8/11
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

use the Ownable contract provided by OpenZepplin and have the MultiSig contract
deploy those children contracts.

However…

As we added functions to the MultiSig contract and the child contracts that the MultiSig
contract was creating, the gas cost to deploy the MultiSig contract was increasing. I
learned that the CREATE opcode is one of the most expensive opcodes, and we were
using it twice in our MultiSig constructor. Eventually, we got to a point where the
contracts had gotten so large that we could not add any new functions. The gas cost
was to high.

Going back to our Family factory example — when the MomContract uses new to create
the DaughterContract and SonContract , she stores all of their bytecode. That means,
any function you add to the those child contracts adds to the bytecode size of the
MomContract .

Deploying the DaughterContract and SonContract first, and passing them into the
MomContract will save on gas since the MomContract will not store the bytecode of the
child contracts. However, the son will not be able to find out how old his mom is
because he won’t have her address to call the getAge function (since he is created
first).

This is what happened with our project. We had 6 smart contracts that all needed to
call each other’s functions and we wanted modifiers in several of those contracts to
restrict access to specific contracts. How can all contracts know about each other at
the time of deployment? Sometimes you can’t line them up perfectly.

Our solution…a registry. Stay tuned for my next post where I will be writing about how
we used a registry to keep track of our smart contracts.

If you want to learn more about using factories to create multiple instances of
contracts, I recommend the following articles:

Solidity DelegateProxy Contracts

Solidity Smart Contracts Design Patterns


https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 9/11
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

I hope you found this article useful. Please don’t hesitate to reach out if you have
additional questions or thoughts you’d like to discuss further with our team —
[email protected]

☞ To stay up to date with our work with smart contract development, follow us on
Medium and Twitter.

Sign Up for our Monthly Email!


Email

First Name

Sign up

I agree to leave medium.com and submit this information,


which will be collected and used according to Upscribe's
privacy policy.

Powered by Upscribe

Ethereum Blockchain Smart Contracts Dapps Distributed Ledgers

https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 10/11
2/12/23, 3:35 PM Creating a contract with a smart contract | by Kseniya Lifanova | Upstate Interactive | Medium

413 4

About Help Terms Privacy

Get the Medium app


Open in app Sign up Sign In

Search Medium

https://medium.com/upstate-interactive/creating-a-contract-with-a-smart-contract-bdb67c5c8595 11/11
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+

How to Simply Deploy a Smart Contract on


Ethereum?
Difficulty Level : Hard ● Last Updated : 10 Nov, 2022

Read Discuss Courses Practice Video

Smar t contracts are blocks of code that reside on the blockchain. It is like an Ethereum

account but there is a critical difference between an external account and a smar t

contract. Unlike a smar t contract, an external account can connect to multiple Ethereum

networks (Goerli testnet, mainnet, etc.) whereas a smar t contract is only specific to one

individual network (the network it is deployed on). When a smar t contract is deployed, it

creates an instance (contract account) on the network. One can create multiple

instances of a smar t contract on the network or multiple networks. Deployment of a

smar t contract is done by sending a transaction to the network with bytecode.

Deploying To A Local Network

An emulator can be used to deploy a smar t contract on a local network eg. Ganache-cli.

It takes care of ever ything and the user doesn’t have to worr y about the security and the

gas amount required for transactions since ever ything is happening on a local test

network. All one has to do is pass the ganache provider as an argument to the web3

instance(web3 facilitates the connection between the blockchain network and the js

application). 

Start Your Coding Journey Now! Login Register


https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 1/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

Deploying To Actual Ethereum Network

Before deploying a smar t contract to an actual Ethereum network make sure the account

has some ether in it. Deploying a contract is like sending a transaction and it needs some

gas amount to process. Unlike deploying on a local network, transactions will take some

time to complete (anywhere between 15 seconds to 5 minutes). Web3 is used to interact

with the network the same way it is done in local deployment except customize the

provider that will be passed into the web3 instance. Instead of creating our own node

that connects to the Ethereum network, one can use a developer platform with RPC

endpoints like Infura or Alchemy. With one of these accounts, you have an API key that

gives access to their Infura / Alchemy blockchain nodes that are already hosted on the

Ethereum network. Simply sign-up for Infura and get an endpoint that will be used in the

code to deploy the smar t contract. The below tutorial shows a smar t contract being

deployed with Infura. For a smar t contract tutorial using tools like Alchemy (ethers.js,

Hardhat, Solidity, and Metamask), refer to this basic tutorial – “Hello World Smar t

Contract“.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 2/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

example.sol- Below is the sample solidity code used for testing. All it does is set a public

variable as the address of the sender.

Solidity

// Solidity program to implement

Start Your Coding Journey Now!


// the above approach
pragma solidity ^0.8.4;
https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 3/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

 
// Creating a contract named Example
contract Example
{
    // Public variable of type address
    address public manager;
 
    // Constructor function to set manager
    // as address of sender
     constructor()
     {
        manager = msg.sender;
     }
}

Step 1- Install the required dependencies by running the following commands-

npm i [email protected] [email protected] [email protected]

Make sure to install the same versions for the following scripts to run successfully.

Step 2- Sign up for Infura and create a project on a par ticular Ethereum network to get

access to the endpoint. The endpoint will be required to deploy the smar t contract on the

infura node that is already hosted on the Ethereum network. To create a project on

infura-

Click on create a new project.

Give it a name.

Select the network to deploy the smar t contract on. 

A maximum of 3 projects can be created on infura for free.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 4/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

Step 3 – Get access to Bytecode and A BI (Compile the smar t contract). Solidity compiler

gives a huge piece of code as output, one can print the output to console if required. Only

the relevant par t (relevant for deployment) i.e., bytecode and inter face are extracted

from the output in the following script.

Compile.js- Below is the javascript file.

Javascript

// Javascript file to implement


// the above approach

Start Your Coding Journey Now!


const path = require("path");
const fs = require("fs");
https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 5/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

const solc = require("solc");


 
// remember to change line 8 to your
// own file path. Make sure you have your
// own file name or contract name in line
// 13, 28 and 30 as well.
 
const examplePath = path.resolve(__dirname, "contracts", "example.sol");
const source = fs.readFileSync(examplePath, "utf-8");
 
var input = {
    language: 'Solidity',
    sources: {
        'example.sol': {
            content: source
        }
    },
    settings: {
        outputSelection: {
            '*': {
                '*': ['*']
            }
        }
    }
};
 
var output = JSON.parse(solc.compile(JSON.stringify(input)));
 
var interface = output.contracts["example.sol"]["example"].abi;
 
var bytecode = output.contracts['example.sol']["example"].evm.bytecode.object;
 
module.exports = { interface, bytecode };

Step 4 – Add Metamask extension to google chrome from the chrome web store.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 6/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

Step 5 – Once have access to the bytecode and inter face, all that is required is to create a

provider with own mnemonic phrase and infura endpoint using the truffle-hdwallet-

provider that was installed earlier. Create a web3 instance and pass the provider as an

argument. Finally, use the deploy method with bytecode as an argument to deploy the

smar t contract.

deploy.js

Javascript

const HDWalletProvider = require("truffle-hdwallet-provider");


 
// Web3 constructor function.
const Web3 = require("web3");
 
// Get bytecode and ABI after compiling
// solidity code.
const { interface, bytecode } = require("file-path");
 
const provider = new HDWalletProvider(
  "mnemonic phrase",
  // Remember to change this to your own phrase!
  "-"
  // Remember to change this to your own endpoint!
);
 
// Create an instance of Web3 and pass the
// provider as an argument.
Start Your Coding Journey Now!
const web3 = new Web3(provider);

https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 7/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

 
const deploy = async () => {
  // Get access to all accounts linked to mnemonic
  // Make sure you have metamask installed.
  const accounts = await web3.eth.getAccounts();
 
  console.log("Attempting to deploy from account", accounts[0]);
 
  // Pass initial gas and account to use in the send function
  const result = await new web3.eth.Contract(interface)
    .deploy({ data: bytecode })
    .send({ gas: "1000000", from: accounts[0]});
 
  console.log("Contract deployed to", result.options.address);
};
 
deploy();
 
// The purpose of creating a function and
// calling it at the end -
// so that we can use async await instead
// of using promises

Output : 

Contract is deployed to 0x8716443863c87ee791C1ee15289e61503Ad4443c

Now the contract is deployed on the network, its functionality can be tested using remix

IDE or one can create an inter face to interact with the smar t contract on the network.

Interacting With Deployed Smar t Contract Using Remix IDE

Remix can be used to connect to actual Ethereum networks and interact with deployed

smar t contracts. It is the easiest way to interact with a deployed smar t contract without

having to make a fancy frontend. 

Step 1- Open Remix IDE in chrome browser and copy the solidity code of the deployed

smar t contract and paste it in the Ballot.sol file in the IDE. Switch to the solidity compiler

by clicking on the “S” icon on the sidebar and compile it.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 8/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

Step 2- Navigate to Deploy and run transactions from the sidebar and select injected

web3 from environment dropdown. It is the instance of web3 injected by metamask into

your browser. It also has access to all the accounts.

Step 3- Instead of deploying the smar t contract, copy the address of the already

deployed smar t contract in the “At Address” field. This button is disabled until you put in

a valid address. Once the button is clicked, the list of functions from your smar t

contracts can be seen. One can interact with a deployed smar t contract using these

function buttons. Since the “example.sol” has only one variable, manager. Clicking this

button will give the address of the account it was deployed from as the output.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 9/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

Before Mainnet Deployment | Goerli Testnet

Before deploying to the Ethereum mainnet, we recommend deploying to the Goerli

testnet. Note that with the recent Ethereum merge, Goerli is the only Ethereum-

suppor ted testnet. Other testnets like Rinkeby, Kovan, and Ropsten have been

deprecated. 

By deploying on Goerli testnet first, you’re able to test your smar t contract without it

costing real money (in the form of real E TH). In order to deploy to Goerli testnet

(https://eth-goerli.g.alchemy.com/v2/Alchemy-API-key  or

https://goerli.infura.io/v3/Infura-API-key), you’ll need test Goerli Ether (“Goerli

testE TH”). You get Goerli testE TH from Goerli faucets – for example, Alchemy provides a

free Goerli faucet where you can get more testE TH ever y day: goerlifaucet.com. 

Start Your Coding Journey Now! Like 5

https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 10/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

Next

How to use GANACHE Truffle Suite


to Deploy a Smart Contract in
Solidity (Blockchain)?

Related Articles

1. Deploy a Smart Contract on Ethereum with Python, Truffle and web3py

2. Interacting With Ethereum Smart Contract Using Web3js

3. Solidity - Deploy a Smart Contract for Marks Management System

4. How to use MetaMask to Deploy a Smart contract in Solidity (Blockchain)?

5. How to use GANACHE Truffle Suite to Deploy a Smart Contract in Solidity


(Blockchain)?

6. How to Deploy Contract From NodeJS using Web3?

7. Use of Ethereum's RLPx in Ethereum Ecosystem

8. Ethereum (ETH) vs Ethereum Classic (ETC) in Blockchain

9. Steps to Execute Solidity Smart Contract using Remix IDE

10. Creating a Smart Contract that Returns Address and Balance of Owner using
Solidity

Start Your Coding Journey Now!


Ar ticle Contributed By :

https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 11/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

gitanshwadhwa
@gitanshwadhwa

Vote for difficulty

Current difficulty : Hard

Easy Normal Medium Hard Expert

Improved By : shelleyolto0v

Article Tags : Picked, Blockchain, Solidity

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Start YourAdvertise
Coding Journey Now!
with us Video Tutorials

https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 12/13
2/12/23, 3:38 PM How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks

Courses

News Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Web Development Contribute


Web Tutorials Write an Article
Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/how-to-simply-deploy-a-smart-contract-on-ethereum/ 13/13
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

Published in Edureka

Aryya Paul Follow

Feb 28, 2018 · 8 min read · Listen

Save

Solidity Tutorial - A Complete Guide To Start


Your Journey In Solidity

Solidity Tutorial — Edureka

This article on Solidity tutorial showcases a lot of Solidity features. This tutorial
assumes some knowledge of the Ethereum Virtual Machine and programming in
general.

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 1/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

Ethereum, the world Computer provides an enormously powerful shared global infrastructure
to build a Decentralized application using a programming language called Solidity.

This article on Solidity tutorial covers the following topics:

1. What is Solidity?

2. Contracts in Ethereum Solidity

3. The layout of a Solidity File

4. Value Types in Solidity

5. Operators

6. Data Structures in Solidity

7. Control Structures

8. Functions

9. Inheritance

Let’s start our Solidity Tutorial with an introduction to Solidity.

What is Solidity?

Ethereum Solidity is a contract-oriented, high-level language with a syntax like that of


JavaScript.

Solidity is a tool used to generate a machine-level code to execute on EVM. The solidity
compiler takes the high-level code and breaks it down into simpler instructions.

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 2/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

Solidity code is encapsulated in Contracts

Contracts in Ethereum Solidity


A contract is the fundamental building block of Ethereum’s decentralized Applications.
All variables and functions are part of a contract and this is the starting point of all the
projects.

An empty contract named MyFirst would look like this:

version pragma ^0.4.19;


contract MyFirst{
}

Stick to your screen because next in our Solidity tutorial we’re gonna start coding…

Layout of Solidity File


Source files can contain an arbitrary number of contract definitions, include directives
and pragma directives.

Version Pragma
Version Pragma is the declaration of the version of the Solidity compiler that the
particular code should use.

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 3/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

version pragma ^0.4.00;

Note: The source file shown above will not compile with a compiler earlier than version 0.4.0
and it will also not work on a compiler starting from version 0.5.0.

Importing other Source Files


Ethereum Solidity supports import statements that are very similar to those available
in JavaScript, although Solidity does not know the concept of a “default export”.

At a global level you can use import statements of the following form:

import "filename";

The above statement imports all global symbols from “filename” into the current
global scope.

import * as symbolName from "filename";

…creates a new global symbol symbolName whose members are all the global symbols
from “filename”

Comments
Just like any other language, single line and multi-line comments are possible in Solidity.

// This is a single-line comment.


/*
This is a
multi-line comment
*/

Now, before we move further in our Solidity tutorial, you should know that Ethereum
has three areas where it can store items.

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 4/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

1. Storage: where all the contract state variables reside. Every contract has its own
storage and it is persistent between function calls

2. Memory: hold temporary values and gets erased between (external) function calls
and is cheaper to use

3. Stack: hold small local variables and is almost free to use, but can only hold a
limited amount of values

For almost all the types, you cannot specify where they should be stored, because they
are copied everytime they are used.

Alright, now that you are aware of the storage locations in Ethereum Solidity, let me
tell you about the general value types.

Value Types in Solidity


The following types are also called value types because variables of these types will
always be passed by value.

Boolean
Keyword: Bool

The possible values are constants i.e., true or false

Integers
https://medium.com/edureka/solidity-tutorial-ca49906bdd47 5/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

Keyword: int/uint (uint8 to uint256 in steps of 8 (unsigned of 8 up to 256 bits) and int8 to
int256)

Signed and unsigned integers of various sizes.

Example:

contract MySample{
uint UnsignedInt =50;
}

In the above statement, we have created a uint called InsignedInt & set it to 50.

Address:
Keyword: address

Holds a 20-byte value (size of an Ethereum address). Address types also have members
and serve as a base for all contracts.

Members of Addresses: Balance & Transfer

It is possible to query the balance of an address using the property balance and to send
Ether to an address using the transfer function.

address x = 0x123;
address myAddress = this;
if (x.balance < 10 && myAddress.balance > = 10)
x.transfer(10);

Strings:
Keyword: String literals are written with either double or single-quotes “foo” or ‘bar’.

Used for arbitrary-length UTF-data.

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 6/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

string language = "Solidity";

These value types can interact with each other in expressions containing operators.
Next, in our Solidity tutorial, let me tell you about the various operators.

Operators
Operators in solidity are same as in JavaScript. Solidity has four types of operators:

Arithmetic Operators
Solidity has pretty straightforward Math operations. The following are similar to most
of the programming languages:

Addition: x + y

Subtraction: x - y

Multiplication: x * y

Division: x / y

Modulus / remainder: x % y

Solidity also give you an option to use an exponential operator, here’s how:

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 7/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

uint x = 10 ** 3; // equal to 10^3 = 1000

Incremental Operators
Incremental operators in solidity: a++, a–, ++a, –a, a+=1, a=a+1

Rules applicable to other programming languages are similar in solidity also.

Bitwise Operators:
Following are the operators: (Bitwise OR) ‘|’, (Bitwise XOR), (Bitwise negation) ‘~’ ,
(Bitwise right shift) ‘>>’, (Bitwise left shift) ‘<<‘

Logical Operators:
Logical operators in Solidity: ! (logical negation), && (logical and), || (logical or), ==
(equality), != (not equal)

Example:

contract operators {
// Arithmetic Operators
// +,-,*,/, %, **
// Incremental Operators
// a++, a--, a+=1, a=a+1,++a,--a;
a=10;
a= a++; //here, output will be 10, because the value is first returned
and then then increment is done
a=++a;
//Logical Operators
!, &&, ||, ==, !=
isOwner = true && false;
var orValue= 0x02 | 0x01; // output would be 0x03
//Bitwise Operators~,>>, <<;
function Operators() {
// Initialize state variables here}}

Now Sometimes there is a need for a more complex data type. For this Solidity
provides structs.

Data Structures in Solidity


https://medium.com/edureka/solidity-tutorial-ca49906bdd47 8/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

Solidity provides three types of data structures:

Structs
Solidity provides a way to define new types in the form of structs. Structs are custom
defined types that can group several variables.

pragma solidity ^0.4.0;


contract Ballot {
struct Voter { // Struct
uint weight1, weight2, weight3;
bool voted;
address delegate1, delegate2, delegate3, delegate4;
string name;
uint vote1, vote2, vote3, vote4, vote5;
uint height1, height2, height3 } }

Note: Structs can only have 16 members, exceeding which the following error might
occur: Stack too Deep.

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 9/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

Structs allow you to create more complicated data types that have multiple properties.

Now, what if you need a collection of something, say addresses. Well, just like most of
the languages, Solidity also has Arrays.

Arrays
Arrays in Solidity can have a compile-time fixed size or they can be dynamic.

uint[3] fixed; //array of fixed length 3


uint[] dynamic; //a dynamic array has no fixed size, it can keep
growing

You can also create an array of structs. Using the previously created Voter struct:

Voter[] voting;

Note: declaring an array as public will automatically create a getter method for it.

Voter[] public voting;

Mappings
Mappings can be seen as hash tables which are virtually initialized such that every
possible key exists and is mapped to a value whose byte-representation is all zeros: a
type’s default value.

Mappings are declared as:

Mapping(_Keytype => _ValueType )

Note: _Keytype can be almost any type except for a dynamically sized array, a contract,
an enum and a struct.

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 10/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

Example:

contract MappingExample {
mapping(address => uint) public balances;
function update(uint newBalance) {
balances[msg.sender] = newBalance; }}
contract MappingUser {
function f() returns (uint) {
MappingExample m = new MappingExample();
m.update(100);
return m.balances(this);
}}

Control Structures
Most of the control structures in JavaScript are available in Solidity except for switch
and goto.

So there is: if, else, while, do, for, break, continue, return, ? :, with the usual semantics
known from C or JavaScript.

Note: There is no type conversion from non-boolean to boolean types as there is in C


and JavaScript.

Now let’s see how these Control structures are used in Solidity.

Example:

contract ControlStructure {
address public a;
function ControlStructure>){
// if-else can be used like this
if(input1==2)
a=1;
else
a=0;
// while can be used like this
while(input1>=0){
if(input1==5)
continue;
input1=input1-1;
a++;}
https://medium.com/edureka/solidity-tutorial-ca49906bdd47 11/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

// for loop can be used like this


for(uint i=0;i<=50;i++) { a++; if(a==4) break; } //do while can be
used like this do { a--; } (while a>0);
// Conditional Operator can be used like this
bool IsTrue = (a == 1)?true: false;
/*will show an error because
there is no type conversion from non-boolean to boolean
*/
if(1)
{
}

Moving on with our Solidity tutorial blog, let’s talk about the executable units of code
within a Contract. These are called functions.

Functions
Here is how a function is declared in Solidity.

function sampleFunc(string name, uint amount) {


}

The above-declared is an empty body function which takes two parameters: a string
and a uint.

You would call this function like:

sampleFunc("Shashank", 10000);

Talking about functions, Solidity also provides function modifiers.

Function Modifiers
It is used to easily change the behavior of the functions. These conditions can be
checked before even making the function calls because they have been declared in the
function definitions in the smart contracts.

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 12/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

Example: If you want to call a kill contract function through only the owner or creator
of the function.

contract FunctionModifiers{
address public creator;
function FunctionModifiers() {
creator = msg.sender;}
Modifier onlyCreator() {
if(msg.sender!=creator){
throw; }
_; //resumes the function wherever the access modifier is used
}
function killContract() onlyCreator{ //function will not execute if an
exception occurs
self-destruct(creator); }}

Inheritance
Solidity supports multiple Inheritance by copying code including polymorphism.

contract Owned {
address Owner ;
function owned() {
owner = msg.sender;
}}
contract Mortal is Owned { // 'is' keyword is used for inheritance
function kill(){
self-destruct(owner); }}
contract User is Owned, Mortal //Multiple inheritance
{
string public UserName;
function User(string _name){
UserName = _name;
}}

Alright, I feel the above-discussed concepts are sufficient enough for you to kick-start with
Solidity programming.

Go Code!!

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 13/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

With that, I conclude this Solidity Tutorial article. I hope you enjoyed reading this blog
and found it informative. By now, you must have acquired a sound understanding of
what Solidity Programming Language is. Now go ahead and practice.

I hope you enjoyed reading this blog and found it informative. If you wish to check out
more articles on the market’s most trending technologies like Artificial Intelligence,
DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects
of Blockchain.

1. Blockchain Tutorial

2. Ethereum Tutorial

3. Ethereum Private Networks

4. What are Smart Contracts?

5. Truffle Ethereum Tutorial

6. Best Ethereum Development Tools

7. Hyperledger Fabric

8. Hyperledge vs Ethereum

Originally published at www.edureka.co on February 28, 2018.

Ethereum Solidity Solidity Tutorial Blockchain Blockchain Technology

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 14/15
2/12/23, 3:48 PM Solidity Tutorial - A Complete Guide To Start Your Journey In Solidity | by Aryya Paul | Edureka | Medium

About Help Terms Privacy

Open in app Sign up Sign In

Get the Medium app


Search Medium

https://medium.com/edureka/solidity-tutorial-ca49906bdd47 15/15
2/12/23, 3:53 PM An Introduction of Solidity, Ethereum’s Programming Language | by Kevin Gabeci | DataDrivenInvestor

Published in DataDrivenInvestor

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Kevin Gabeci Follow

Aug 1, 2020 · 2 min read · · Listen

Save

An Introduction of Solidity, Ethereum’s


Programming Language
Solidity is an object-oriented programming language that is used for writing smart
contracts on various blockchain platforms. It is mostly associated with Ethereum as it
is developed by some core authors of the coin. It was first proposed in August 2014 by
computer scientist Gavin Wood and later acquired by the Ethereum project’s Solidity
team.

https://medium.datadriveninvestor.com/an-introduction-of-solidity-ethereums-programming-language-2ce325707f9e 1/4
2/12/23, 3:53 PM An Introduction of Solidity, Ethereum’s Programming Language | by Kevin Gabeci | DataDrivenInvestor

Photo by Clément H on Unsplash

Why Solidity?
Solidity is a statically-typed programming language designed for developing smart
contracts that run on the EVM. Solidity is compiled to bytecode that is executable on
the EVM. With Solidity, developers can write applications that implement self-
enforcing business logic embodied in smart contracts, leaving a non-repudiable and
authoritative record of transactions. Writing smart contracts in contract-specific
languages such as Solidity is claimed to be easy if you have prior programming
experience.

Strategic or Tactical Programming? The Road Ahead for Software


Engineers | Data Driven Investor
Ousterhout (2018) mentions in his book 'A Philosophy of Software
Design" some principles in order to dig deeper into…
www.datadriveninvestor.com

https://medium.datadriveninvestor.com/an-introduction-of-solidity-ethereums-programming-language-2ce325707f9e 2/4
2/12/23, 3:53 PM An Introduction of Solidity, Ethereum’s Programming Language | by Kevin Gabeci | DataDrivenInvestor

Its syntax is very similar to that of scripting languages like JavaScript, and it was
influenced by existing languages such as C++, Python, and JavaScript.Solidity uses a
vast number of programming concepts from other coding languages. For example, it
has variables, string manipulation, classes, functions, arithmetic operations, and so
on. While in a language like C, a programmer would be likely to create some form of a
function, like ‘int main’ and ‘main,’ Solidity works with a ‘contract’ that is created
analogously.

Is it worth learning it?


While jobs for blockchain are on the rise learning a programing language for said
blockchains,
Open in app
it’s a huge bonus. You won’t be without a job, but if you haven’t mastered
Sign up Sign In
another language before, you’ll find challenges in the learning process. If you are
committed to Search
spending a few years learning it, then go ahead and do it since it’s not a
Medium
bad opportunity to start now.

You can use Solidity for several things, like creating your decentralized app or smart
contracts. dApps are on the rise now, and it’s a good skill to know how to write them
since the job market is going to need a lot more coders in the future specialized in this
specific thing.

Here’s my article about creating your cryptocurrency token using Solidity.

Gain Access to Expert View — Subscribe to DDI Intel

Ethereum Blockchain Solidity Cryptocurrency Programming

Get notified via email whenever Kevin Gabeci publishes an interesting article.
The more that you read, the more things you'll know. The more that you learn, the more places you'll go. So, don't hesitate
and subscribe to read the latest from me. Let's learn and grow together.

https://medium.datadriveninvestor.com/an-introduction-of-solidity-ethereums-programming-language-2ce325707f9e 3/4
2/12/23, 3:53 PM An Introduction of Solidity, Ethereum’s Programming Language | by Kevin Gabeci | DataDrivenInvestor

By signing up, you will create a Medium account if you don’t already have one. Review
our Privacy Policy for more information about our privacy practices.

Subscribe

About Help Terms Privacy

Get the Medium app

https://medium.datadriveninvestor.com/an-introduction-of-solidity-ethereums-programming-language-2ce325707f9e 4/4
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Leo Zhang Follow

Jul 24, 2022 · 7 min read · · Listen

Save

Verify Ethereum Smart Contract State with Proof


In previous blog post, we introduced how to verify account state with state proof.

In this blog post, I will introduce how data is stored in Ethereum smart contract, and
how to verify the storage state with proof.

What to store in smart contract storage


Ethereum smart contract is also an account, which has its own account state, such as
account balance, nonce. In addition to that, it also has code and extra storage.

The storage of a smart contract is essentially a key-value pair store. In order to


generate and store proof for the existence of a key-value pair, a Merkle Patricia Trie is
constructed to store the key value pairs.

What is the actual key value pairs to be stored in storage?


In order to explain that, let’s use a smart contract as an example. For simplicity, I will
use the default Migration contract from truffle:

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract Migrations {
address public owner = msg.sender;
https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 1/11
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

uint public last_completed_migration;


modifier restricted() {
require(
msg.sender == owner,
"This function is restricted to the contract's owner"
);
_;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
}

This contract is for storing migration steps. It has two state variables: owner and
last_completed_migration .

How are they stored as key value pairs in storage? Is the owner stored under a key
owner and the other uint value migration under a key last_completed_migration ?

No. The variable names are not stored in smart contract storage.

Each state variables are stored in a storage unit called, slot . slot is indexed from 0.

So in the above example, the owner value is stored at slot 0, and the
last_completed_migration value is stored at slot 1.

These slots are determined at compile time, strictly based on the order in which the
variables appear in the contract code.

Query the contract state value in storage


The contract source code shows it has two state values. They are stored in storage slots.
How to query them?

We can query them from a full node using the RPC method getStorageAt .

It takes the contract address and slot index as parameters. In our example, the contract
is deployed at address 0xcca577ee56d30a444c73f8fc8d5ce34ed1c7da8b . We can double
check the contract’s source code on etherscan.io:

https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 2/11
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

Since the owner value stores at slot 0. We can send the following request to query the
value for the owner .

curl https://eth-mainnet.g.alchemy.com/v2/<API_KEY> \
-X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_getStorageAt","params":
["0xcca577ee56d30a444c73f8fc8d5ce34ed1c7da8b","0x0"],"id":1}'
{
"jsonrpc": "2.0",
"id": 1,
"result":
"0x000000000000000000000000de74da73d5102a796559933296c73e7d1c6f37fb"
}

The result shows the stored owner address is


0xde74da73d5102a796559933296c73e7d1c6f37fb . Note the result is left padded with 0s
because each slot stores 32 bytes data.

Likewise, we can query the last_completed_migration value stored at slot 1.

curl https://eth-mainnet.g.alchemy.com/v2/<API_KEY> \
-X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_getStorageAt","params":
["0xcca577ee56d30a444c73f8fc8d5ce34ed1c7da8b","0x1"],"id":1}'
{
"jsonrpc": "2.0",
"id": 1,
"result":
"0x0000000000000000000000000000000000000000000000000000000000000002"
}

The result shows


it’s 0x0000000000000000000000000000000000000000000000000000000000000002 , which is a uint
value 2 in left padded hex format.

https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 3/11
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

We don’t have to trust these values, because later we will query proof for them and
verify the proof ourselves.

Storage Merkle Trie


With the result from the eth_getStorageAt method, we’ve verified that the storage
values are stored at slot 0 and 1:

slot 0: 0xde74da73d5102a796559933296c73e7d1c6f37fb
slot 1: 0x02

In order to generate proof for the storage state, the full node need to store these key
value pairs into a Merkle trie.

Before storing into Merkle trie, the key-value pairs need to be converted.

The slot index, which is the key, will first first be encoded to hex string and left padded
with 0s, then hashed with keccad256 ;

The value will be encoded to hex string and then RLP encoded.

This is the actual converted key-value pairs stored into the contract storage merkle trie:

"0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563":
"0x94de74da73d5102a796559933296c73e7d1c6f37fb"
"0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6":
"0x02"

We can construct this Merkle trie locally with these two key value pairs and compute
the root hash of the trie. Later, we can use the root hash to compare with the hash in
the proof.

// slot index
slot0 :=
common.FromHex("0x0000000000000000000000000000000000000000000000000000
000000000000")
https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 4/11
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

slot1 :=
common.FromHex("0x0000000000000000000000000000000000000000000000000000
000000000001")
// encode values to be stored
ownerAddress, err :=
rlp.EncodeToBytes(common.FromHex("0xde74da73d5102a796559933296c73e7d1c
6f37fb"))
require.NoError(t, err)
lastCompletedMigration, err :=
rlp.EncodeToBytes(common.FromHex("0x02"))
require.NoError(t, err)
// create a trie and store the key-value pairs,
// the key needs to be hashed
trie := NewTrie()
trie.Put(crypto.Keccak256(slot0), ownerAddress)
trie.Put(crypto.Keccak256(slot1), lastCompletedMigration)
// compute the root hash and check if consistent with the storage
// hash of contract 0xcca577ee56d30a444c73f8fc8d5ce34ed1c7da8b
rootHash := trie.Hash()
storageHash :=
common.FromHex("0x7317ebbe7d6c43dd6944ed0e2c5f79762113cb75fa0bed712437
7c0814737fb4")
require.Equal(t, storageHash, rootHash)

The above test passes.

If we visualize the Merkle trie we built locally, this is what it look like:

https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 5/11
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

Verify contract State with storage Proof


We have the root hash of the storage trie of the deployed contract. Now let’s verify it by
querying account proof using the eth_getProof RPC method.

Note, the parameter 0xcca577ee56d30a444c73f8fc8d5ce34ed1c7da8b is the contract


address; 0xA8894B is block 11045195 :

curl https://eth-mainnet.g.alchemy.com/v2/<API_KEY> \
-X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_getProof","params":
["0xcca577ee56d30a444c73f8fc8d5ce34ed1c7da8b",[], "0xA8894B"],"id":1}'
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"address": "0xcca577ee56d30a444c73f8fc8d5ce34ed1c7da8b",
"accountProof": [
...
],
"balance": "0x0",
"codeHash":
"0x6c7686cf8f47f081f63d3f53a87c3c2ca0de63eb057e795f5c0414c6f861f9e3",
"nonce": "0x0",

https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 6/11
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

"storageHash":
"0x7317ebbe7d6c43dd6944ed0e2c5f79762113cb75fa0bed7124377c0814737fb4",
"storageProof": []
}
}

The result shows that the storageHash is


0x7317ebbe7d6c43dd6944ed0e2c5f79762113cb75fa0bed7124377c0814737fb4 , which matches
with the root hash of the Merkle trie that we created with the two key value pairs for
the two contract variables. This means the storage state for that contract is identical to
the Merkle trie we created locally.

But in order to trust the storageHash is valid, we should first verify the full account
state is valid with the proof. I will skip this part here, since we’ve introduced how to do
it in the previous blog post. You could also checkout the test case (see link in the end).

However, a contract might have lots of contract variables, what if I only care about the
state of a specific contract variable? Is it possible to query and verify proof for a single
contract variable? For instance, the owner variable.

Yes, we can.

Verify contract variable with proof


The eth_getProof method allows to query the proof for a single state slot (or multiple).
The second parameter of the eth_getProof method accepts an array of storage keys,
which could be state slot index.

For instance,to query the proof for the owner variable at slot 0, we can specify the
storage key as 0x0000000000000000000000000000000000000000000000000000000000000000 or
0x0 for short:

curl https://eth-mainnet.g.alchemy.com/v2/<API_KEY> \
-X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_getProof","params":
["0xcca577ee56d30a444c73f8fc8d5ce34ed1c7da8b",["0x0"],
"0xA8894B"],"id":1}'

https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 7/11
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"address": "0xcca577ee56d30a444c73f8fc8d5ce34ed1c7da8b",
"accountProof": [
...
],
"balance": "0x0",
"codeHash":
"0x6c7686cf8f47f081f63d3f53a87c3c2ca0de63eb057e795f5c0414c6f861f9e3",
"nonce": "0x0",
"storageHash":
"0x7317ebbe7d6c43dd6944ed0e2c5f79762113cb75fa0bed7124377c0814737fb4",
"storageProof": [
{
"key": "0x0",
"value": "0xde74da73d5102a796559933296c73e7d1c6f37fb",
"proof": [

"0xf8518080a0cd2a98a2ebb71b70e1109bf206dbc96dc73c76569b42df09ff269ecdc
d31b1398080808080808080a0236e8f61ecde6abfebc6c529441f782f62469d8a2cc47
b7aace2c136bd3b1ff08080808080",

"0xf7a0390decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56
39594de74da73d5102a796559933296c73e7d1c6f37fb"
]
}
]
}
}

The result includes a non-empty storageProof field. That is the proof for the state of
the owner variable.

The proof contains two hex strings, which are the two encoded trie nodes along the
path from the root node of the trie to the leaf node that stores the value.

It can be verified against the storageHash in the account state:

result := response.Result
// the storage hash and the proof is the data to be verified
storageHash := result.StorageHash
storageProof := result.StorageProof[0]

https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 8/11
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

// encode the key-value pair


key := common.LeftPadBytes(storageProof.Key, 32)
value, err := rlp.EncodeToBytes(storageProof.Value)
require.NoError(t, err)
// build a trie with the nodes in the proof
proofTrie := NewProofDB()
for _, node := range storageProof.Proof {
proofTrie.Put(crypto.Keccak256(node), node)
}
// verify the proof
verified, err := VerifyProof(
storageHash.Bytes(), crypto.Keccak256(key), proofTrie)
require.NoError(t, err)
// confirm the value from the proof is consistent with
// the reported value
require.True(t, bytes.Equal(verified, value), fmt.Sprintf("%x != %x",
verified, value))

Verification passed. It means we can trust that at block 11045195 , the owner value of
the Migration contract, which is deployed at address
0xcca577ee56d30a444c73f8fc8d5ce34ed1c7da8b , is
0xde74da73d5102a796559933296c73e7d1c6f37fb .

Summary
OK. Let’s make a summary of what we’ve learned so far:

Ethereum contract has extra storage to store contract’s state variables.

State variables are stored in storage slots, each slot is 32 bytes long.

Storage slots are indexed from 0.

Slot index is a uint256 number, it’s a very big space.

As a light client, they can query storage proof from a full node for a specific state
variable of a contract using the eth_getProof method.

Once received the storage proof, a light client can verify it themselves.

Light client uses the nonce in the block header to verify the block. If the block
header is valid, it can trust the stateRoot hash included in the block header.
https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 9/11
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

Light client can query the state proof for a specific contract by address, and can
verify the account state against the stateRoot hash that they trust. After the
verification, if the account state is valid, they can trust the account state data,
which includes the storageHash .

Light client can query the storage proof for a specific state variable of a contract.
The storage proof is another Merkle proof that can be verified against the
storageHash of the account state. If the storage proof is valid, the light client can
trust that the value of the state variable.

Next
In this tutorial, we used simple contract to explain how the contract state is stored. The
contract state variables are fixed sized values, such as address, uint etc.

Ethereum smart contract could also store dynamic sized values, such as array and
map. There are very useful use cases for them. We will cover them in the next blog
post.

In the next blog post, I will use the USDC contract as an example to explain how a
smart contract stores dynamic sized values, and how to verify the USDC account
balance or other ERC20 token balance with proof.

Stay turned!

References
https://ethereum.github.io/yellowpaper/paper.pdf

The source code of all the code and test cases used in this blog post

More
If you are interested in learning more, check out my blog post series:

Merkle Patricia Trie Explained

Verify Ethereum Account Balance with State Proof

EIP 1186 — the standard for getting account proof


https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 10/11
2/12/23, 3:57 PM Verify Ethereum Smart Contract State with Proof | by Leo Zhang | Medium

Verify Ethereum Smart Contract State with Proof

Verify USDC Balance and NFT Meta Data with Proof

Blockchain Ethereum Crypto Cryptocurrency Web 3

About Help Terms Privacy


Open in app Sign up Sign In

Get the MediumSearch


app Medium

https://medium.com/@chiqing/verify-ethereum-smart-contract-state-with-proof-1a8a0b4c8008 11/11
2/12/23, 3:59 PM Get ETH & ERC20 token balances for multiple addresses in a single call | by William O'Beirne | Medium

William O'Beirne Follow

Nov 6, 2018 · 4 min read · Listen

Save

Get ETH & ERC20 token balances for multiple


addresses in a single call
TL;DR a slick contract and NPM package for efficient and fast balance checks. Scroll
to the bottom to try it out and find the package.

A common task that has plagued wallet providers and block explorers since ERC20
tokens came out is fetching all of the value associated with a single address. With
tokens included, you need to both call eth_getBalance , as well as balanceOf for each
token. But what if I told you we could bundle those into a single call, and not just for a

https://medium.com/@wbobeirne/get-all-eth-token-balances-for-multiple-addresses-in-a-single-node-call-4d0bcd1e5625 1/5
2/12/23, 3:59 PM Get ETH & ERC20 token balances for multiple addresses in a single call | by William O'Beirne | Medium

single address, but as many addresses as we want? And you can do so without having to
run custom software, since it works on any Ethereum node? Let me explain.

Credits for this method go to DeltaBalances for the idea & Henry Nguyen for the final implementation

At ETHSanFrancisco this year, myself and a team of 3 others put together a chrome
extension that keeps track of your addresses called Safu. One of the key features of the
extension was it needed to to check all of the balances of all of your addresses, and
fast.

Most applications’ approach for doing this so far has usually been to fire off dozens or
hundreds of requests to a node, and fill in the balances as they come back. The more
speed conscious developers may have even utilized JSON RPC’s batch spec, seeing as
all of the main Ethereum clients support it. But that still wasn’t good enough for Safu,
since we wanted to be showing all balances for multiple addresses at once, and we
wanted it fast.

An underused trick to do this much faster, and much more efficiently is by using a
smart contract. Most people only think of using smart contracts for their ability to
store data, and handling the permissions around who can store and remove what. But
you can actually make read-only contracts that perform useful functions for you that
are completely stateless. So that’s exactly what we’ve got, a smart contract that fetches

https://medium.com/@wbobeirne/get-all-eth-token-balances-for-multiple-addresses-in-a-single-node-call-4d0bcd1e5625 2/5
2/12/23, 3:59 PM Get ETH & ERC20 token balances for multiple addresses in a single call | by William O'Beirne | Medium

all of the desired balances for us. This is considerably faster, as we don’t have to waste
time with HTTP round trips and clogging up a node’s available connections & threads.
It’s all done internally in the EVM in one go. Here’s a comparison of the network
requests between the old multi-request way, and the new contract way:

0.00 s SD

18 1K i
On the left, MyCrypto’s balance checker. On the right, our single contract request.

The code for this contract is deceptively simple. You simply have an array that, as you
loop over every address and desired token, you append balances to it. The main
function of it is embedded below, but you can find the full source code here.

/*
Check the token balances of a wallet for multiple tokens.
Pass 0x0 as a "token" address to get ETH balance.

Possible error throws:


- extremely large arrays for user and or tokens (gas cost too high)

Returns a one-dimensional that's user.length * tokens.length long. The


array is ordered by all of the 0th users token balances, then the 1th
user, and so on.
*/
function balances(address[] users, address[] tokens) external view returns (uint[]) {
uint[] memory addrBalances = new uint[](tokens.length * users.length);

for(uint i = 0; i < users.length; i++) {


for (uint j = 0; j < tokens.length; j++) {
uint addrIdx = j + tokens.length * i;
if (tokens[j] != address(0x0)) {
addrBalances[addrIdx] = tokenBalance(users[i], tokens[j]);
} else {
addrBalances[addrIdx] = users[i].balance; // ETH balance
}
}
}
https://medium.com/@wbobeirne/get-all-eth-token-balances-for-multiple-addresses-in-a-single-node-call-4d0bcd1e5625 3/5
2/12/23, 3:59 PM Get ETH & ERC20 token balances for multiple addresses in a single call | by William O'Beirne | Medium
}
You can find the full contract code here.
return addrBalances;
}
Demo & NPM Package
You can see a demo of it in action here. It’s using the contract above, wrapped in a
handy web3.js & ethers.js compatible library that handles some of the input and
output trickiness.

You can find the NPM package that powers the demo here, complete with code
samples. The library also defaults to using a contract that’s already been deployed on
mainnet, so there’s no need for you to deploy the contract yourself to get started using
this today. It’s as simple as installing the package, and using one of two functions:

1 import Web3 from 'web3';


2 import { getAddressesBalances } from 'eth-balance-checker/lib/web3';
3
4 const web3 = new Web3(...);
5 const addresses = ['0x123...', '0x456...'];
6 const tokens = ['0x0', '0x789...'];
7
8 getAddressesBalances(web3, addresses, tokens).then(balances => {
9 console.log(balances); // { "0x123...": { "0x0": "100", ... }, ... }
10 });

balance.ts hosted with ❤ by GitHub view raw

Check the readme in the package for more information.

…But There’s Always a Catch


There is an unexpected issue with using smart contracts as functions though, and
that’s the block gas limit. Despite the fact that we’re making a read-only call that
doesn’t require a transaction, the block gas limit is still taken into account, and calls
that would exceed the limit of a single block get rejected.

The current block gas limit is around 8 million, and this function uses approximately
500,000 gas per 100 balances. So you should limit yourself to around 1,000 total balance
calls (addresses * tokens) per contract method call to be safe. Even if you split balance

https://medium.com/@wbobeirne/get-all-eth-token-balances-for-multiple-addresses-in-a-single-node-call-4d0bcd1e5625 4/5
2/12/23, 3:59 PM Get ETH & ERC20 token balances for multiple addresses in a single call | by William O'Beirne | Medium

checks into a few calls using this contract method, you’ll still be getting incredible time
savings over splitting thousands of calls.

Special thanks to Aaron (Github), Henry (Github), and Daniel (Github, Twitter) for helping
put together the Safu extension. Thanks to DeltaBalances for the original single-address
balance contract implementation.

Sometimes my Twitter and Github accounts have stuff worth looking at too.

Open in app Get unlimited access

Search Medium

Ethereum Blockchain Dapps Cryptocurrency Bitcoin

https://medium.com/@wbobeirne/get-all-eth-token-balances-for-multiple-addresses-in-a-single-node-call-4d0bcd1e5625 5/5
2/12/23, 4:00 PM Creating a Smart Contract that Returns Address and Balance of Owner using Solidity - GeeksforGeeks

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+

Creating a Smart Contract that Returns


Address and Balance of Owner using Solidity
Difficulty Level : Medium ● Last Updated : 11 May, 2022

Read Discuss Courses Practice Video

Problem: Create a smar t contract named MyContract having a state variable as owner.

Create a constructor to fetch the address of the owner from msg and hold it into the state

variable owner. Also, create a function getBalance() to show the current balance of the

owner.

Solution: Ever y smar t contract is owned by an address called as owner. A smar t contract

can know its owner ’s address using sender proper ty and its available balance using a

special built-in object called msg.

Step 1: Open Remix-IDE.

Step 2: Select File Explorer from the lef t side icons and select Solidity in the

environment. Click on New option below the Solidity environment. Enter the file name as

MyContract.sol and Click on the OK button.

Start Your Coding Journey Now! Login Register


https://www.geeksforgeeks.org/creating-a-smart-contract-that-returns-address-and-balance-of-owner-using-solidity/ 1/7
2/12/23, 4:00 PM Creating a Smart Contract that Returns Address and Balance of Owner using Solidity - GeeksforGeeks

Step 3: Enter the following Solidity Code.

Solidity

// Solidity program to
// retrieve address and
// balance of owner
pragma solidity ^0.6.8;     
  
// Creating a contract
Start Your Coding Journey Now!
contract MyContract
{
https://www.geeksforgeeks.org/creating-a-smart-contract-that-returns-address-and-balance-of-owner-using-solidity/ 2/7
2/12/23, 4:00 PM Creating a Smart Contract that Returns Address and Balance of Owner using Solidity - GeeksforGeeks

    // Private state variable


    address private owner;
  
     // Defining a constructor   
     constructor() public{   
        owner=msg.sender;
    }
  
    // Function to get 
    // address of owner
    function getOwner(
    ) public view returns (address) {    
        return owner;
    }
  
    // Function to return 
    // current balance of owner
    function getBalance(
    ) public view returns(uint256){
        return owner.balance;
    }
}

Step 4:  Compile the file MyContract.sol from the Solidity Compiler tab. 

Step 5: Deploy the smar t contract from the Deploy and Run Transaction tab and you will

get the balance and address of the owner.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/creating-a-smart-contract-that-returns-address-and-balance-of-owner-using-solidity/ 3/7
2/12/23, 4:00 PM Creating a Smart Contract that Returns Address and Balance of Owner using Solidity - GeeksforGeeks

Step 6: The output below shows the address and the balance of the owner.

Start Your Coding Journey Now!


Like 10

https://www.geeksforgeeks.org/creating-a-smart-contract-that-returns-address-and-balance-of-owner-using-solidity/ 4/7
2/12/23, 4:00 PM Creating a Smart Contract that Returns Address and Balance of Owner using Solidity - GeeksforGeeks

Previous Next

Related Articles

1. Steps to Execute Solidity Smart Contract using Remix IDE

2. What is Smart Contract in Solidity?

3. Solidity - Deploy a Smart Contract for Marks Management System

4. How to use MetaMask to Deploy a Smart contract in Solidity (Blockchain)?

5. How to use GANACHE Truffle Suite to Deploy a Smart Contract in Solidity


(Blockchain)?

6. Interacting With Ethereum Smart Contract Using Web3js

7. Deploying Smart Contract on Test/Main Network Using Truffle

8. Deploy a Smart Contract on Ethereum with Python, Truffle and web3py

9. Solidity - Abstract Contract

10. What is Escrow Smart Contract?

Ar ticle Contributed By :

muskan02
@muskan02
Start Your Coding Journey Now!
https://www.geeksforgeeks.org/creating-a-smart-contract-that-returns-address-and-balance-of-owner-using-solidity/ 5/7
2/12/23, 4:00 PM Creating a Smart Contract that Returns Address and Balance of Owner using Solidity - GeeksforGeeks

Vote for difficulty

Current difficulty : Medium

Easy Normal Medium Hard Expert

Article Tags : Blockchain, Solidity

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Advertise with us Video Tutorials
Courses

News Languages
Start Your Coding
Top News
Journey Now! Python
https://www.geeksforgeeks.org/creating-a-smart-contract-that-returns-address-and-balance-of-owner-using-solidity/ 6/7
2/12/23, 4:00 PM Creating a Smart Contract that Returns Address and Balance of Owner using Solidity - GeeksforGeeks

Technology Java
Work & Career CPP
Business Golang
Finance C#
Lifestyle SQL
Knowledge Kotlin

Web Development Contribute


Web Tutorials Write an Article
Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/creating-a-smart-contract-that-returns-address-and-balance-of-owner-using-solidity/ 7/7
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

Published in Coinmonks

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Jean Cvllr Follow

Feb 23, 2021 · 8 min read · · Listen

Save

Solidity Tutorial: all about Modifiers

Modifiers are analog to the decorator pattern (source: https://refactoring.guru/design-patterns/decorator)

In Solidity, Modifiers express what actions are occurring in a declarative and readable
manner. They are similar to the decorator pattern used in Object Oriented
Programming.

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 1/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

What is exactly a Modifier in Solidity ?


The Solidity documentation define a modifier as follow:

A function modifier is a compile-time source code roll-


up.

It can be used to amend the semantics of functions in


a declarative way.
From this definition, we can understand that a modifier aims to change the behaviour
of the function to which it is attached.

For instance, automatically checking a condition prior to executing the function (this
is mainly what they are used for).

Modifiers are useful because they reduce code redundancy. You can re-use the same
modifier in multiple functions if you are checking for the same condition over your
smart contract.

When to use a modifier in Solidity?


The main use case of modifiers is for automatically checking a condition, prior to
executing a function. If the function does not meet the modifier requirement, an
exception is thrown, and the function execution stops.

How to create and use Modifiers ?


Modifiers can be created (declared) as follow:

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 2/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

modifier MyModifier {
// modifier code goes here...
}

You can write a modifier with or without arguments. If the modifier does not have
argument, you can omit the parentheses () .

modifier ModifierWithArguments(uint a) {
// ...
}
modifier ModifierWithoutArguments() {
// ...
}
modifier ModifierWithoutArguments {
// ...
}

How do modifiers work?


Let’s start with some basic examples below.

modifier onlyOwner {
require(msg.sender == owner);
_;
}

The _; symbol
The symbol _; is called a merge wildcard. It merges the function code with the
modifier code where the _; is placed. (give example in code).

In other terms, the body of the function (to which the modifier is attached to) will be
inserted where the special symbol _; appears in the modifier’s definition.

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 3/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

Using the terms of the Solidity docs, it “returns the flow of execution to the original
function code”.

A modifier must have the symbol _; within its body in order to execute. It is
mandatory (does Solidity throw an error if it is not the case?).

Where to place the _; ?


The place where you write the _; symbol will decide if the function has to be executed
before, in between or after the modifier code.

modifier SomethingBefore {
require(/* check something first */);
_; // resume with function execution
}
// Do one where modifier is placed in the middle
modifier SomethingAfter {
_; // run function first
require(/* then check something */)
}

As shown in the example above, you can place the _; at the beginning, middle or the
end of your modifier body.

In practice, (especially until you understand how modifiers work really well), the safest
usage pattern is to place the _; at the end. In this scenario, the modifier serves for
consistent validation check, so to check a condition upfront and then carry on. The
code snippet below show show this as example:

function isOkay() public view returns(bool) {


// do some validation checking
return true;
}
function isAuthorised(address _user) public view returns(bool) {
// logic that checks that _user is authorised
return true;
}

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 4/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

modifier OnlyIfOkAndAuthorised {
require(isOkay());
require(isAuthorised(msg.sender));
_;
}

NB: return true are just placeholder for more meaningful results.

Passing arguments to Modifiers.


Modifiers can also accept arguments. Like a function, you just have to pass the variable
type + name between parentheses in front of the modifier name.

modifier Fee (uint _fee) {


if (msg.value >= _fee) {
_;
}
}

Using the example above, you can ensure that a user (or contract) that call one of your
contract function has sent some ethers to pay a pre-required fee.

Let’s illustrate with a simple example of a contract that acts like a vault.

You want to ensure that every user that want to take out money stored in the contract
vault pays a minimum fee of 2.5 % of an ether to the contract.

A modifier with arguments can simulate this behaviour. See the code below.

pragma solidity ^0.8.0;


contract Vault {

modifier fee(uint _fee) {


if (msg.value != _fee) {
revert("You must pay a fee to withdraw your ethers");
} else {
https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 5/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

_;
}
}

function deposit(address _user, uint _amount) external {


// ...
}

function withdraw(uint _amount) external payable fee(0.025 ether)


{
// ...
}
}

An other example is to check for instance that it is not a specific address that is calling
the function.

modifier notSpecificAddress (address _user) {


if (_user === msg.sender) throw;
_;
}
function someFunction(address _user) notSpecificAddress("0x......") {
// ...
}

See other examples on CryptoZombie, chapter 8 and 9.

Look at the modifier nonReentrant from Open Zeppelin.

Can find more practical use cases below on how to use arguments in modifiers.

Arbitrary expressions are allowed for modifier arguments and in this context, all
symbols visibles from the function are visible in the modifier.

Applying multiple Modifiers to a function.


Multiple modifiers can be applied to a function. You can do this as follow:

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 6/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

contract OwnerContract {
address public owner = msg.sender;
uint public creationTime = now;
modifier onlyBy(address _account) {
require(
msg.sender == _account,
"Sender not authorized.
);
_;
}
modifier onlyAfter(uint _time) {
require(
now >= _time,
"Function called too early."
);
_;
}
function disown() public onlyBy(owner) onlyAfter(creationTime + 6
weeks) {
delete owner;
}
}

The modifiers will be executed in the order they are defined, so from left to right. So in
the example above, the function will check the following conditions prior to run:

1. onlyBy(...) : is the address calling the contract the owner ?

2. onlyAfter(...) : Is there more than 6 weeks that the person has been the owner ?

Modifier Overriding
Like functions, modifiers defined in one contract can be overriden by other contracts
that derive from it. As the Solidity documentation suggest:

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 7/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

Modifiers are inheritable properties of contracts and


may be overridden by derived contracts.
Therefore, symbols introduced in a modifier are not visible in the function (because
the modifier might change if it is overridden in the derived contract).

Modifiers with Enums


If you contract holds a global variable of type enum, you can check the value it holds
by passing one of the available option as an argument to the modifier.

enum State { Created, Locked, Inactive }


State state;
modifier isState(State _expectedState) {
require(state == _expectedState);
_;
}

Modifiers in Practice
The following section describes some practical use cases for using modifiers.

Only owner, or specific users


A good example is given on the Colony blog. It demonstrates how to use a modifier to
check that a function can be called and executed only by a specific address.

modifier OnlyBy(address _account) {


require(msg.sender == _account, “sender not authorised”);
_;
}

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 8/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

Support Multiple Admins


The article “Writing robust smart contracts in Solidity” gives an other example that
extends from the previous one. Instead of allowing one user, we can support multiple
specific users to run a function.

Make the contract state discoverable to specific conditions


You can use modifiers in conjunction with getter functions.

For instance, view functions that should be guarded by a certain combination of


concerns can use the modifier

The idea is that clients, other contracts and other internal functions can use the getter
function to fetch / check the individual concerns (if they want to).

As a result, the logic of it all (and your intent) remains very clear to reviewers.

The example above enables to keep the code organised while making the state
discoverable to clients and ensure potentially that a complex logic is consistently
applied.

You can then have several functions like above which have some tricky steps.
Hopefully, they can be understood as individual concerns. Then when used in
combination, you can reduce repetition and improve readability with a modifier.

Data Validation
An other excellent use case for modifiers is to verify data inputs.

Below are some examples, based on different data types.

modifier throwIfAddressIsInvalid(address _target) {


if (_target == 0x0) throw;
_;
}
modifier throwIfIsEmptyString(string _id) {
if (bytes(_id).length == 0) throw;
_;
}

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 9/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

modifier throwIfEqualToZero(uint _id) {


if (_id == 0) throw;
_:
}
modifier throwIfIsEmptyBytes32(bytes32 _id) {
if (_id == "") throw;
_:
}

Check that some time (=blocks) has passed

modifier OnlyAfter(uint _time) {


require(now >= _time, "function called too early!");
_;
}

Refund Ether sent by Accident


The blockchain world does not allow for mistakes. For any ethers or other form of
value sent by accident, there is no clerk to turn to for a claim, as there is no bank or
central authority that monitor transactions.

However, you can make your smart contract to act like a good cashier, by noticing him
what to do when accidents happen on the end-user.

modifier refundEtherSentByAccident() {
if(msg.value > 0) throw;
_;
}

Charge a fee
On the other end, your smart contract can reinforce payments, by ensuring for
instance that a specific fee has been paid in order to perform an operation.

Modifier Fee (uint _fee) {


if (msg.value >= _fee) {
_;
https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 10/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

}
}

Send Change Back


We saw before how a modifier could be used to refund ethers sent by accident. But
how about the case where you send more than you should?

Some code snippet from the Solidity documentation provides good examples on how
to do this.

An example of the implementation would look like this.

modifier GiveChangeBack(uint _amount) {


_;
if (msg.value > _amount) {
msg.sender.transfer(msg.value - _amount);
}
}

Switch between states


Modifier can be used for complex design patterns. This include the state machine
pattern.

Prevent Re-Entrancy
Look at the modifier nonReentrant from OpenZeppelin
https://docs.soliditylang.org/en/v0.5.3/contracts.html#function-modifiers

Restrict to Users / Disallow contracts to interact


SUSHISWAP gives an excellent example of a modifier that enables only externally
owned accounts (= users) to claim their rewards on their contract.

As a result, this prevent other smart contracts to call the specific function the modifier
is attached to.

modifier onlyEOA() {
require(msg.sender == tx.origin, "Must use EOA");
https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 11/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

_;
}

only Humans
This modifier complements the previous one, which checked if it was an Externally
Owned Account (EOA). It checks at the caller address that no code is present, using the
opcode extcodesize(…) opcode via assembly

This code was taken from the Youtube video describing the Acoraida Monica contract
challenge.

modifier onlyHuman {
uint size;
address addr = msg.sender;
assembly { size := extcodesize(addr) }
require(size == 0, “only humans allowed! (code present at caller
address)”);
_;
}

Security Consideration about modifiers


Modifiers could have dangerous in the previous versions of Solidity.

Before Solidity version 0.4.0, it was possible to skip the part after _;

Join Coinmonks Telegram Channel and Youtube


Channel get daily Crypto News
Also, Read
Copy Trading | Crypto Tax Software

Grid Trading | Crypto Hardware Wallet

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 12/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

Crypto Telegram Signals | Crypto Trading Bot

Pionex Dual Investment | AdvCash Review | Uphold Review

8 Best Cryptocurrency APIs for Developers

Uphold Card Review | Trust Wallet vs MetaMask

Earn Sign-up Bonus — 10 Best Crypto Platforms

Best Crypto Exchange | Best Crypto Exchange in India

Best Crypto APIs for Developers

Best Crypto Lending Platform

An ultimate guide to Leveraged Token

Solidity Ethereum Smart Contracts Blockchain Dapps

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Your email

Get this newsletter

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 13/14
2/12/23, 4:03 PM Solidity Tutorial: all about Modifiers | by Jean Cvllr | Coinmonks | Medium

About Help Terms Privacy

Open in app Sign up Sign In

Get the Medium app


Search Medium

https://medium.com/coinmonks/solidity-tutorial-all-about-modifiers-a86cf81c14cb 14/14
2/12/23, 4:05 PM Lesson 4: Solidity Functions and Function Modifiers | by Lajos Deme | Solidify | Medium

Published in Solidify

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Lajos Deme Follow

Feb 24, 2022 · 6 min read · · Listen

Save

Lesson 4: Solidity Functions and Function


Modifiers

https://medium.com/solidify/lesson-4-solidity-functions-and-function-modifiers-32b4b52d58b1 1/10
2/12/23, 4:05 PM Lesson 4: Solidity Functions and Function Modifiers | by Lajos Deme | Solidify | Medium

Photo by Michael Dziedzic on Unsplash

In the previous introductory lessons, we started to dip our toes into the world of
Solidity and reviewed a few basic concepts like reference and value types. Now we will
further progress on our journey, and take a look at solidity functions and function
modifiers.

Functions in Solidity take some typed inputs, and they produce an arbitrary number of
outputs, and they may or may not change state. Functions can differ by visibility or
whether they are state-changing or not. The next lesson is a deep dive into function
visibility, so here we will examine the other properties of Solidity functions.

Parameters are declared like variables, they can be used inside the function as local
variables, and they can also be assigned to. If you don’t use a parameter inside the
function you can drop the name of the parameter and only indicate the type.

https://medium.com/solidify/lesson-4-solidity-functions-and-function-modifiers-32b4b52d58b1 2/10
2/12/23, 4:05 PM Lesson 4: Solidity Functions and Function Modifiers | by Lajos Deme | Solidify | Medium

As stated, you can return multiple values using the returns keyword, followed by the
type and name of the return values.

An example function declaration in Solidity looks like this:

function myFunction(uint256 one, uint256 two) external pure returns


(bool success, uint256 res) {
return (true, one + two);
}

We can rewrite this function without the return statement by explicitly assigning to the
return values:

function myFunction(uint256 one, uint256 two) external pure returns


(bool success, uint256 res) {
success = true;
res = one + two;
}

This function takes two uint256 values as inputs, and returns a bool and a uint256 .

How functions handle state


When it comes to how functions handle state, we can differentiate between three types
of functions.

We can talk about state-changing functions, view functions, and pure functions.

Before we examine each one, let’s determine what counts as modifying the state.

According to the Solidity docs, the following statements are considered changing the
state:

1. writing to state variables

2. emitting events

3. creating other contracts


https://medium.com/solidify/lesson-4-solidity-functions-and-function-modifiers-32b4b52d58b1 3/10
2/12/23, 4:05 PM Lesson 4: Solidity Functions and Function Modifiers | by Lajos Deme | Solidify | Medium

4. using selfdestruct

5. sending Ether via calls

6. calling any function not marked view or pure

7. using low-level calls

8. using inline assembly that contains certain opcodes

According to the docs, the following statements are considered (in addition to the
above) reading from the state:

1. reading from state variables

2. accessing address(this).balance or the balance of another address

3. accessing any of the members of block , tx , msg (excluding msg.sig and msg.data )

4. calling any function not marked as pure

5. using inline assembly that contains certain opcodes

Later in this series, we will go deep into each of these state-changing and state-reading
statements, for now, it’s enough to have a birds-eye view of what they are.

State-changing functions
The first one is a function that changes the state. We don’t use any special keyword
here, this is the default.

In the simplest form, the declaration looks like this (this function is marked as
external , but in terms of being able to change state, the visibility doesn’t matter):

function changeState() external { }

View functions

https://medium.com/solidify/lesson-4-solidity-functions-and-function-modifiers-32b4b52d58b1 4/10
2/12/23, 4:05 PM Lesson 4: Solidity Functions and Function Modifiers | by Lajos Deme | Solidify | Medium

If a function is marked as view it can only read from the state but is not able to modify
it.

Here is a simple example of a contract with a view function. As you can see it reads
from the state, but does not modify it:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Example {
uint256 public a = 3;
function f() public view returns (uint256) {
return a * block.timestamp;
}
}

For public variables Solidity auto-generates view functions, so for example, if we


deployed the above contract, we could call a() to get the value 3.

Pure functions
Pure functions on the other hand neither read from nor modify the state. What results
from this is that it should be possible to evaluate a pure function at compile time given
only its inputs and msg.data but no access to the blockchain state.

An example of a pure function:

function f(uint256 a, uint256 b) public pure returns (uint256) {


return a * b;
}

The special receive function


This special function is for receiving ether. It can be declared only once per contract,
and its declaration is also different from regular functions. It looks like this:

https://medium.com/solidify/lesson-4-solidity-functions-and-function-modifiers-32b4b52d58b1 5/10
2/12/23, 4:05 PM Lesson 4: Solidity Functions and Function Modifiers | by Lajos Deme | Solidify | Medium

receive() exernal payable { }

As you can see, we don’t use the function keyword, we mark the function as external

and payable . It can not have arguments, must not return anything, but can be virtual

and can have modifiers (more on these later).

This function is called whenever

a call is made to the contract with empty calldata

the send or transfer functions are called

The special fallback function


The special fallback function is executed on a contract if no other functions match the
function signature, or there is no receive ether function.

Just like with receive , a contract can have only one fallback function. It is also
declared without the a function keyword. There are actually two ways to declare
the fallback function:

fallback() exernal [payable] { }

or:

fallback(bytes calldata _input) exernal [payable] returns (bytes


memory _output) { }

We can see that in both cases we have external visibility and we can make it
optionally payable . In the second case, we also provide some data as input and output
something as the result of the function.

If there is no receive function, and the fallback is marked as payable , the


fallback will be called if ether is sent to the contract.
https://medium.com/solidify/lesson-4-solidity-functions-and-function-modifiers-32b4b52d58b1 6/10
2/12/23, 4:05 PM Lesson 4: Solidity Functions and Function Modifiers | by Lajos Deme | Solidify | Medium

Function overloading
Function overloading means having two functions with the same name in a contract,
but with different parameter types.

function f(uint256 a) public pure returns(uint256) {


return 2 * a;
}
function f(uint256 a, uint256 b) public pure returns(uint) {
return a * b;
}

Function modifiers
Function modifiers are reusable code that can be attached to a function. As you might
have guessed from the name, they modify the behavior of a function.

This reusable code can be executed either before or after the function is run.

The most common way to use modifiers is to check a condition prior to executing the
function. Modifiers are inheritable and can be overridden by derived contracts. They
are declared by using the modifier keyword.

This topic is the perfect place to start getting familiar with the Open Zeppelin smart
contract suite, so we will examine one of the most widely used contracts there, called
Ownable . This contract is about restricting access to certain functions to the contract
owner and prohibiting anyone else to call the function. This is achieved via a modifier.

Let’s take a look at the relevant part of the code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address
indexed newOwner);

https://medium.com/solidify/lesson-4-solidity-functions-and-function-modifiers-32b4b52d58b1 7/10
2/12/23, 4:05 PM Lesson 4: Solidity Functions and Function Modifiers | by Lajos Deme | Solidify | Medium

constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}

modifier onlyOwner() {
require(owner() == _msgSender(),
"Ownable: caller is not the owner");
_;
}
function _transferOwnership(address newOwner) internal virtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}

The goal of the contract is pretty clear from the code, it sets an owner and checks in
the modifier that the caller is the owner. Now let’s examine what’s going on in the
modifier.

We declare a modifier called onlyOwner that checks if the owner is the same as the
caller, then executes the rest of the function.

The _ is responsible for executing the rest of the function. You usually put it after the
checks like above, but there is nothing holding you back from sandwitching the _
between code and executing some code before and after the function.

Function modifiers can also take parameters, just like this:

modifier validAddress(address _addr) {


require(_addr != address(0), "Address is not valid";
_;
}

The way you call a function modifier is by specifying it in the function signature.

https://medium.com/solidify/lesson-4-solidity-functions-and-function-modifiers-32b4b52d58b1 8/10
2/12/23, 4:05 PM Lesson 4: Solidity Functions and Function Modifiers | by Lajos Deme | Solidify | Medium

function f(address _addr) external onlyOwner validAddress(_addr) { }

Modifiers are very useful, they are employed in almost all smart contracts, and they
make the code cleaner, more readable, and free from repetitions.

Conclusion
In this lesson, we looked at functions and function modifiers in Solidity.

Thank you for staying with us till the end. If you enjoyed reading this piece please keep
in touch and follow Solidify to keep up with our lessons on Solidity. In the upcoming
articles, we will deep dive into the intricacies of the language, progressing from
beginner to advanced level.

If you are new, please consider checking out the previous lessons.

Lesson 3: Reference Types in Solidity


Introduction to reference types
medium.com

Lesson 2: Value Types in Solidity


Introduction to value types
medium.com

Lesson 1: Your First Solidity Smart Contract


In the previous lesson, we looked at how to set up your local Solidity
development environment. Here we will continue…
medium.com

https://medium.com/solidify/lesson-4-solidity-functions-and-function-modifiers-32b4b52d58b1 9/10
2/12/23, 4:05 PM Lesson 4: Solidity Functions and Function Modifiers | by Lajos Deme | Solidify | Medium

How to Setup Your Local Solidity Development Environment


Get started with smart contract development
medium.com

Solidity Smart Contracts Blockchain Ethereum Programming

Open in app Sign up Sign In

Search Medium

About Help Terms Privacy

Get the Medium app

https://medium.com/solidify/lesson-4-solidity-functions-and-function-modifiers-32b4b52d58b1 10/10
2/12/23, 4:06 PM Solidity - Basics of Contracts - GeeksforGeeks

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+

Solidity – Basics of Contracts


Difficulty Level : Easy ● Last Updated : 11 May, 2022

Read Discuss Courses Practice Video

Solidity Contracts are like a class in any other object-oriented programming language.

They firmly contain data as state variables and functions which can modif y these

variables. When a function is called on a different instance (contract), the E VM function

call happens and the context is switched in such a way that the state variables are

inaccessible. A contract or its function needs to be called for anything to happen. Some

basic proper ties of contracts are as follows :

Constructor: Special method created using the constructor keyword, which is

invoked only once when the contract is created.

State Variables : These are the variables that are used to store the state of the

contract.

Functions : Functions are used to manipulate the state of the contracts by modif ying

the state variables.

Creating a Contract

Creating contracts programmatically is generally done by using JavaScript API web3.js,

which has a built-in function web3.eth.Contract to create the contracts. When a contract

is created its constructor is executed, a constructor is an optional special method

defined by using the constructor keyword which executes one per contract. Once the

constructor is called the final code of the contract is added to the blockchain.

Syntax :

Start Your Coding Journey Now! Login Register


https://www.geeksforgeeks.org/solidity-basics-of-contracts/ 1/9
2/12/23, 4:06 PM Solidity - Basics of Contracts - GeeksforGeeks

contract <contract_name>{

constructor() <visibility>{
.......
}
// rest code
}

Example : In the below example, the contract Test is created to demonstrate how to

create a contract in Solidity.

Solidity

// Solidity program to demonstrate 


// how to create a contract
pragma solidity ^0.4.23;
  
// Creating a contract
contract Test {
    
  // Declaring variable
  string str;
   
  // Defining a constructor
  constructor(string str_in){
      str = str_in;
  }
Start Your Coding Journey Now!
  
  // Defining a function to 
https://www.geeksforgeeks.org/solidity-basics-of-contracts/ 2/9
2/12/23, 4:06 PM Solidity - Basics of Contracts - GeeksforGeeks

  // return value of variable 'str'


  function str_out(
  ) public view returns(string memory){
      return str;
  }
}

Output : 

Visibility Modifiers

Solidity provides four types of visibilities for functions and state variables. Functions

have to specified by any of the four visibilities but for state variables external is not

Start Your Coding Journey Now!


allowed. 

https://www.geeksforgeeks.org/solidity-basics-of-contracts/ 3/9
2/12/23, 4:06 PM Solidity - Basics of Contracts - GeeksforGeeks

1. External: External functions are can be called by other contracts via transactions. An

external function cannot be called internally. For calling an external function within

the contract this.function_name() method is used. Sometimes external functions are

more efficient when they have large arrays of data.

2. Public : Public functions or variables can be called both externally or internally via

messages. For public static variables, a getter method is created automatically in

solidity.

3. Internal: These functions or variables can be accessed only internally i.e. within the

contract or the derived contracts.

4. Private : These functions or variables can only be visible for the contracts in which

they are defined. They are not accessible to derived contracts also.

Example : In the below example, the contract contract_example is created to

demonstrate different visibility modifiers discussed above.

Solidity

// Solidity program to demonstrate 


// visibility modifiers
pragma solidity ^0.5.0;
  
// Creating a contract
contract contract_example {
  
   // Declaring private 
   // state variable
   uint private num1;
     
   // Declaring public 
   // state variable
   uint public num2;
  
  // Declaring Internal 
  // state variable
   string internal str;
  
   // Defining a constructor
   constructor() public {
      num2 = 10;
   }
  
   // Defining a private function
Start Your Coding Journey Now!
   function increment(

https://www.geeksforgeeks.org/solidity-basics-of-contracts/ 4/9
2/12/23, 4:06 PM Solidity - Basics of Contracts - GeeksforGeeks

     uint data1) private pure returns(


     uint) { return data1 + 1; }
     
   // Defining public functions
   function updateValue(
     uint data1) public { num1 = data1; }
   function getValue(
   ) public view returns(
     uint) { return num1; }
  
   // Declaring public functions
   function setStr(
     string memory _str) public;
   function getStr(
   ) public returns (string memory);
 }
  
   // Child contract inheriting 
   // from the parent contract
   // 'contract_example'
   contract derived_contract is contract_example{
  
   // Defining public function of 
   // parent contract
   function setStr(
     string memory _str) public{
   str = _str;
   }
  
  // Defining public function 
  // of parent contract   
  function getStr(
  ) public returns (
    string memory){ return str; }
}
  
//External Contract
contract D {
  
   // Defining a public function to create 
   // an object of child contract access the
   // functions from child and parent contract
   function readData(
   ) public payable returns(
     string memory, uint) {
      contract_example c 
        = new derived_contract();
     c.setStr("GeeksForGeeks");

Start Your Coding Journey Now!


      c.updateValue(16);         
      return (c.getStr(), c.getValue());
https://www.geeksforgeeks.org/solidity-basics-of-contracts/ 5/9
2/12/23, 4:06 PM Solidity - Basics of Contracts - GeeksforGeeks

   }
}

Output : 

Like 4

Next

Introduction to Solidity

Related Articles
Start Your Coding Journey Now!
https://www.geeksforgeeks.org/solidity-basics-of-contracts/ 6/9
2/12/23, 4:06 PM Solidity - Basics of Contracts - GeeksforGeeks

1. Creating Ownable Contracts in Solidity

2. Solidity - Basics of Interface

3. Smart Contracts in Blockchain

4. Difference Between Dapps, Crypto Wallets and Smart Contracts

5. Smart Contracts and IoT

6. Timestamp Dependency in Smart Contracts

7. Overflow and Underflow Attacks on Smart Contracts

8. Reentrancy Attack in Smart Contracts

9. Solidity - Types

10. Solidity - Functions

Ar ticle Contributed By :

jeeteshgavande30
@jeeteshgavande30

Vote for difficulty

Current difficulty : Easy

Easy Normal Medium Hard Expert

Start Your Coding Journey Now!


Blockchain, Solidity
Article Tags :
https://www.geeksforgeeks.org/solidity-basics-of-contracts/ 7/9
2/12/23, 4:06 PM Solidity - Basics of Contracts - GeeksforGeeks

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Advertise with us Video Tutorials
Courses

News Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Start Your
WebCoding Journey Now!
Development Contribute
https://www.geeksforgeeks.org/solidity-basics-of-contracts/ 8/9
2/12/23, 4:06 PM Solidity - Basics of Contracts - GeeksforGeeks

Web Tutorials Write an Article


Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-basics-of-contracts/ 9/9
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

Published in Coinmonks

Blockchain Tech Follow

Sep 1, 2022 · 5 min read · Listen

Save

Complete Solidity Code Deployment Process

Solidity!
I guess many of you know, that Solidity is the programing language for Ethereum
smart contract development. If you are new to solidity, don’t worry, today we will be
having a complete solidity code development process as well as we will see how to
deploy a smart contract in solidity!

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 1/11
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

Great Saroj :)

What is Solidity
Solidity is a high-level statically typed programming language. With the help of this, we
can create smart contracts for uses such as voting, crowdfunding, blind auctions, and
multi-signature wallets. It is mostly used for Ethereum smart contract development.
Solidity is behave differently from any other programming language like Java,
Javascript, C++, etc. In this article, we will see how solidity smart contracts are written
and the deployment process.

But Saroj, where to write this solidity smart contract as you said, it behaves diff from other
programming languages? Like any IDE?

Great question! The best part is, to write solidity smart contracts we no need any
application or software in our local system. We can write directly in the browser. Just
hit %[remix.ethereum.org/] URL and Boom! You will see a workspace like the one
below.

In this window, you can see some examples of smart contracts. To create a new file just
click on the new file icon.

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 2/11
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

Now, let’s write a solidity contract to check whether a particular age can vote or not.

//SPDX-License-Identifier: GPL-3.0
//we have to mention a version no the solidity
pragma solidity >= 0.5.0 < 0.9.0;
contract IfElse{
uint public age;
//function to set a new age
function setAge(uint newAge) public{
age = newAge;
}
//function to check whether the age is able to vote or not
function IsVotor() public view returns(string memory){
string memory voter;
if(age >= 18){
voter = "Can Vote";
}else{
voter = "Can't Vote";
}
return voter;
}
}

After writing the code, it will check for the compilation process. To know more about
the compilation process please check my previous article here

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 3/11
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

During the compilation process, we have to choose one solidity compiler version. Also,
make sure that the version is included in your contract code.

Let’s have an error and check what it looks like.

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 4/11
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

As you can see above, I removed the semicolon in line no. 12. Solidity compiler gives
an error and says, hey bro, please add a semicolon. Once we resolve all the errors, then
again we have to compile. We can also set auto-compile.

Once the compilation process gets successful, it will display a green tick mark on the
left side.

Then only we can move to the deployment process

Let’s deploy our smart contract!

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 5/11
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

To deploy the smart contract we have to choose a Remix VM(Virtual Machine). This is a
simple test smart contract, so we can choose from London or Berlin.

The next step is we have to assign an Ethereum account address to run the
deployment.

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 6/11
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

As you can see we have 100 ethers in each address, those are not real ethers, these are
only for testing and there are of no real value. Once we choose an address, we have to
set the Gas limit, which is used for deploying the smart contract on Ethereum VM.
Once we set it all, then we can click on the deploy button. And our contracts will be
deployed successfully. You can see the deployed contracts below.

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 7/11
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

Now time to test our smart contract!

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 8/11
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

Once successfully deployed we can test the smart contract. If you click the buttons it
will show the default value.

As you can see in the above image when I clicked the age, it is showing 0. and it shows
Can’t Vote for the function. Now let’s put some value in the setAge and test again.

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 9/11
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

Now we inserted 18 in the setAge, and if we click the age, now it will show 18. Also now
we can see Can Vote after clicking the function.

This is a small overview of the deployment process of the smart contract. I know this is
kind of confusing if you are new to solidity. But trust me, once you get into it, it will
more fun :) I hope you all love this article and enjoyed the reading. Don’t forget to try it
out.

Thanks, Saroj, this is a great demo. waiting for your next one.

See
Openyou
in appsoon with an awesome topic. Get unlimited access

New toSearch
trading?
Medium Try crypto trading bots or copy
trading

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 10/11
2/12/23, 4:10 PM Complete Solidity Code Deployment Process | by Blockchain Tech | Coinmonks | Medium

Blockchain Solidity Ethereum Smart Contracts Web 3

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/coinmonks/complete-solidity-code-deployment-process-f88be7913990 11/11
2/12/23, 4:12 PM An Introduction to Solidity and Remix 👾 | by gmchad.eth | Medium

gmchad.eth Follow

Jun 11, 2022 · 7 min read · Listen

Save

An Introduction to Solidity and Remix 👾


📚 Introduction
The quickest way to get started developing in solidity is with the Remix browser-based
IDE (integrated development environment).

https://remix.ethereum.org/

Remix has all the development tools needed to start writing solidity code, compiling
code (turning code into machine language), and deploying smart contracts onto the
Ethereum network.

https://medium.com/@ultrasoundchad/an-introduction-to-solidity-and-remix-91b710865934 1/10
2/12/23, 4:12 PM An Introduction to Solidity and Remix 👾 | by gmchad.eth | Medium

Let’s dive into some of the features Remix has to offer and try deploying a smart
contract.

🔮 Solidity
We’re going to start with the 1_Storage.sol smart contract found under the contacts
folder in the default workspace tab.

1_Storage.sol

Don’t worry if this is your first time looking at solidity or code for that matter, we’re
going to walk through this smart contract step by step.

Line 3: pragma solidity ≥0.7.0 <0.9.0; — All smart contracts start with this line which
serves to specify to the compiler which version of solidity this contract should target.
For this contract, we’re targeting versions greater or equal to 0.7.0 and less than 0.9.0.

Line 10: contract Storage {...} —All smart contracts must begin with the contract

keyword followed by the name of the contract. This contract is called Storage.

Line 12: uint256 number; — This is a variable that stores an unsigned integer up to 256
bits. An unsigned integer means a positive number with no decimal points. 256 bits

https://medium.com/@ultrasoundchad/an-introduction-to-solidity-and-remix-91b710865934 2/10
2/12/23, 4:12 PM An Introduction to Solidity and Remix 👾 | by gmchad.eth | Medium

represent how big this integer can be, in this case, the max size in solidity. To learn
more about bits and bytes here is a great article.

Line 18–20: function store(uint256 num) public { number = num } — These lines
represent a function that takes in one parameter, uint256 num , and sets the variable
number from Line 12 to that value. A function is a stored piece of code that can be
reused and called by other code and sometimes users of the smart contract. The
public tag indicates anyone outside of the contract can call this function, meaning you
or me.

Line 26–28: function retrieve() public view returns (uint256) { return number } —
You can probably guess that this function just returns the variable number . This
function is public view , which indicates it’s open for anyone to call and does not
modify any contract variables. In solidity, you also need to specify what a function
returns if it does so. In this case number is a uint256 so we specify that at the end of the
function signature.

Even though this is a very basic contract that simply stores and returns a number,
there are quite a few language features demonstrated. Let’s now compile and deploy
this contract.

🪄 Compilation

https://medium.com/@ultrasoundchad/an-introduction-to-solidity-and-remix-91b710865934 3/10
2/12/23, 4:12 PM An Introduction to Solidity and Remix 👾 | by gmchad.eth | Medium

Compiling a Contract

Head over to the third tab on the left-hand navigation bar and you should be presented
with the above screen. Compiling a contract is the process of turning human-readable
solidity code into Bytecode that the Ethereum Virtual Machine (EVM) can process. You
can think of the EVM as the distributed operating system of Ethereum. To learn more
you can jump into the rabbit hole here.

Make sure the Compiler version is set within the range specified by the pragma , 0.8.7
is fine. You also want to make sure the Contract chosen is Storage (1_Storage.sol) .
Sometimes when your contract depends on other contracts (this is called inheritance),
Remix has trouble figuring out which contract you want to deploy.

Once you have your parameters set, you can go ahead and click the blue compile
button and wait for the green checkmark to pop up. If there are issues, Remix will let
you know.

https://medium.com/@ultrasoundchad/an-introduction-to-solidity-and-remix-91b710865934 4/10
2/12/23, 4:12 PM An Introduction to Solidity and Remix 👾 | by gmchad.eth | Medium

ABI & Bytecode

You’ll notice on the bottom left that you can also copy the ABI and the Bytecode of the
compiled contract. ABI stands for Application Binary Interface and it’s a format that
other programs can use to understand how to interact with a specific contract. All
Dapps or decentralized applications use smart contract ABIs to connect frontend
applications to smart contracts.

Let’s take a look a the specific ABI of this contract.

https://medium.com/@ultrasoundchad/an-introduction-to-solidity-and-remix-91b710865934 5/10
2/12/23, 4:12 PM An Introduction to Solidity and Remix 👾 | by gmchad.eth | Medium

Contract ABI

The ABI is written in JSON (javascript object notation), a common format for
representing data in many programming languages. We won’t go into detail here, but
you’ll notice the common keywords between the smart contract and the ABI.

The key takeaway is that the ABI is used by other programs to interact with smart contracts.

We won’t take a look at the Bytecode here because it’s mostly gibberish and out of
scope for this article, but feel free to take a peek!

Let’s move on to deploying the contract and interacting with it on Remix!


https://medium.com/@ultrasoundchad/an-introduction-to-solidity-and-remix-91b710865934 6/10
2/12/23, 4:12 PM An Introduction to Solidity and Remix 👾 | by gmchad.eth | Medium

🚀 Deployment

Deploying a Contract

Head over to the fourth tab which is represented by the Ethereum symbol. Let’s go
over what each tab means.

Environment: This specifies where the contract will be deployed to. For this tutorial,
we will be using the Javascript VM, which is a virtual blockchain that is running in the
browser. It’s great for local testing but is not a real blockchain. The most common
other option is Injected Web3 , which will use your Metamask environment and real
accounts to deploy to a either test network or the Ethereum main network, commonly
called mainnet.

Account: This is the account from where the contract will be deployed. With the
Javascript VM, this is a test account that only lives in the browser. If you were to switch
to Injected Web3 , you would see the account your Metamask is currently targeting.

https://medium.com/@ultrasoundchad/an-introduction-to-solidity-and-remix-91b710865934 7/10
2/12/23, 4:12 PM An Introduction to Solidity and Remix 👾 | by gmchad.eth | Medium

Gas Limit: The max amount of gas you’re willing to spend to deploy the contract or
interact with a contract.

Value: Some smart contract functions require you to send ETH to them. An example of
this is minting functions for NFTs. You can select the amount to send in this tab here.
WEI is just a denomination of ETH, you can play around with the conversions here.

Contract: The contract you are targeting to deploy. In our case, this should be Storage

Lastly, the At Address button allows you to point Remix to a contract that’s already
deployed in the case where you would want to interact with a live contract from Remix.

Okay, we’re ready to deploy! Hit the orange Deploy button and it should show up under
the Deployed Contracts section.

🕹️Interaction

Interacting with a Contract

Once deployed, you can interact with a smart contract through Remix. Try specifying a
number and hitting the store button. You should see something happen under the
terminal tab.

https://medium.com/@ultrasoundchad/an-introduction-to-solidity-and-remix-91b710865934 8/10
2/12/23, 4:12 PM An Introduction to Solidity and Remix 👾 | by gmchad.eth | Medium

Terminal Tab

If you can’t see the terminal, there should be a pull-up tab at the bottom of the screen
you can use to bring it up. The terminal is where you can see the output of any
transaction you send, including the contract creation transaction. Some things to
notice from this transaction.

Transaction Hash: the unique id of the transaction

From: the account that executed the transaction

To: the contract address the transaction was sent to

Gas: the gas used by the contract

Decoded input: the data that was sent to the contract in the transaction. In our case
this was 10 , the number to be stored in the contract.

The last thing to do is retrieve the number from the contract. Go ahead and click the
retrieve button and you should see the number that you stored pop up!

An important takeaway is that retrieving data from a contract via an external account
doesn’t cost gas as long as there are no variables (state) being updated.

https://medium.com/@ultrasoundchad/an-introduction-to-solidity-and-remix-91b710865934 9/10
2/12/23, 4:12 PM An Introduction to Solidity and Remix 👾 | by gmchad.eth | Medium

Congrats! If you made it this far you’ve successfully walked through all the steps of
understanding, compiling, deploying, and interacting with a smart contract via the
Remix IDE!

If you want to challenge yourself, try going through the same steps with the
3_Ballot.sol contract except instead of using the Javascript VM network, try
deploying to a test network by using the injected web3 environment option during
deployment.

Hint: You’ll need to change your Metamask network to a testnet like rinkeby and
request some free rinkeby eth.

Tip: If you want to learn more about solidity when walking through 3_Ballot.sol ,
https://solidity-by-example.org/
Open in app is a great site to learn the language essentials.
Get unlimited access

Search Medium

If you liked this tutorial, feel free to follow me on Twitter


https://twitter.com/ultrasoundchad

Solidity Smart Contracts Remix Programming Ethereum

https://medium.com/@ultrasoundchad/an-introduction-to-solidity-and-remix-91b710865934 10/10
2/12/23, 4:14 PM Explaining Ethereum Contract ABI & EVM Bytecode | by eiki | Medium

eiki Follow

Jul 16, 2019 · 4 min read · Listen

Save

Explaining Ethereum Contract ABI & EVM


Bytecode
Explaining Ethereum Contract ABI and EVM Bytecode with theory and command-line
practice

Introduction
This article explains Contract ABI & EVM bytecode in Ethereum. As Ethereum uses
EVM(Ethereum Virtual Machine) as a heart of the system, smart contract code written
in high-level languages needs to be compiled into EVM bytecode and Contract ABI to
be run. It is necessary to understand them when you interact with the smart contract.

What you can get from this article


Understanding what Contract ABI and EVM bytecode are, and its relations.

How to generate Contract ABI & EVM bytecode with ’solc’ command-line

Not explained

Details of Contract ABI Specification(encode/decode).

How to write a smart contract

The basic explanation of Ethereum and blockchain

*Readers are expected to have basic knowledge of Ethereum and blockchain.

https://medium.com/@eiki1212/explaining-ethereum-contract-abi-evm-bytecode-6afa6e917c3b 1/9
2/12/23, 4:14 PM Explaining Ethereum Contract ABI & EVM Bytecode | by eiki | Medium

Bytecode & ABI


As Ethereum uses EVM(Ethereum Virtual Machine) as a core component of the
network, smart contract code written in high-level languages needs to be compiled
into EVM bytecode to be run. EMV Bytecode is an executable code on EVM and
Contract ABI is an interface to interact with EVM bytecode. For example, if you want to
call a function in a smart contract with your JavaScript code, ABI plays a role as an
intermediary between your JavaScript code and EVM bytecode to interact with each
other. Below diagram shows the architecture of Contract ABI, EVM bytecode and
outside components(dApp and network). The left side is a process of compiling and the
right side is interacting.

https://hackernoon.com/ethernaut-lvl-0-walkthrough-abis-web3-and-how-to-abuse-them-d92a8842d71b

EVM bytecode(Bytecode)
EVM bytecode is a low-level programming language which is compiled from a high-
level programming language such as solidity. EVM is a virtual machine which places
between OS and application layer to mitigate OS dependency. Thankfully to EVM,
Ethereum smart contract can be run on almost any of computers. If you are a Java
developer, you can think of JVM(Java Virtual Machine) as the same mechanism. EVM
bytecode looks like below. It is not human-readable but readable for the machine.
https://medium.com/@eiki1212/explaining-ethereum-contract-abi-evm-bytecode-6afa6e917c3b 2/9
2/12/23, 4:14 PM Explaining Ethereum Contract ABI & EVM Bytecode | by eiki | Medium

6080604052348015600f57600080fd5b5060878061001e6000396000f3fe6080604052
348015600f57600080fd5b506004361060285760003560e01c8063037a417c14602d57
5b600080fd5b60336049565b6040518082815260200191505060405180910390f35b60
00600190509056fea265627a7a7230582050d33093e20eb388eec760ca84ba30ec42da
dbdeb8edf5cd8b261e89b8d4279264736f6c634300050a0032

More deeply, when compiling on Remix IDE, you see four fields like below. They
represent more details of bytecode such as linkReference, opcodes, and source Map.
‘object’ is an EVM bytecode.

linkReference: deployed address of address of other smart contracts on


which the current smart contract has a dependency.
object: Current smart contract bytecode
opcodes: Operation codes that are human-readable low-level
instructions.
sourceMap: ource map is to match each contract instruction to the
section of the source code from which it was generated.

Contract ABI
In computer science, ABI(Application Binary Interface) is an interface between two
program modules; often, between an operating system and user programs. In
Ethereum, Contract ABI is an interface that defines a standard scheme of how to call
functions in a smart contract and get data back. Contract ABI is designed for external
use to enables application-to-contract and contract-to-contract interaction. For
example, if you want to call a smart contract function from your dApp, you call via
Contract ABI. Contract ABI is represented with JSON format like below.

https://medium.com/@eiki1212/explaining-ethereum-contract-abi-evm-bytecode-6afa6e917c3b 3/9
2/12/23, 4:14 PM Explaining Ethereum Contract ABI & EVM Bytecode | by eiki | Medium

1 [
2 {
3 "constant":true,
4 "inputs":[
5 ],
6 "name":"testFunc",
7 "outputs":[
8 {
9 "name":"",
10 "type":"int256"
11 }
12 ],
13 "payable":false,
14 "stateMutability":"pure",
15 "type":"function"
16 }
17 ]

contract_abi_sample.json hosted with ❤ by GitHub view raw

Contract ABI defines function names and argument data types. It is used to encode
contract calls for the EVM and to read data out of transactions. There is a clear
specification of how to encode and decode Contract ABI. I will use the below function
to describe the example of encoding.

function withdraw(uint withdraw_amount) public {}

First, “withdraw” function will be encoded with keccak256 and first 4 bytes are used as
a selector. the selector is a mark to be used to identify which function to call.

// Encode function with keccak256.


> web3.utils.sha3(“withdraw(uint256)”)
0x2e1a7d4d13322e7b96f9a57413e1525c250fb7a9021cf91d1540d5b69f16a49f
// Extract first 4 bytes.
0x2c1a7d4d

https://medium.com/@eiki1212/explaining-ethereum-contract-abi-evm-bytecode-6afa6e917c3b 4/9
2/12/23, 4:14 PM Explaining Ethereum Contract ABI & EVM Bytecode | by eiki | Medium

Next, the argument will be encoded in hex decimal and appended to encoded
“withdraw” function with 32 bytes padding.

// Convert from ETH to Wei.


> withdraw_amount = web3.utils.toWei(“0.01", “ether”);
10000000000000000
// Convert Wei with hexdecimal.
> withdraw_amount_hex = web3.toHex(withdraw_mount);
0x2386f26fc10000
// Left padding.
> withdraw_amount_padleft = web3.utils.leftPad(withdraw_amount_hex,
32);
0x0000000000000000002386f26fc10000
// Append to selector(encoded function).
“0x2c1a7d4d” + withdraw_amount_padleft
// Final encoded ABI.
0x2c1a7d4d0x0000000000000000002386f26fc10000

The data invokes withdraw function and requesting 0.01 as the argument. If you want
to know details about ABI encoding/decoding specification, please refer to Contract
ABI Specification.

More practically, interacting with the contract, you can use web3.js like below. First is
making a contract with Contract ABI, and next is creating an instance with EVM
bytecode. This code is generated by Solidity REMIX when compile is succeeded.

https://medium.com/@eiki1212/explaining-ethereum-contract-abi-evm-bytecode-6afa6e917c3b 5/9
2/12/23, 4:14 PM Explaining Ethereum Contract ABI & EVM Bytecode | by eiki | Medium

1 var samplecontractContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"testFunc","ou


2 var samplecontract = samplecontractContract.new(
3 {
4 from: web3.eth.accounts[0],
5 data: '0x6080604052348015600f57600080fd5b50607e8061001e6000396000f3fe6080604052348015600f5760
6 gas: '4700000'
7 }, function (e, contract){
8 console.log(e, contract);
9 if (typeof contract.address !== 'undefined') {
10 console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contr
11 }
12 })

sample_contract_abi.sol hosted with ❤ by GitHub view raw

Commands with “solc”


Let’s see how to generate Contract ABI and EVM bytecode with ’solc’ command. Solc
command is one of the most popularly used compilers. Let’s install it with npm
package manager.

Install

$ npm install -g solc

We will use this sample source code. The filename is SampleToken.sol.

https://medium.com/@eiki1212/explaining-ethereum-contract-abi-evm-bytecode-6afa6e917c3b 6/9
2/12/23, 4:14 PM Explaining Ethereum Contract ABI & EVM Bytecode | by eiki | Medium

1 pragma solidity ^0.5.8;


2
3 contract SampleContract {
4
5 function testFunc() public pure returns (int) {
6 return 1;
7 }
8 }

sample_contract.sol hosted with ❤ by GitHub view raw

Output EVM Bytecode

$ solc --bin SampleToken.sol


> ======= SampleContract.sol:SampleContract =======
Binary:
6080604052348015600f57600080fd5b5060878061001e6000396000f3fe6080604052
348015600f57600080fd5b506004361060285760003560e01c8063037a417c14602d57
5b600080fd5b60336049565b6040518082815260200191505060405180910390f35b60
00600190509056fea265627a7a7230582050d33093e20eb388eec760ca84ba30ec42da
dbdeb8edf5cd8b261e89b8d4279264736f6c634300050a0032

Output Contract ABI

$ sold —abi SampleToken.sol


> ======= SampleContract.sol:SampleContract =======
Contract JSON ABI
[{"constant":true,"inputs":[],"name":"testFunc","outputs":
[{"name":"","type":"int256"}],"payable":false,"stateMutability":"pure"
,"type":"function"}]

If you want to output to a specific directory, you can set with “-o” option. (you cannot
set output file name).

$ mkdir build
$ solc --abi -o build SampleToken.sol

https://medium.com/@eiki1212/explaining-ethereum-contract-abi-evm-bytecode-6afa6e917c3b 7/9
2/12/23, 4:14 PM Explaining Ethereum Contract ABI & EVM Bytecode | by eiki | Medium

When you re-compile, set “ — overwrite” option.

$ solc --abi -o build —overwrite SampleToken.sol

Get Help

$ solc --help

Conclusion
The article explained Contract ABI and EMV Bytecode. EVM Bytecode is a compiled
source code from the high-level programming language and Contract ABI is an
interface to interact with the EVM bytecode. And, both of them can be compiled with
’solc’incommand-line
Open app which is mostly used in Ethereum development. I hope the article
Get unlimited access

helps you to practically understand Contract ABI and EVM bytecode. If you have any
Search Medium
questions or comments, always welcome. Thank you.

References
Solidity Bytecode and Opcode Basics

What is an ABI and why is it needed to interact with contracts?

calldata keyword as parameter in solidity v0.5.0 function?

Solidity Source Mapping

Ethereum Abi Smart Contract Blockchain Evm Bytecode

https://medium.com/@eiki1212/explaining-ethereum-contract-abi-evm-bytecode-6afa6e917c3b 8/9
2/12/23, 4:14 PM Explaining Ethereum Contract ABI & EVM Bytecode | by eiki | Medium

https://medium.com/@eiki1212/explaining-ethereum-contract-abi-evm-bytecode-6afa6e917c3b 9/9
2/12/23, 4:16 PM Understanding SMART CONTRACT — BYTECODE & ABI | by Tanisk Annpurna | Coinmonks | Medium

Published in Coinmonks

Tanisk Annpurna Follow

Jul 9, 2022 · 4 min read · Listen

Save

Smart Contract

Understanding SMART CONTRACT —


BYTECODE & ABI

https://medium.com/coinmonks/understanding-smart-contract-bytecode-abi-4747b1616450 1/6
2/12/23, 4:16 PM Understanding SMART CONTRACT — BYTECODE & ABI | by Tanisk Annpurna | Coinmonks | Medium

In the last article, we saw how smart contracts are better than paper contracts. Read it
here 👉Intro to Smart Contracts

Lets Start….
We have seen how smart contracts are better than the old paper contracts, and how
EVM makes sure that smart contracts keeps their promises.

Now, EVM doesn’t understand any high level language. It understands low level
language. So, we need to convert our smart contract into low level language i.e.
BYTECODE.

💜 BYTECODE
- Bytecode is a low level language consisting combination of numbers and alphabets.
- Bytecodes are very hard to write as well as read. Basically its not human readable.
- Using different frameworks like solcjs,ethers, hardhat and many more, we can
convert our smart contracts into bytecodes.
- This is how a bytecode looks for a very small and simple smart contract.

608060405234801561001057600080fd5b50610771806100206000396000f3fe60806040523
4801561001057600080fd5b50600436106100575760003560e01c80632e64cec11461005c5
780636057361d1461007a5780636f760f41146100965780639e7a13ad146100b2578063b2a
c62ef146100e3575b600080fd5b610064610113565b

- We can see them as a combinations of numbers and alphabets.


- EVM is a stack machine, meaning it uses stack to run any script. It stores functions,
would PUSH function, would POP them and many more.
- Bytecode may look gibberish but they are commands for EVM on how to interact with
stack.
- If we convert these bytecodes into OPCODE i.e. operation code, we will see how or
what commands these combinations are giving to EVM.
- There are many websites that can convert bytecode -> opcode. I am using etherscan.
👉[https://etherscan.io/opcode-tool](Link)

New to trading? Try crypto trading bots or copy trading

This is what we get….


https://medium.com/coinmonks/understanding-smart-contract-bytecode-abi-4747b1616450 2/6
2/12/23, 4:16 PM Understanding SMART CONTRACT — BYTECODE & ABI | by Tanisk Annpurna | Coinmonks | Medium

[0] DUP1
[2] PUSH1 0x40
[3] MSTORE
[4] CALLVALUE
[5] DUP1
[6] ISZERO
[9] PUSH2 0x0010
[10] JUMPI
[12] PUSH1 0x00
[13] DUP1
[14] REVERT
[15] JUMPDEST
[16] POP
[19] PUSH2 0x0771
[20] DUP1
[23] PUSH2 0x0020
[25] PUSH1 0x00
[26] CODECOPY
[28] PUSH1 0x00
[29] RETURN

👉 Remember EVM treats every number as a hexadecimal number. “0x” means that the
number is a hexadecimal number. Now in-case of EVM, it doesn’t need any “0x” as it treats
every number as hexadecimal. So “0x40” in EVM we can put it as just “40”.*

Now these are different commands that helps EVM. Here is what they mean
1. PUSH1 0x40 -> This means to put 1 byte value of “0x40” in the stack. Now the
hexadecimal value of PUSH1 is “60”. So the commands become “6040”.
2. MSTORE -> This will allocate memory of 0x60 and will move 0x40 in there. The
hexadecimal code for MSTORE is “0x52”.

So the final bytecode for these becomes…


604052

https://medium.com/coinmonks/understanding-smart-contract-bytecode-abi-4747b1616450 3/6
2/12/23, 4:16 PM Understanding SMART CONTRACT — BYTECODE & ABI | by Tanisk Annpurna | Coinmonks | Medium

In this way every bytecode has their meaning and tells EVM what to do. We don’t
require to know about what every bytecode means for writing a smart contract. Just
knowing what it does is good. But if you want to learn more, Here is a link that will
help a lot [Ethervm.io](https://www.ethervm.io/).

Now, In the last article we saw ABI. Well, Smart contracts are only good when someone
can use it. So here helps ABI.

💜 ABI
- ABI stands for Application Binary Interface.
- ABI’s are not as complicated as BYTECODE and are human readable.
- ABI looks like these :

[
{
“inputs”: [
{
“internalType”: “string”,
“name”: “_name”,
“type”: “string”
},
{
“internalType”: “uint256”,
“name”: “_favouriteNumber”,
“type”: “uint256”
}
],
“name”: “addPerson”,
“outputs”: [],
“stateMutability”: “nonpayable”,
“type”: “function”
}
]

- As we can look these are just JSON format files with extension of .abi
- If we look closely these abi contains like type:’function’ or “uint256” or “string”.
https://medium.com/coinmonks/understanding-smart-contract-bytecode-abi-4747b1616450 4/6
2/12/23, 4:16 PM Understanding SMART CONTRACT — BYTECODE & ABI | by Tanisk Annpurna | Coinmonks | Medium

- These files contains all the details about the smart contracts like variables , their type
, their name as well as name of functions, access modifiers, they are payable or non-
payable and many more.

Ex-> when type is “uint256” or “string” that means its a variable but when its “function”
that means its a function.

- Its used when JavaScript wants to interact with smart contract, that is where abi
comes in. without abi there will not be any interactions and you can’t call any functions
or do anything with it.

💜 Let’s summarise….

- Smart contract requires bytecode and abi to run.


- Bytecode is non human readable and it tells EVM on how to execute the smart
contract.
- Bytecode can be converted OpCode which is human readable.
- Every number in bytecode means a command in EVM. EVM assumes every number
as hexadecimal.
- ABI is a JSON file with extension of .abi. It contains details about variables, access
modifiers, function, their return types and many more.
- ABI makes it possible for JavaScript to call the functions in smart contract.

👉Remember if you can write correct BYTECODE and ABI, you can simply deploy that
on the chain.

In the next article, we will see in how we can convert our smart contract to bytecode
and ABI. We will also get basics of solidity and how to write smart contract and deploy.

Hello, I am Tanisk Annpurna


I post about
🚀web3, Blockchain, Ethereum
🐦Smart Contract, Solidity
🎉JavaScript, ReactJS, NodeJS
Follow and like for more such posts. !!✌️!!

https://medium.com/coinmonks/understanding-smart-contract-bytecode-abi-4747b1616450 5/6
2/12/23, 4:16 PM Understanding SMART CONTRACT — BYTECODE & ABI | by Tanisk Annpurna | Coinmonks | Medium

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also, Read
Binance Futures Trading | 3Commas vs Mudrex vs eToro

How to buy Monero | IDEX Review | BitKan Trading Bot

CoinDCX Review | Crypto Margin Trading Exchanges

Red Dog Casino Review | Swyftx Review | CoinGate Review

Bookmap Review | 5 Best Crypto Exchanges in the USA


Open in app Get unlimited access

Search Medium
Ethereum Ethereum Blockchain Smart Contracts Web 3 Blockchain

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/coinmonks/understanding-smart-contract-bytecode-abi-4747b1616450 6/6
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Published in Web3 Magazine

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Thomas Guibert Follow

Mar 15, 2022 · 12 min read · · Listen

Save

Create Your First Ethereum Smart Contract With


Remix IDE
Build a Blockchain-powered chat from your browser!

Nenad Novaković

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 1/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Heard about Ethereum smart contracts before and would like to build your own but
you don’t really know how to get started?

This tutorial is made for you. Together, we’re gonna go through the creation and
deployment of your very first smart contract to the Ethereum Blockchain.

Everything will be done directly in your browser. There will be nothing to set up in
your environment. In fact, we will be using the web version of the Remix IDE, to write
and deploy our smart contract.

Disclaimer: This tutorial won’t focus at all on how the blockchain works, what can be
achieved with a smart contract, and how to make it gas efficient. Those are complete
topics on their own. The goal here is to cover the steps from writing to deploying your
smart contract.

First of all, here is a very short definition of a smart contract, as described by the
ethereum.org website:

“A smart contract is a program that runs on the Ethereum blockchain. It’s a collection of code
(its functions) and data (its state) that resides at a specific address on the Ethereum
blockchain.”

So. The game plan is simple. Write some code and somehow deploy it to the
blockchain!

Here is a more detailed summary of what we gonna do:

Getting Familiar With Remix


Write a Basic Smart Contract
Compile Our Smart Contract

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 2/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Add a Few Tests to Our Smart Contract


Deploy Our Smart Contract to the Rinkeby Test Network
Interact With Our Deployed Smart Contract From Remix
Conclusion

Getting Familiar With Remix

“Remix IDE is an open source web and desktop application. It fosters a fast development cycle
and has a rich set of plugins with intuitive GUIs. Remix is used for the entire journey of
contract development as well as act as a playground for learning and teaching Ethereum.”

The File Explorers — Remix

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 3/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

This pretty much looks like any other IDE right? In the sidebar, you have 3 tabs, for
now:

The file explorer, as seen in the picture above. This is where we’re going to write
our smart contract and its test file. It should be pre-filled with some files already.
Feel free to go through them!

The Solidity compiler. This is where we will compile our smart contract, once it is
ready.

The Deploy and Run Transactions, which is, you guessed it, where we will send our
smart contract to the Blockchain.

There is not much more to add than this for now… Let’s work!

Write a Basic Smart Contract


I thought it would be fun to write a smart contract that will enable people to chat on
the Blockchain!

The smart contract will be really simple. It will have two functions:

The first function will allow a user to post a message that will be fully stored on the
blockchain,

The second function will allow us to retrieve the messages (this would allow us to
display them in a web app)!

Let’s get started!


Create a new file in the contracts folder and name it BlockchainChat.sol .

Then, add the first lines of our contract in it:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
contract BlockchainChat {
}

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 4/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

So, what’s going on here?

The first line is the license declaration. A one-line comment in a predefined format
that states how can others use (or not use) your source code. It is not mandatory to
have this line but the Solidity Compiler will throw a warning if we don’t declare any
license.

The line that follows is the directive that specifies the compiler version to be used for
the current solidity file. You got it, we will use the version 0.8.12 .

Finally, our contract declaration, which starts with the word contract . Looks pretty
much like a Class declaration in many programming languages.

Add a Message Struct


So we said we want to store messages in our contract. More than the message, we need
to also store the address of the user that has sent it and also a timestamp of when the
message was added.

That’s three different pieces of information that we somehow need to pack together.
For that, we use what is called a struct in Solidity:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
contract BlockchainChat {
struct Message {
address waver;
string message;
uint timestamp;
}
Message[] messages;
}

Finally, we add a messages state variables, of type Message[] , which is an array of the
struct created above.

A state variable is a variable whose value is permanently stored in the contract storage. —
Ethereum StackExchange
https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 5/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Add the sendMessage function

// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
contract BlockchainChat {
struct Message {
address waver;
string content;
uint timestamp;
}
Message[] messages;
function sendMessage(string calldata _content) public {
messages.push(Message(msg.sender, _content, block.timestamp));
}
}

What we do here is pretty straightforward. We push the received message to our


messages state variable. But here are a few things that you might want to know more:

string calldata _content

This is the parameter that gives us the message sent. It is of type string . Notice the
calldata keyword? It defines the data area where a variable is stored.

I don’t want to confuse you with that in this article because there is much to say and
understand about it but if you feel like you want to know more, here is a good thread
on StackExchange.

msg.sender & block.timestamp

Those two aren’t declared anywhere so where are they coming from? They are Global
Variables.

msg contains properties that allow access to the blockchain. Here, msg.sender will
always be equal to the address where the call came from (the user in our case).

block contains a lot of interesting data about the current block being added to the
blockchain. In our case, we get the timestamp!
https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 6/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Here is a link to the solidity documentation that tells more about what you can get
from them: soliditylang.org.

Add the getMessage function

// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
contract BlockchainChat {
struct Message {
address waver;
string content;
uint timestamp;
}
Message[] messages;
function sendMessage(string calldata _content) public {
messages.push(Message(msg.sender, _content, block.timestamp));
}
function getMessages() view public returns (Message[] memory) {
return messages;
}
}

getMessages is simpler than our sendMessage function. But here are interesting facts
about it:

view

Notice the view keyword? This is called a Modifier. It states that this function is read-
only. Inside functions that are of type view , state variables cannot be modified.

Since it is read-only, it comes with the great advantage that calling this function won’t
require doing a transaction and therefore won’t cost any gas to the user! More on that
later when we try our contract.

public

As for our previous function, getMessages is a public function. This is a Function


Visibility Specifier. It essentially means that it can be called from outside of the

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 7/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

contract (as opposed to a private function).

returns

Finally, the returns statement followed by the (Message[] memory) states what data this
function will return.

Compile Our Smart Contract


Our smart contract is looking good! Keep the BlockchainChat.sol file open and click on
the Solidity Compiler tab in the sidebar.

The Solidity Compiler — Remix

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 8/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

There are a few options that can affect how the contract is compiled but selected ones
are already fine. Let’s go ahead and click “Compile BlockchainChat.sol.”

If everything goes well, you should get the smart contract artifacts added in
contracts/artifacts in the file explorer.

About the created artifacts

1. artifacts/BlockchainChat.json : contains the link to the libraries, the bytecode, the


deployed bytecode, the gas estimation, the method identifiers, and the ABI. It is
used for linking a library address to the file.

2. artifacts/BlockchainChat_metadata.json : contains the metadata from the output of


Solidity compilation.

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 9/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Add a Few Tests to Our Smart Contract


It is primordial to test your contract extensively before deploying it to the blockchain.
The blockchain is by design immutable. So you can’t just deploy your contract and fix it
later if you find a bug, that’s simply not possible.

Remix offers the possibility to write and run tests. Let’s add a test file so we can ensure
that our smart contract works as intended before deploying it.

Come back to the File Explorers and under the tests folder, create a new file named
BlockchainChat_test.sol . Fill it with this code:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
import "remix_tests.sol";
import "../contracts/BlockchainChat.sol";
contract BlockchainChatTest {
BlockchainChat blockchainChatToTest;
/// 'beforeAll' runs before all other tests
function beforeAll () public {
blockchainChatToTest = new BlockchainChat();
}
function checkSendMessage () public {
// Send a first message
blockchainChatToTest.sendMessage("Hello World!");
// Ensure the messages variable contains 1 message
Assert.equal(blockchainChatToTest.getMessages().length, uint(1),
"messages state variable should contain 1 message");
// Ensure that our first message's content is "Hello World!"
Assert.equal(blockchainChatToTest.getMessages()[0].content,
string("Hello World!"), "The first Message in message should be
\"Hello World!\"");
// Send a second message
blockchainChatToTest.sendMessage("This chat is super fun.");
// Ensure the messages variable contains 2messages
Assert.equal(blockchainChatToTest.getMessages().length, uint(2),
"messages state variable should contain 2 messages");
}
}

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 10/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Nothing really complex in this file. It’s essentially making sure that when a message is
sent, it is stored in our smart contract and that the messages can be retrieved.

Run our test file


In the sidebar, click on the Solidity Unit Testing tab.

Is this tab missing? Click the plug at the bottom of the sidebar. This will open the Plugin
Manager. Search for Solidity Unit Testing and activate this plugin.

Click on the run button. The tests for our smart contract will run and hopefully pass!

Successfully passing tests — Remix

Deploy Our Smart Contract to the Rinkeby Test Network


As previously said, the blockchain is immutable. A deployed smart contract can’t be
modified anymore. While we’ve covered our BlockchainChat smart contract with a few
tests, it might not be wise to deploy it to Ethereum Mainnet yet.

Deploying a smart contract cost a lot of gas, which means a lot of real money. We might
want to test it in “real condition” for free first!

There are what we call Testnets (Test network). Rinkeby is one of them. A testnet is an
environment that is pretty much like Mainnet, despite the fact that it’s here to act as a
sandbox.

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 11/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

It’s a testing environment, that can be used to run your smart contract in almost real
condition, without involving real assets (we will see in a bit that we will still use ETH,
but fake ETH!).

Now that you know more about why we want to deploy to Rinkeby first, here are the
steps to get started:

Note that the steps to deploy to Ethereum Mainnet are exactly the same as the ones that will
follow.

Install Metamask
We will need Metamask to send transactions, so make sure that it is installed.
You can get it on metamask.io.

Select the Rinkeby network


Metamask allows us to change the environment in one click. By default, it is connected
to Mainnet, let’s switch it to Rinkeby.

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 12/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Where to get ETH to deploy our smart contract


Rinkeby works as Mainnet. Meaning that we still need to pay gas to deploy our
contract. And to pay for the gas, we need ETH… “Rinkeby ETH”.

We can get some Rinkeby ETH to play with on Faucets.

There are many Faucets available, here is rinkebyfaucet.com that you can use to get
some Rinkeby ETH in your wallet.

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 13/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Copy and paste the wallet address you want to use to deploy your smart contract and
click on Send me ETH. Wait a few seconds and your wallet should have received
around 0.1 fake ETH.

Let’s deploy our smart contract (for real this time)


Head back to Remix, and go to the Deploy and Run Transactions page.

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 14/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Here is how to configure the settings:

Environment

Under the hood, Metamask exposes a Web3 object to the webpage. We want to use it to
deploy our contract. Therefore, select Injected Web3 in the dropdown.

Metamask should pop up, asking for authorization to connect to Remix.

Select the account you want to connect with. It should be the same as the one you used
with the Faucet previously.

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 15/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Once done, please make sure, once again, that you are connected to the Rinkeby
Network.

Account

The account you selected in the previous step should appear here. Make sure that it is
the same wallet address.

Gas Limit and Value

Not much to change here, leave the default values.

Contract

Make sure that BlockchainChat is selected.

We’re all set!


Click on deploy. This should open a Metamask contract deployment transaction
request.

Go ahead and click on Confirm to deploy your contract.

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 16/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

After a few seconds, the terminal displays a success message!

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 17/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Click the View on Etherscan link, which should lead you to the transaction page as
follows:

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 18/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

What’s important on this page is:

From: this is the wallet used to deploy the contract

To: this is the address of our BlockchainChat smart contract

Congratulations, you’ve deployed a smart contract to Rinkeby!

Click on the contract address to access the smart contract details. There, you will see
all the transactions ever made with your contract. For now, there should be only the
contract creation transaction.

Interact With Our Deployed Smart Contract From Remix

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 19/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Head back to Remix. There should now be a deployed contracts panel in the Deploy &
Run Transactions tab:

Fun! There are the two functions that we created in our BlockchainChat smart
contract: sendMessage and getMessages .

Send the first message!


In the input next to the sendMessage button, type any message you would like to
publish in your chat, and then click the sendMessage button.

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 20/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

This should pop up Metamask, prompting you to validate the transaction. Accept it!
After a few seconds, you should have confirmation in the Remix terminal:

Try out the getMessages function


Now, let’s click on the getMessages function and look at the terminal. (you might need
to expand the response)

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 21/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

{
“0”: “tuple(address,string,uint256)[]:
0x096....D13fD,Hey there!,1647106198”
};

getMessages returns the list of messages stored in the messages state variable of our
smart contract. That’s a success!

Did you notice a difference while calling getMessages ?

Metamask did not ask you to accept a transaction to get the messages in our smart
contract.
https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 22/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Remember, here is what our getMessages function look likes:

function getMessages() view public returns (Message[] memory) {


return messages;
}

That’s because of the view keyword used in the getMessages function declaration. In
fact, here we are just reading the blockchain, we are not modifying it.

Reading the blockchain is free! Imagine that we are creating a web app for our chat
and we’re requiring our users to do a transaction to receive the latest published
messages… Our chat would be quite expensive to use! But thanks to view , it is free to
receive the messages!

Conclusion
Congratulations for making it until the end and for writing and deploying your first
Ethereum smart contract!

Now that you have fully gone through the process, it’s time to experiment more! Can
you think of anything that could be improved? Here is an idea:

Currently, a user could send an empty string as a message, which is not really fun.
Here is how the sendMessage function could be modified:

function sendMessage(string calldata _content) public {


uint contentLength = bytes(_content).length;
require(contentLength > 0, "Please provide a message!");
messages.push(Message(msg.sender, _content, block.timestamp));
}

This was a very comprehensive first step in Solidity.

Smart contract development is a whole different paradigm. Blockchain’s immutability


and gas cost-efficiency require developers to be extremely rigorous. These topics were

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 23/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

not covered in this article but definitely need to be in your areas of exploration if you
aspire to be a Solidity developer!

Thanks for reading.

Programming Solidity Ethereum Blockchain Web 3

Enjoy the read? Reward the writer.Beta


Your tip will go to Thomas Guibert through a third-party platform of their choice, letting them know you appreciate their
story.

Give a tip

Get an email whenever Thomas Guibert publishes.

Your email

Subscribe

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

About Help Terms Privacy

Open in app Sign up Sign In

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 24/25
2/12/23, 4:19 PM Create Your First Ethereum Smart Contract With Remix IDE | by Thomas Guibert | Web3 Magazine | Medium

Get the Medium app


Search Medium

https://medium.com/web3-magazine/create-your-first-ethereum-smart-contract-with-remix-ide-667e46e81901 25/25
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

Published in Quick Code

Quick Code Follow

May 10, 2018 · 13 min read · Listen

Save

10 Best Solidity Tutorials For Ethereum [2023


FEB] — Learn Solidity Online
Learn Solidity for writing smart contracts with the best Solidity tutorials
for beginners in 2023.
The digital cryptocurrency Bitcoin was the first Blockchain application. The success of
Bitcoin led to the creation of the Ethereum platform. Whereas Bitcoin is a “Blockchain
Application”, Ethereum is a “Blockchain Platform”. Ethereum not only supports a
distributed ledger but also supports Smart Contracts.

Smart Contracts are computer programs that have a code that implements contractual
agreements (rules) between two or more parties. The rules coded in the smart contract
are triggered by events in the physical world and automatically carry out some
predefined action(s). All of this happens without any intermediary, web servers, or
back-end databases.

Let me give you an example — eBay is the intermediary between the buyer and seller.
eBay makes $ every time a buyer buys an item from the seller. In a decentralized
bidding application, a smart contract can replace EBay the intermediary. The rule
coded in the contract will be that when a buyer will pay, the seller will ship the item to
the buyer. The funds will be held in the smart contract till the buyer confirms the
receiving of the goods. Once the buyer confirms the receipt of goods the funds will be
released to the seller. Smart Contracts are executed on the Ethereum network nodes as
https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 1/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

opposed to a centralized server infrastructure owned by an intermediary (e.g., Ebay).


Nodes are Ethereum client processes running on the network participant’s computer.

Anyone can write Ethereum decentralized application, so in other words, you can
create your own Bitcoin like Cryptocurrency or Ebay like application on a public
Ethereum network. Please note that all applications are not a good candidate for
Blockchain technology for example building a static website on Blockchain technology
is not the right use of the technology.

Solidity is a programming language for writing Smart Contracts. Essentially, think of it as a


way to control a bank account with code. With Solidity, we can write applications that
simulate a crowd funding campaign, a lottery, a loan, or any other type of financial
instrument. Don’t be intimidated by learning ‘another’ programming language; Solidity is
known to be quite similar to Javascript and exceptionally easy to pick up for anyone who has
previous JS experience. This course will give you all the tools you need to master Solidity.

1. Compile Your First Ethereum Smart Contract With Solidity


Learn how to set up your own private blockchain node using Geth, Solidity, and Mist.

I will walk you through how to compile and run your first smart contract on a local test
environment.

This will include

1. Installing Solidity, which used used to compile the contract into byte code that can
be deployed on the blockchain.

2. Installing Geth, which runs a local node and also has a JavaScript command line
that can be used to talk to the blockchain.

3. Create a private local node, so you can experiment without spending money.

4. Create a couple of test accounts

5. Deploy the smart contract into the test blockchain

6. Call the functions of our smart contract to see that it is working.

We do not cover:
https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 2/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

1. Solidity programming in depth, only show how to set up environment, compile and
interact with contract.

2. Workflow and IDE’s for programming

2. Blockchain Specialization
This specialization introduces blockchain, a revolutionary technology that enables
peer-to-peer transfer of digital assets without any intermediaries, and is predicted to
be just as impactful as the Internet. More specifically, it prepares learners to program
on the Ethereum blockchain. The four courses provide learners with (i) an
understanding and working knowledge of foundational blockchain concepts, (ii) a skill
set for designing and implementing smart contracts, (iii) methods for developing
decentralized applications on the blockchain, and (iv) information about the ongoing
specific industry-wide blockchain frameworks.

The specialization covers a range of essential topics, from the cryptographic


underpinnings of blockchain technology to enabling decentralized applications on a
private Ethereum blockchain platform.

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 3/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

It is ideal for programmers and designers involved in developing and implementing


blockchain applications, and anyone who is interested in understanding its potential.

In this course you will learn :

Understand smart contracts, a core idea and computational model of blockchain


that enables automation, autonomy, scalability and transparency.

How to design and program smart contracts and decentralized application.

Have an understanding and working knowledge of the emerging blockchain


technology.

How to think of innovative application models, leveraging the blockchain


technology.

3. Ethereum: Building Blockchain Decentralized Apps (DApps)


Are you interested in writing blockchain apps or integrating cryptocurrency into your
existing apps?

In this course, you will learn:

how to work in the Ethereum blockchain environment.

about key programming concepts and techniques surrounding Ethereum


development.

how to build decentralized applications (DApps) using some of the web


programming languages.

The course shows mobile and web developers who are broadly familiar with
programming concepts how to work in the Ethereum blockchain environment.

As you walks through the creation of a smart contract, a web user interface, and the
JavaScript needed to link the two, the course helps to familiarize you with key
programming concepts and techniques surrounding Ethereum development.

Discover what the Ethereum blockchain is and how it differs from bitcoin. Get an
introduction to Solidity, the programming language used to write smart contracts on
https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 4/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

the Ethereum network.

In addition, learn how to build decentralized applications (DApps) using some of the
web programming languages you’re already familiar with.

4. Create Ethereum & Blockchain Applications Using Solidity


Learn about everything there is to know about Ethereum and Blockchain Based
Applications and How To Program Them. A step by step process is used to show
explain every facet of these topics.

Gain a good understanding of the following concepts with this course:

What Solidity Is?

How To Create Blockchain Applications?

What Blockchain is?

How Blockchain works?

What is Bitcoin?

What is Ethereum?

Programming Blockchain Programs

What are Cryptocurrencies?

How Cryptocurrencies work?

Alternative cryptocurrencies

Cryptography basics

5. Developing Applications on Ethereum Blockchain


Learn to develop applications for the Ethereum platform. Start with the basics of
blockchain and Ethereum, then learn the core skills for writing smart contracts using
Solidity programming language.

The course includes:

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 5/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

Ethereum Protocol

Getting Started with Smart Contracts

Solidity Programming Language

Ethereum API

Truffle Framework

Developing Advanced Smart Contracts

Web Applications with Ethereum

In this course, Developing Applications on Ethereum Blockchain, you will gain the
ability to develop decentralized applications for Ethereum.

First, you will learn the basics of blockchain and the Ethereum platform.

Next, you will discover how to develop smart contracts using Solidity, how to interact
with smart contracts, and how to create an efficient development environment for
Ethereum projects.

Finally, you will explore how to develop web applications that interact with an
Ethereum blockchain.

When you’re finished with this course, you will have the skills and knowledge of the
Ethereum platform needed to develop your applications for both public and private
networks.

6. Become a Blockchain Developer


Demand for blockchain developers is skyrocketing. In this program, you’ll work with
the Bitcoin and Ethereum protocols, build projects for real-world application, and gain
the essential skills for a career in this dynamic space.

In this course, you will learn:

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 6/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

the basics of how the blockchain data model works by creating your own private
blockchain using Node.js and Leveldb.

how to dvance your blockchain skillset to the second generation of blockchain


services with smart contracts utilizing the Ethereum network.

blockchain architecture and advanced concepts such as privacy, security and


decentralized file management.

how to advance your blockchain skill set by developing a decentralized application


(Dapp) that will perform actions based on external triggers, and handle payments.

Learn the fundamentals of the blockchain platform. Create your own private
blockchain, and secure a digital asset using blockchain identity.

Explore the Ethereum platform, and use Solidity and smart contracts to develop your
own decentralized app.

7. Advance Your Skills in the Blockchain


For those in the IT industry especially, a thorough understanding of how Blockchain
works, and what the key development skills are, can set you on a new career
development path.

In this course, you will learn how to:

master fundamental blockchain and cryptocurrency concepts.

understand the development competency skills for Solidity and Ethereum.

master blockchain programming for iOS.

Learn about the blockchain and the implications of decentralized, encrypted data
storage for business and society.

You will learn about the blockchain and the implications of decentralized, encrypted
data storage for business and society

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 7/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

Learn how to build decentralized applications (DApps) using some of the web
programming languages you’re already familiar with.

This course teaches you how to build a simple contract-based application with Solidity.
Learn how to implement blockchain-based storage and encryption in the iOS
framework using Swift.

You will understand the basics of how cryptocurrencies are created, traded, and
mined. Explore some of the basic security requirements for cryptocurrencies and
provides guidance on how to lower security risks.

8. Ethereum Game Development: Build A Game On The Blockchain


Work With Solidity & Other Tools, To Build A Fun Game! Gaining Greater Proficiency
In Ethereum Blockchain Development.

In this Ethereum Game Development Course, we’re going to help you alleviate all of
those questions you have around building something practical, upon the Ethereum
Blockchain.

We’re going to help you build a Tic-Tac-Toe Game upon the Ethereum Blockchain, so
you can become a more proficient Ethereum Blockchain Developer. Following which,
you’ll have worked with the Ethereum Blockchain at a more advanced level.

That’s the pure and simple goal, but, that entails covering every element of the
Ethereum Blockchain Development journey, which we’re sure you’re going to find
fascinating.

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 8/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

9. Learn Solidity: Programming Language for Smart Contracts


Best Solidity Tutorial Available Online to Build Blockchain Based Decentralized
Application DApps on Ethereum Network.

Solidity is a programming language for writing smart contracts which run on


Ethereum Virtual Machine on Blockchain. It is a contract-oriented, high-level language
whose syntax is similar to that of JavaScript and it is designed to target the Ethereum
Virtual Machine.

In this course you will learn everything related to Solidity to build Smart Contracts
based Blockchain application on Ethereum.

What is Ethereum, Smart Contracts & Blockchain?

What is Solidity & Ethereum Virtual Machine?

How to install & Setup Solidity Development Environment?

How to write first basic smart contracts?

Data types, control structure, functions, inheritance, mathematical operations, etc.

How to deploy & test smart contracts in Solidity?

Building 2 Applications

1. Voting Ballot on Blockchain

2. FundRaiser Application

This course will enable you to build any kind of Blockchain application on Ethereum
using Solidity which is most common language for writing Ethereum Blockchain.

10. Ethereum Developer Masterclass: Build Real World Projects


Step-By-Step: Real-World dApps On The Blockchain Using Latest Solidity, Web3js,
Truffle, TestRPC and MetaMask.

Ethereum Developer Masterclass: Build Real World Projects — is the most complete
Ethereum Blockchain Development course online helping you to build complex, real

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 9/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

world, ethereum based distributed applications using solidity successfully.

This course is perfect for anyone who wants to start there journey with the Blockchain,
Solidity, and Ethereum whilst building something large and meaningful. Those who
have an interest in advanced coding, including proven workflows and techniques will
thoroughly enjoy this course.

1. In this course we’ll be detailing every aspect of the Ethereum Blockchain


Development Ecosystem with you at an advanced level, enabling you to go forth to
build complex Decentralised Applications using Solidity.

2. Within this course we’ll be guiding you through the process to create and launch
your own Initial Coin Offering upon Ethereum, you’ll then understand how it works on
a technical level.

3. By taking and completing this course we’ll guide you through the steps to help you
successfully build your very own completely decentralized exchange, and deploy it to
Rinkeby-Testnet.

11. Become a Blockchain Developer with Ethereum and Solidity


Develop your first decentralized application from scratch on the Ethereum blockchain.

This course is a complete introduction to decentralized application (Dapp)


development on the Ethereum blockchain using the Solidity language and the Truffle
build framework.

No need to know anything about the blockchain, you should just have some basic
software development experience. Whether you have already written some code for
backend, web or mobile applications, it should be enough to become a blockchain
developer thanks to this course.

The blockchain is all the rage these days, and there is a lot of theoretical or anticipative
talk around it, but this course will help you get your hands dirty with actual code in
order to build your first decentralized application. This is the kind of skill that can get
you an actual job as a blockchain developer, something that is in skyrocketing demand
right now.

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 10/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

Have you ever looked back on the nineties, thinking you would have loved to be a part
of the web revolution. Well, stop dreaming: the blockchain is here and it promises to
be even bigger than the web or even the mobile revolution.

We briefly cover the philosophy of the blockchain, both as a crypto-currency


system and as a development platform

Then we will explain how blockchains work, what are their main components and
how its ecosystem is structured

After that we quickly go over the main cryptographic tools you need to understand

We continue with a description of the perfect development environment, including


tools that are used by most professional blockchain developers

And the biggest part of the course is dedicated to guiding you through the iterative
creation, development, testing and deployment of the ChainList decentralized
application

Tools that you will come across

Ethereum of course

The Metamask Chrome extension

The Solidity smart contract language

The Truffle build and test framework (Truffle 4)

The Ganache Ethereum node emulator

Github Pages

Atom (text editor)

The Rinkeby test network

12. Ethereum: Decentralized Application Design & Development


Develop a full DAPP | ICO | Setup Private network in next 2 weeks using Web3J,
TruffleV4, MetaMask, Ganache, Solidity +++.

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 11/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

To build Ethereum Decentralized applications you will need to learn a couple of skills.
This course can help you learn all of those skills but there are some prerequisites for
the course:

1. Experience with either Javascript or Java. Course will NOT teach Javascript

2. Basic understanding of the Javascript/HTML DOM model

3. Access to a PC or MAC with access to the Internet (Minimum 4GB needed 6 GB


preferred)

4. Comfortable with new software installation & hands on coding

This course takes the approach of “Learn by doing”. Students are encouraged to try out
all aspects of the technologies on their own after each lecture. Almost all of the
concepts discussed in the lectures are shown in action by way code samples etc. The
demo code used in the lectures is available for download from GitHub so that students
can change the code to try out new things.

Front end of the Decentralized applications are typically created as single page or
desktop applications using Javascript/HTML/CSS. Since there are multiple Javascript
frameworks, it was decided to keep the lectures independent of any specific JS
framework. Students are free to use any one or more JS frameworks of their choice.

Multiple quizzes in each section will validate student’s knowledge. Coding exercises
will help them understand the concepts better & gain confidence.

Course is divided into 10 sections:

Section#1

Introduces the Blockchain & Ethereum technology

Section#2

Drills deeper into the Ethereum Blockchain technology

Concepts, Wallet

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 12/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

Hands-on: Install Wallet, Mining for Ethers, Transactions

Section#3

Ethereum Client

Hands-on: Install Geth, Try out the geth commands & options

Section#4 Geth Javascript Management API

Hands-on: Try out the various API i console and by writing scripts

Section#5

Web3 API

Hands-on: Develop Javascript/HTML front end for executing contracts on TestNet

Section#6

Getting ready for Smart Contract development

Learn about the various tools & frameworks used for developing smart contract

Hands-on: Installation : Visual Studio, Truffle framework version 4.0, Ganache, Meta-
Mask

Section#7

Solidity for smart contracts development

Learn the concepts of Solidity language

Hands-on: Code simple contracts in Solidity + write test cases for testing

Section#8

Solidity &Infrastructure patterns

Hands-on: Code smart contracts

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 13/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

End to end application walkthrough

Hands-on: DIY Project & Solution

Section#9

Covers the setting up of private networks

Tools for managing private networks

Section#10

All about Initial Coin Offering & ERC20 Standard for creating and launching a coin

Students will learn how to create a coin and manage it in common tools.

13. Ethereum Blockchain Developer: Build Projects Using Solidity


One Of The Largest, Most In-Depth Ethereum Blockchain Development Courses,
Helping You To Build Projects Using Solidity.

Ethereum Blockchain Developer: Build Projects Using Solidity — is one of the largest,
most in-depth ethereum development courses online. The curriculum contains a
https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 14/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

number of practical exercises, which will help you put all the knowledge you’ve
learned into practice to create something of value.

By taking this course you’ll get to work with the ethereum blockchain on a practical
level, with step-by-step instructions guiding you through the entire process. This
course embodies our ethos of learning by doing, as you’ll have projects created of your
very own by completing this course.

1. We’re in the early adopter stage with ethereum technology, so you currently have the
chance to get in at the ground level and become proficient in it before it reaches the
next adoption stage.

2. Being apart of a community is crucial when it comes to new technology, and the
ethereum communities are some of the most friendliest, hence you’ll be able to
communicate with them effectively having created projects of your very own in this
course.

3. There aren’t many blockchain developers, yet there’s huge demand! If you decide to
continue to advance your journey in this field, you can be assured there are companies
seeking your skills.

14. Ethereum and Solidity: The Complete Developer’s Guide


Use Ethereum, Solidity, and Smart Contracts to build production-ready apps based on
the blockchain.

The development community is still figuring out the best way to use Ethereum in the
creation of new and exciting apps. I spent a tremendous amount of time to research
and create best practice for interfacing with Ethereum from Javascript. I can’t
overstate it enough; this course will show you the best and most easily repeatable
patterns for creating production-ready apps with Ethereum.

Thank you for reading this. We have curated top


tutorials on more subjects, you would like to see them:
https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 15/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

6 Best Cryptocurrency Trading Courses For Beginners — Learn


Cryptocurrency Trading Online
Learn cryptocurrency trading to understand how to trade
cryptocurrency with the best cryptocurrency courses for…
medium.com

10+ Best Swift Tutorials For Beginners — Learn Swift Online


Learn Swift to become an advanced mobile developer with the best
Swift tutorials for beginners in 2022.
medium.com

10+ Best Cryptocurrency Courses for beginners — Learn


Cryptocurrency Online
Learn cryptocurrency courses to increase your profit with the best
cryptocurrency tutorials for beginners in 2022
medium.com

Disclosure: We may get a small affiliate commission if you buy a course through links on this
page. Thank you.

Ethereum Cryptocurrency Investment Cryptocurrency Crypto Solidity

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 16/17
2/12/23, 4:24 PM 10 Best Solidity Tutorials For Ethereum [2023 FEB] — Learn Solidity Online | Quick Code

Sign up for Developer Updates


By Quick Code

Receive weekly updates about new posts on programming, development, data science, web development and
more Take a look.

Open
Emails in
willapp
be sent to [email protected]. Not you? Get unlimited access

Get this newsletter


Search Medium

https://medium.com/quick-code/top-tutorials-to-learn-ethereum-solidity-at-different-level-23700a04ae80 17/17
2/12/23, 4:27 PM Finance 3.0 WIKI | Ethereum Testnet vs. Mainnet | by hummingbot | Hummingbot Blog | Medium

Published in Hummingbot Blog

hummingbot Follow

Aug 21, 2018 · 4 min read · Listen

Save

Finance 3.0 WIKI | Ethereum Testnet vs. Mainnet

WHAT IS A TESTNET?
A Testnet is an Ethereum blockchain that uses identical technology and software as the
“Mainnet” Ethereum blockchain. However, whereas the Mainnet network is used for
“actual” transactions with “value”, Testnets are used for testing smart contracts and
decentralized applications (“DApps”).

Differences between the Testnet and Mainnet

https://medium.com/hummingbot/finance-3-0-wiki-testnet-vs-mainnet-8ab5b78d93#:~:text=WHAT IS A TESTNET%3F,applications (“DApps”). 1/5


2/12/23, 4:27 PM Finance 3.0 WIKI | Ethereum Testnet vs. Mainnet | by hummingbot | Hummingbot Blog | Medium

Blockchains are simply databases created by a network of computers that interact with
each other, using purposefully designed software to get the computers on that network
to agree (i.e. achieve “consensus”) on what data to add and store on the database. The
only difference between Testnets and Mainnet is that they are operated by different
networks; i.e. one group of computers has agreed to work with each other and form a
Testnet network, while another group of computers has agreed to work together to
serve as the Mainnet network.

In order for a network of computers to agree to “work with each other”, they must
agree on two parameters which uniquely identify each network:

1. A network ID: a number parameter which acts as an identifier for a network. For
example, the Mainnet’s network ID is 1, while the other most commonly used
Testnets have network IDs of 3, 4, and 42 for Ropsten, Rinkeby, and Kovan,
respectively. So if you want to connect your computer to one of the blockchains,
you run the Ethereum software and specify a network ID of 1 to connect it to the
Mainnet, or you specify a network ID of 3 for Ropsten. That way, it knows which
network of computers to connect to.

2. Genesis block: all computers on a network must agree to all the data stored on that
blockchain, which of course must begin somewhere: the genesis block. The
genesis block is block #1 of a network’s blockchain; it is just arbitrary data that has
been designated as the beginning of that blockchain.

Why Does Ether on the Mainnet Have Value?


https://medium.com/hummingbot/finance-3-0-wiki-testnet-vs-mainnet-8ab5b78d93#:~:text=WHAT IS A TESTNET%3F,applications (“DApps”). 2/5
2/12/23, 4:27 PM Finance 3.0 WIKI | Ethereum Testnet vs. Mainnet | by hummingbot | Hummingbot Blog | Medium

As mentioned, the software used by computers on Testnets and the Mainnet is


identical. You can even mine Ether on some Testnets (“Test Ether”), just as you would
on Mainnet. So if the software is exactly the same, why is Test Ether “worthless” while
Mainnet Ether has value?

The reason that “Mainnet Ether” has value is just because the community assigns
value to Ether that exists on the Ethereum network with a network ID of 1. For
example, if you buy Ether on Coinbase, that Ether corresponds to Ether on the Mainnet
(network ID = 1), rather than Ether on a Testnet (network ID ≠ 1). This is similar in
concept to how a dollar bill is just a piece of paper; the only reason it has value is
because the U.S. government says it does and the general public believes it does and
therefore uses dollar bills to transact value.

WHY DID WE TEST THE BASKET PROTOCOL ON THE TESTNET?


As mentioned, the technologies and software underlying testnets and the mainnet are
identical. Therefore, deploying on the testnet serves as a simulation of how our
protocol would work on the Mainnet itself, with real tokens and real Ether.

Since the testnet functions the same way, it is useful to test smart contracts,
transactions and mining, simulating a real-world environment since there are many
computers running nodes on the testnet, and other developers running smart
contracts and other testnet DApps.

There are also different Testnets available for developers. At CoinAlpha, our engineers
test DApps end-to-end on the Ropsten Testnet before deploying to the Mainnet.

Why did we choose Ropsten Testnet?

The Ropsten Testnet is the most similar network to the Mainnet. It uses the same
consensus algorithm (“proof of work”), which achieves consensus through mining.
Therefore, any computer connecting to the Ropsten network can mine for test Ether.

In contrast, some Ethereum test networks such as Rinkeby and Kovan are more
centralized and use different consensus algorithms (“proof of authority”), which have
https://medium.com/hummingbot/finance-3-0-wiki-testnet-vs-mainnet-8ab5b78d93#:~:text=WHAT IS A TESTNET%3F,applications (“DApps”). 3/5
2/12/23, 4:27 PM Finance 3.0 WIKI | Ethereum Testnet vs. Mainnet | by hummingbot | Hummingbot Blog | Medium

different dynamics and are more centralized. The original creators of the network
control the bulk of the Ether on the network. For example, to get some initial test
ether, you may have to request it from a single party which has “authority”.

HOW CAN YOU GET TEST ETHER?


Test Ether can also be mined. A web search for “testnet mining” should turn up the
information necessary to prepare for mining Testnet tokens.

Another way to acquire Test Ether, which is simpler, is through a web-based service
known as a faucet. These are faucets set up for easily acquiring and donating Testnet
tokens. A web search for “testnet faucet” should point you to the available faucets.

FUN FACT
Since test tokens require mining and only a few people engage in mining them,
martinkou, co-founder and CTO at CoinAlpha once controlled over 50% of hash power
of the entire Testnet, and was therefore capable of perpetrating a “51% attack”. :P

Special Thanks to Yvonne Zhang and Carlo Las Marias for contributing to this article.

To learn more about CoinAlpha:


Check out our website https://coinalpha.com;
Join the conversation on telegram: https://t.me/coinalphainc;
Follow us on Twitter: https://twitter.com/CoinAlphaInc;
Follow our blog: https://medium.com/finance-3.

Blockchain Cryptocurrency Crypto Ethereum Education


Open in app Get unlimited access

Search Medium

https://medium.com/hummingbot/finance-3-0-wiki-testnet-vs-mainnet-8ab5b78d93#:~:text=WHAT IS A TESTNET%3F,applications (“DApps”). 4/5


2/12/23, 4:27 PM Finance 3.0 WIKI | Ethereum Testnet vs. Mainnet | by hummingbot | Hummingbot Blog | Medium

https://medium.com/hummingbot/finance-3-0-wiki-testnet-vs-mainnet-8ab5b78d93#:~:text=WHAT IS A TESTNET%3F,applications (“DApps”). 5/5


2/12/23, 4:29 PM Mainnet vs Testnet : The Difference | by BlockTrain: Learn Web3 | Medium

BlockTrain: Learn Web3 Follow

Aug 8, 2022 · 2 min read · Listen

Save

Mainnet vs Testnet : The Difference

Have you ever done test drive for the car that you were willing to purchase? We do that
to check whether it’s compatible with our needs, only after having 100% confidence we
buy a car. Similarly there are two networks of blockchain — Mainnet & Testnet

Watch & Learn — https://appopener.com/yt/9jwdr7nlp

Mainnet

https://medium.com/@0xblocktrain/mainnet-vs-testnet-the-difference-e96729f4a160 1/3
2/12/23, 4:29 PM Mainnet vs Testnet : The Difference | by BlockTrain: Learn Web3 | Medium

The Main-Network is the ecosystem of connected nodes that execute real


transactions that have real value like sending BTC to your friend in USA.

These transactions are publicly available for anyone to see, on a blockchain


explorer.

The one who carry forwards a transaction of any kind on a mainnet has to pay
some fee (called gas fee), the amount depends upon the network used. Similarly
how we fuel our car frequently because we use it.

The owner of the node, who confirms the transactions authenticity is paid some
part of the gas fee as a reward for their efforts.

Any node in a mainnet is identified by the ID = 1. For eg — if you want to became a


validator in main network you’ll choose your ID as 1.

A mainnet is an open-sourced blockchain, it’s establishes a factor of trust.

Any project that does not have a mainnet is still a concept.

Testnet
A Test-Network is an exact replica of an original blockchain, it follows the same
consensus as the mainnet.

Transactions on a testnet hold no value as the tokens are dummy, just like
Monopoly game.

A node in a test network can have any value except 1, depending upon the test
network. Ropston Network ID = 3, Rinkeby Network ID = 4

Performance of the testnet is used to evaluate the fundamental developments of


the network like security, transaction finality etc.

Developers use testnet to assess the functionality of their decentralized


applications and smart contracts before deploying on the mainnet, as anything
once deployed on mainnet cannot be changed. Testnet helps in rigorous testing.

No deployment & transaction fees are incurred, similar to how we don’t fuel the car
when doing the test drive.
https://medium.com/@0xblocktrain/mainnet-vs-testnet-the-difference-e96729f4a160 2/3
2/12/23, 4:29 PM Mainnet vs Testnet : The Difference | by BlockTrain: Learn Web3 | Medium

Mainnet and Testnet have different genesis blocks (The first block in a blockchain)

Testnet will receive the first updates for any changes/ developments over the
functionalities of the core system. Like, Ropston has completed the merge while
ETH mainnet will be merged in September.

Any questions? Join our discord for live sessions — https://discord.gg/bpjgRBUzKP

Find awesomeness here:

📌 youtube.com/0xblocktrain
Open in app Get unlimited access
📌 instagram.com/0xblocktrain
Search Medium
📌 twitter.com/0xblocktrain

Blockchain Ethereum Bitcoin Programming Technology

https://medium.com/@0xblocktrain/mainnet-vs-testnet-the-difference-e96729f4a160 3/3
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

Published in Level Up Coding

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Kevin Gabeci Follow

Feb 4, 2021 · 5 min read · · Listen

Save

How to use MetaMask: A step by step guide


MetaMask is one of the most popular browser extensions that serves as a way of
storing your Ethereum and other ERC-20 Tokens. The extension is free and secure,
allowing web applications to read and interact with Ethereum’s blockchain.

https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 1/11
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

Step 1. Install MetaMask on your browser.


To create a new wallet, you have to install the extension first. Depending on your
browser, there are different marketplaces to find it. Most browsers have MetaMask on
their stores, so it’s not that hard to see it, but either way, here they are Chrome, Firefox,
and Opera.

In this tutorial, I will be using Google Chrome as an example but the same steps apply
to different browsers as well. If, for some reason, the links above don’t work for you,
just search MetaMask Extension on your favorite search engine, and you can find it
there.

https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 2/11
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

Click on Install MetaMask as a Google Chrome extension.

Click Add to Chrome.

Click Add Extension.

https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 3/11
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 4/11
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

And it’s as easy as that to install the extension on your browser, continue reading the
next step to figure out how to create an account.

Step 2. Create an account.


Click on the extension icon in the upper right corner to open MetaMask.

To install the latest version and be up to date, click Try it now.

Click Continue.

You will be prompted to create a new password. Click Create.

https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 5/11
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

Proceed by clicking Next and accept the Terms of Use.

Click Reveal Secret Words. There you will see a 12 words seed phrase. This is really
important and usually not a good idea to store digitally, so take your time and write it
down.

https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 6/11
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

Verify your secret phrase by selecting the previously generated phrase in order.
Click Confirm.

And that’s it; now you have created your MetaMask account successfully. A new
Ethereum wallet address has just been created for you. It’s waiting for you to deposit
funds, and if you want to learn how to do that, look at the next step below.

Step 3. Depositing funds.


Click on View Account.

https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 7/11
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

You can now see your public address and share it with other people. There are
some methods to buy coins offered by MetaMask, but you can do it differently as
well; you just need your address.

The MetaMask extension will always be available in your browser’s toolbar, ready for
you to continue the journey into the Crypto world. It’s easily accessible and, as you saw
from these steps, simple to use as well. Sending coins is also very intuitive; there’s a big
send button, and the rest are easily understandable. But in case something wrong
happens, and you need to restore your account, you have this option. First, you have to
back it up, and let’s look at how we can do that.

Learn the Best Trading Strategy and elevate your


trading game!

https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 8/11
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

Volume Profile is arguably one of the best trading strategies in the world that has
proven results. Click on this link to get started.

How to backup and restore your wallet using the seed phrase?
Suppose you change your browser or computer and want to connect your wallet again;
here’s how to do it. First, you have to find your seed phrase, which you should have
stored to begin with.

Click on the account icon.

Click Settings.

Find Reveal Seed Words and click it.

Enter your password.

Now save the Secret Seed Phrase somewhere, preferably not digitally. The backup is
done now all you have to do is to learn the restoring process.

Open Metamask and click Import using the account seed phrase.

Enter your Seed Phrase.


https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 9/11
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

Create a new strong password.

Click Restore.

And that’s it; now you have successfully restored your account by following these easy
steps.
Open You
in app are fully prepared now to take on the crypto world as far as yourSign
wallet
up Sign In

management is concerned.
Search Medium

Closing Thoughts
Metamask is your bridge to the decentralized web, and you must understand how to
prepare for it carefully. Hopefully, this article has helped some of you find the answers
they needed, and if you have a question about the process, don’t hesitate to leave a
comment below. I will respond to all of you.

If you have any questions or suggestions about the article, don’t hesitate to leave a reply
in the comment section. Enjoyed what you read? Why not follow my Medium
newsletter so that you don’t miss out on any of my future articles? It’s simple, click
here, enter your email address, and press subscribe.

Do you enjoy reading articles on Medium? Consider becoming a member, there are a
lot of features, and you will get access to content from all creators for just $5 a month.
Use this link, and you also help me out to earn a small commission; click become a
member, and enter your information.

Level Up Coding
Thanks for being a part of our community! Level Up is transforming tech recruiting.
Find your perfect job at the best companies.

Level Up — Transforming the Hiring Process


🔥 Enabling software engineers to find the perfect role that they love 🧠
Finding talent is the most painful part of…
jobs.levelup.dev

https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 10/11
2/12/23, 4:34 PM How to use MetaMask: A step by step guide | by Kevin Gabeci | Level Up Coding

Metamask Ethereum Erc 20 Token Cryptocurrency

Sign up for Top Stories


By Level Up Coding

A monthly summary of the best stories shared in Level Up Coding Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review
our Privacy Policy for more information about our privacy practices.

Get this newsletter

About Help Terms Privacy

Get the Medium app

https://levelup.gitconnected.com/how-to-use-metamask-a-step-by-step-guide-f380a3943fb1 11/11
2/12/23, 4:36 PM Metamask: What it is and what it does | by Nihar Pachpande | Fifth P | Medium

Published in Fifth P

Nihar Pachpande Follow

May 15, 2021 · 3 min read · Listen

Save

Metamask: What it is and what it does

https://medium.com/the-5th-p/metamask-what-it-is-and-what-it-does-925629eeb80d 1/7
2/12/23, 4:36 PM Metamask: What it is and what it does | by Nihar Pachpande | Fifth P | Medium

Metamask is a browser extension designed to make use of Ethereum’s Dapp ecosystem


easier. It also serves as a wallet to hold ERC-20 tokens allowing the users to access
services built on the network via the wallet.

1. Metamask is a browser extentions that acts as an ethereum wallet.

2. It can be used to store Ether and other ERC — 20 tokens.

3. It serves as an interface to interact with various decentralised apps or Dapps.

If you are bored of just investing in crypto, or you have just started to go deeper into
the blockchain ecosystems then you would come to know about the decentralised apps
and the whole ecosystem of things built on Ethereum. Obviously you will start to hate

https://medium.com/the-5th-p/metamask-what-it-is-and-what-it-does-925629eeb80d 2/7
2/12/23, 4:36 PM Metamask: What it is and what it does | by Nihar Pachpande | Fifth P | Medium

the Ether gas fees later, but before you do that you will have to come across the world
of wallets. Something you haven’t touched since last 2 years irl.

As you know everything in the blockchain world is about who can process the larger
number of transactions at lowest amount of time with fewer errors. In 2017,
Cryptokitties which is one of the weirdest but most popular Dapps on the ethereum
network crashed the network with its more than 1.3 million transactions. Also the
Dapps are something too difficult to use for some users. So Metamask was created to
make the world of dapps of easier and accessible for everyone.

What is MetaMask?

https://medium.com/the-5th-p/metamask-what-it-is-and-what-it-does-925629eeb80d 3/7
2/12/23, 4:36 PM Metamask: What it is and what it does | by Nihar Pachpande | Fifth P | Medium

What makes Metamask better:


Popular — it is commonly used so users only need one plugin to access a wide
range of Dapps.

Simple — Instead of managing private keys, users just need to remember a list of
words and transactions are signed on their behalf.

Saves space — Users don’t have to download the Ethereum blockchain as it sends
requests to nodes outside of the user’s computer.

Integrated — Dapps are designed to work with it, so it becomes much easier to send
Ether in and out.

https://medium.com/the-5th-p/metamask-what-it-is-and-what-it-does-925629eeb80d 4/7
2/12/23, 4:36 PM Metamask: What it is and what it does | by Nihar Pachpande | Fifth P | Medium

What disadvantages does it have?


Third-party — MetaMask holds private keys within the user’s browser. This is less
safe than a hardware or paper wallet. It is a reasonable compromise for the ease-
of-use.

External nodes — Instead of being a full node, it relies on external nodes which
sometimes have downtime that can cause MetaMask to stop working.

MetaMask alternatives
Parity — Another browser-based wallet that provides access to Dapps and
Ethereum transactions.

Mist browser — A browser designed to access Dapps which works with Mist wallet,
a full node Ethereum wallet.

MyEtherWallet — A similarly popular online wallet which is based on Ethereum


coins and tokens. It allows you to make transactions without needing to download
the Ethereum blockchain but doesn’t integrate into Dapps in the same way.
https://medium.com/the-5th-p/metamask-what-it-is-and-what-it-does-925629eeb80d 5/7
2/12/23, 4:36 PM Metamask: What it is and what it does | by Nihar Pachpande | Fifth P | Medium

Open in app Get unlimited access

Search Medium

Other advantages:

https://medium.com/the-5th-p/metamask-what-it-is-and-what-it-does-925629eeb80d 6/7
2/12/23, 4:36 PM Metamask: What it is and what it does | by Nihar Pachpande | Fifth P | Medium

Securing Your Wallet in MetaMask Mobile

MetaMask integrated with hardware wallets Trezor and Ledger so that users can use
the service while keeping their crypto on a hardware wallet.

Blockchain Metamask Ethereum

Sign up for FifthP


By Fifth P

Keep reading Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/the-5th-p/metamask-what-it-is-and-what-it-does-925629eeb80d 7/7
2/12/23, 4:38 PM What is MetaMask Wallet?. Description | by Technologies In Industry 4.0 | DataDrivenInvestor

Published in DataDrivenInvestor

Technologies In Industry 4.0 Follow

Sep 19, 2021 · 4 min read · Listen

Save

What is MetaMask Wallet?

https://medium.datadriveninvestor.com/what-is-metamask-wallet-f4da4f92be02 1/6
2/12/23, 4:38 PM What is MetaMask Wallet?. Description | by Technologies In Industry 4.0 | DataDrivenInvestor

Description
MetaMask is a lightweight software cryptocurrency wallet. It is used to interrelate with
the Ethereum block chain. It may be used on Chrome, Firefox and Brave browsers.
This is wallet that aids in sending and receiving Ether. It permits users to store and
manage account keys, tokens, and securely link to decentralized applications via a
well-matched web browser. MetaMask may be downloaded from https://metamask io/.

History and Development

https://medium.datadriveninvestor.com/what-is-metamask-wallet-f4da4f92be02 2/6
2/12/23, 4:38 PM What is MetaMask Wallet?. Description | by Technologies In Industry 4.0 | DataDrivenInvestor

MetaMask was shaped in 2016.

Block chain software company ConsenSys created MetaMask.

MetaMask initiated releasing mobile app versions in starting 2019. It was for closed
beta testing.

It was observed by their official public announcement for iOS and Android in
September 2020.

By way of of September 2020, MetaMask’s browser extension had about 400,000


users, according to Bloomberg News.

How does MetaMask work?


The wallet works with JavaScript by adding a web3 object into the website page we are
on. Always keep in mind that this does not change the website in any way. In its place,
it only enhances a functionality that makes it possible to access the Ethereum
platform.

How to Set Up MetaMask on Computer?


Make sure that computer has a Brave, Firefox or Chrome browser prior to set up and
start using MetaMask. These are free browsers we can download with comfort.
Following is the process of setting up the wallet.

Open the MetaMask homepage to add the extension on the browser we will be
using.

A MetaMask icon will appear on the browser instantly. Click on the icon to open
the application.

Make a new wallet and set a strong password.

MetaMask will show a 12-word seed phrase after setting the password. This is very
critical as it would be wanted in the event that we lose our password. We can copy
the seed or save it as a file.

The wallet is set, and we may now start using it to receive and send supported
digital tokens.
https://medium.datadriveninvestor.com/what-is-metamask-wallet-f4da4f92be02 3/6
2/12/23, 4:38 PM What is MetaMask Wallet?. Description | by Technologies In Industry 4.0 | DataDrivenInvestor

How to use MetaMask to Buy and Send Tokens?


We only need to click “Buy” on the MetaMask interface.

To fund the account, select one of the integrated exchanges, ShapeShift or


Coinbase.

The tokens we want to buy would come from sellers on the ShapeShift or Coinbase
exchange yet we are on MetaMask.

Just click “Send” and enter the public address of the recipient to send tokens from
MetaMask.

Ensure that we also have enough tokens in our wallet to send and meet the
transaction fee.

Approve the transaction details and accept.

MetaMask pros and cons


Pros

This is open source software. It has a great development community that pays to its
development.

Hierarchical deterministic settings are being used by the wallet that supports users
to endorsement their accounts.

MetaMask has combined ShapeShift and Coinbase exchanges to make it easy to


exchange ETH and other ERC-20 tokens

The wallet has an instinctive user interface.

MetaMask has a consistent customer support.

Cons

There is a bigger risk of being hacked than with other type of wallets, for example
hardware wallets, equally an online wallet.

Most browsers for example Chrome gather user info that could compromise
privacy.
https://medium.datadriveninvestor.com/what-is-metamask-wallet-f4da4f92be02 4/6
2/12/23, 4:38 PM What is MetaMask Wallet?. Description | by Technologies In Industry 4.0 | DataDrivenInvestor

The main inadequacy of the wallet is that it is a web-based wallet.

It is worthwhile to only use the wallet to store a small amount of crypto coins to
stay safe.

We could reflect it the store for tokens to buy products for instance DApps on the
Ethereum block chain.

Do not hesitate to use MetaMask if new to Ethereum.

Only use it with great caution. Remember to all the time keeping the computer,
browser, and MetaMask informed for improved security.

Breaking changes
MetaMask will stop adding window.web3 and make the following breaking changes to
our window ethereum API:

End the 0-padding eth_chainId return values.

Halt producing the chainIdChanged event, and in its place only emit
chainChanged.

Eliminate ethereum.publicConfigStore.

Get rid of the ethereum._metamask.is Enabled experimental method.

Remove the ethereum._metamask.is Approved experimental method.

We’re good to go, if we do not use any of the features that are being removed as part of
this update.

Security updates
It’s a significant update that SES lock down is now in production. This will continue to
keep MetaMask users safe in the long run. Transaction management has been
improved, therefore, we can transact more reasonably, quickly and consistently.
Progressive gas estimation API has also been launched to crush first inside Swaps
feature, and then for all Meta Mask transactions.

https://medium.datadriveninvestor.com/what-is-metamask-wallet-f4da4f92be02 5/6
2/12/23, 4:38 PM What is MetaMask Wallet?. Description | by Technologies In Industry 4.0 | DataDrivenInvestor

This API totals multiple gas approximation services to deliver the best gas estimations.
This application transports more consistency and steadiness to gas prices in
MetaMask.

What’s new in MetaMask Mobile?


The browser is more secure than ever.

Web3 addition to iframes will be temporarily disabled due to limitations with the
web view implementation.

Therefore, dapps that run inside iframes, or rely on this functionality, may not
work. This makes using web3 sites in the MetaMask mobile browser more secure.

For more details visit:https://www.technologiesinindustry4.com/2021/01/what-is-


metamask-wallet.html
Open in app Get unlimited access

Search Medium

Blockchain Blockchain Technology Blockchain Development Ethereum Blockchain

Metamask

Get an email whenever Enduring And Emergent Technologies Of Industry 4.0


publishes.
https://medium.com/subscribe/@bloggingtech260

Emails will be sent to [email protected]. Not you?

Subscribe

https://medium.datadriveninvestor.com/what-is-metamask-wallet-f4da4f92be02 6/6
2/12/23, 4:40 PM Guide: How to setup MetaMask. MetaMask is just an Ethereum Browser… | by Sun Exchange | Medium

Sun Exchange Follow

Jul 31, 2018 · 2 min read · Listen

Save

Guide: How to setup MetaMask

MetaMask is just an Ethereum Browser and Ether wallet. It interacts with Ethereum
Dapps and Smart Contracts without running a full Ethereum node. MetaMask add-on
can be installed on Chrome, Firefox, Opera, and the new Brave browser. It also allows
you to store ERC20 tokens.

https://medium.com/@alias_73214/guide-how-to-setup-metamask-d2ee6e212a3e#:~:text=Open up a new Chrome,corner of the chrome browser. 1/6


2/12/23, 4:40 PM Guide: How to setup MetaMask. MetaMask is just an Ethereum Browser… | by Sun Exchange | Medium

First, let’s setup MetaMask in the Chrome browser. Open up a new Chrome browser
window and navigate to
https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbef
gpgknn and then click on ‘ADD TO CHROME’ to install MetaMask plugin.

After installing, click on the MetaMask icon on the top right corner of the chrome
browser. It will open up MediMask UI, scroll all the way down and click Accept to
agree MetaMask’s terms of use.

https://medium.com/@alias_73214/guide-how-to-setup-metamask-d2ee6e212a3e#:~:text=Open up a new Chrome,corner of the chrome browser. 2/6


2/12/23, 4:40 PM Guide: How to setup MetaMask. MetaMask is just an Ethereum Browser… | by Sun Exchange | Medium

Then enter a password, confirm the password, and then click Create for a new
Ethereum account. This account allows to send and receive Ether, ERC20 tokens and
also allows you to deploy Smart Contracts.

https://medium.com/@alias_73214/guide-how-to-setup-metamask-d2ee6e212a3e#:~:text=Open up a new Chrome,corner of the chrome browser. 3/6


2/12/23, 4:40 PM Guide: How to setup MetaMask. MetaMask is just an Ethereum Browser… | by Sun Exchange | Medium

MetaMask will now show you a 12 word recovery key (Seed) as below.

https://medium.com/@alias_73214/guide-how-to-setup-metamask-d2ee6e212a3e#:~:text=Open up a new Chrome,corner of the chrome browser. 4/6


2/12/23, 4:40 PM Guide: How to setup MetaMask. MetaMask is just an Ethereum Browser… | by Sun Exchange | Medium

These 12 words are the only way to restore MetaMask accounts if you forget the
password. It should be stored in a safe location, such as in a notebook or USB key kept
in a safe. Then click on ‘I’VE COPIED IT SOMEWHERE SAFE’. The main screen of
MetaMask will open as below.

https://medium.com/@alias_73214/guide-how-to-setup-metamask-d2ee6e212a3e#:~:text=Open up a new Chrome,corner of the chrome browser. 5/6


2/12/23, 4:40 PM Guide: How to setup MetaMask. MetaMask is just an Ethereum Browser… | by Sun Exchange | Medium

Open in app Get unlimited access

Search Medium

That’s it you’ve just created a new Ethereum address using MetaMask! You’re address
can be found by clicking on the three little black dots and clicking “Copy Address to
clipboard”.

If anything is unclear please do not hesitate to reach out to us on Telegram or email us


at [email protected]

Ethereum Erc 20 Sunex Guides And Tutorials Blockchain

https://medium.com/@alias_73214/guide-how-to-setup-metamask-d2ee6e212a3e#:~:text=Open up a new Chrome,corner of the chrome browser. 6/6


2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

Decrypt Follow

Sep 23, 2020 · 6 min read · Listen

Save

MetaMask: The Beginner’s Guide


MetaMask is a browser extension designed to make accessing Ethereum’s Dapp
ecosystem easier. It also serves as a wallet for holding ERC-20 tokens allowing users to
access services built on the network via the wallet.

In brief
MetaMask is a browser plugin that serves as an Ethereum wallet.

Users can store Ether and other ERC-20 tokens in the MetaMask wallet.

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 1/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

The wallet can also be used to interact with decentralized applications, or dapps.

Popular decentralized application ( dapp) CryptoKitties crashed the Ethereum


blockchain with 1.3 million transactions in December 2017. But since then, user
numbers have dwindled into the hundreds.

For many users, dapps are just too difficult to use. MetaMask is hoping to change that,
lowering the barrier of entry to the wonderful world of dapps and bringing the
decentralized web to the mass market.

What is MetaMask?
MetaMask (which, like an editorially independent Decrypt, is funded by Ethereum
incubator ConsenSys) is a browser plugin that serves as an Ethereum wallet, and is
installed like any regular plugin. Once it’s installed, it allows users to store Ether and
other ERC-20 tokens, enabling them to make transactions to any Ethereum address.

What is MetaMask?

By connecting to Ethereum-based Dapps, users can spend their coins in games, stake
tokens in gambling applications and trade them on decentralized exchanges. 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.
https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 2/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

How to get started using MetaMask


Though it might seem complicated from the outset, 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.

Getting Started with MetaMask

First, you’ll need to download and install the official Metamask extension/addon for
your browser; either the Google Chrome extension or the Firefox addon depending on
your browser. For our guide, we’ll be using the Firefox version, but the steps are nearly
identical for other browsers too.

Once installed, you should see the below splash screen. Click the ‘Get Started’ button to
begin creating your Ethereum wallet using MetaMask.

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 3/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

On the next step, click the ‘Create a Wallet’ button.

You’ll then be asked if you want to help improve MetaMask. Click ‘No Thanks’ if this
doesn’t interest you, otherwise click ‘I agree’.

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 4/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

Pick a password on the next step. This needs to be at least 8 characters long. We
recommend using a completely unique password that hasn’t been used anywhere else,
and contains a mixture of upper and lower case letters, symbols, and numbers.

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 5/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

Read and accept the Terms of Use, and click ‘Create’ once your password has been set.

MetaMask will then present you with your 12-word backup phrase. You’ll need to write
this down in the same order displayed on your screen. This 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 back phrase will be able to
recover your funds, so keep it private.

Click ‘Next’ once you’ve written this down.

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 6/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

Confirm your backup phrase on the next screen by entering the words in the same
order saved previously. Click ‘Confirm’ once done.

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 7/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

You have now almost completed the MetaMask setup process. Just click ‘All Done’ on
the final page, and you will be automatically logged in to MetaMask. If you ever get
logged out, you’ll be able to log back in again by clicking the icon added to your web
browser (usually found next to the URL bar).

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 8/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

You will then be able to access your list of assets in the ‘Assets’ tab and view your
transaction history in the ‘Activity’ tab.

Sending transactions 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, using information from
ETH Gas Station or similar platforms to choose a more suitable gas price.

After clicking ‘Next’, you will then be able to either confirm or reject the transaction on
the subsequent page.

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 9/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

To use MetaMask to interact with a DApp or smart contract, you’ll usually need to find
a ‘Connect to Wallet’ button or similar on the platform you are trying to use. After
clicking this, you should then see a prompt asking whether you want to let the DApp
connect to your wallet.

The below example is for Uniswap, but a similar process should be observed for other
DApps. Simply connecting with a DApp means it can view your addresses-they cannot
access your funds.

Once connected, you’ll then be able to interact with the DApps and use its features.

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 10/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

Dapps automatically connect to MetaMask, simplifying the connection process. Within


the Dapp, if payment is required, a pop-up window will appear asking to confirm the
transaction from the MetaMask account.

What advantages does MetaMask have?


😻 Popular — it is commonly used so users only need one plugin to access a wide
range of Dapps.

🕐 Simple — Instead of managing private keys, users just need to remember a list
of words and transactions are signed on their behalf.

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 11/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

💽 Saves space — Users don’t have to download the Ethereum blockchain as it


sends requests to nodes outside of the user’s computer.

🔗 Integrated — Dapps are designed to work with it, so it becomes much easier to
send Ether in and out.

What disadvantages does it have?


👪 Third-party — MetaMask holds private keys within the user’s browser. This is
less safe than a hardware or paper wallet. It is a reasonable compromise for the
ease-of-use.

🖥️External nodes — Instead of being a full node, it relies on external nodes which
sometimes have downtime that can cause MetaMask to stop working.

Alternatives to MetaMask
Parity — Another browser-based wallet that provides access to Dapps and
Ethereum transactions.

Mist browser — A browser designed to access Dapps which works with Mist wallet,
a full node Ethereum wallet.

MyEtherWallet — A similarly popular online wallet which is based on Ethereum


coins and tokens. It allows you to make transactions without needing to download
the Ethereum blockchain but doesn’t integrate into Dapps in the same way.

Did you know?


MetaMask integrated with hardware wallets Trezor and Ledger so that users can use
the service while keeping their crypto on a hardware wallet.

The future of MetaMask


Since its launch, MetaMask has provided an easy access point for the growing dapp
space. As new dapp products and services emerge, user numbers are picking up,
hitting a million users of its Chrome extension in February 2020.

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 12/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

Open in app Get unlimited access

Search Medium
In September 2020, MetaMask launched MetaMask Mobile for Android and iPhone, its
first smartphone app.

Introducing MetaMask Mobile

The smartphone app enables users to create new accounts or log in with their existing
MetaMask account, and provides much the same functionality as the browser-based
https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 13/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium

version. Users get a token wallet, key vault, and login so they can manage digital assets
and access dapps such as Uniswap and OpenSea.

Originally written by Daniel Phillips and published at Decrypt: MetaMask: What It Is and
How To Use It

Metamask Metamask Mobile Crypto Wallet Erc 20 Ethereum

https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 14/14
2/12/23, 4:44 PM The Beginners Guide to Using an Ethereum Test Network | by Geoff Hayes | Compound | Medium

Published in Compound

Geoff Hayes Follow

Feb 17, 2018 · 3 min read · Listen

Save

The Beginners Guide to Using an Ethereum Test


Network
Before a project launches on the Ethereum blockchain (or before changes are made to
the blockchain itself), a version is deployed to an Ethereum Test Network (“testnet”),
which simulates Ethereum — this gives developers, the community, and you a chance
to kick the tires before real assets are involved.

Ether and tokens on a testnet are easy to obtain, and carry no real-world value — still, it
can be fun to own 10,000 Ether or a trillion tokens on a testnet.

Testnets
There are three testnets currently in use, and each behaves similarly to the production
blockchain (where your real Ether and tokens reside). Developers may have a personal
preference or favorite testnet, and projects typically develop on only one of them.

Ropsten: A proof-of-work blockchain that most closely resembles Ethereum; you


can easily mine faux-Ether.

Kovan: A proof-of-authority blockchain, started by the Parity team. Ether can’t be


mined; it has to be requested.

Rinkeby: A proof-of-authority blockchain, started by the Geth team. Ether can’t be


mined; it has to be requested.
https://medium.com/compound-finance/the-beginners-guide-to-using-an-ethereum-test-network-95bbbc85fc1d 1/4
2/12/23, 4:44 PM The Beginners Guide to Using an Ethereum Test Network | by Geoff Hayes | Compound | Medium

Connecting to a testnet
Ethereum addresses & private keys that work on Ethereum, work on each testnet — be
extremely careful not to send Ether or tokens on the Ethereum main-net to a testnet address,
or you will lose your assets.

Before proceeding, Compound recommends creating a new wallet specifically for use
on testnets; you’ll never accidentally send Ether, if you don’t have Ether.

MetaMask
Using MetaMask to send Ether and tokens on a testnet is straightforward; in the top-
left of MetaMask, you can select an Ethereum network.

Switch from the Main Ethereum Network to Rinkeby (or other testnet) and you should
see your balances and transaction history update, to reflect the network you’ve
selected.

https://medium.com/compound-finance/the-beginners-guide-to-using-an-ethereum-test-network-95bbbc85fc1d 2/4
2/12/23, 4:44 PM The Beginners Guide to Using an Ethereum Test Network | by Geoff Hayes | Compound | Medium

Now, when you create a transaction using MetaMask, it will be transmitted to the
network you’ve selected.

MyEtherWallet & MyCrypto

MyEtherWallet

MyCrypto

MyEtherWallet and MyCrypto similarly allows you to select an alternate network, in


the top right of the screen. When you do so, all transactions, and contract calls are
conducted on the network that you’ve chosen.

Acquiring Ether
It’s time to load up your new account with faucet Ether.

Kovan
The Kovan Faucet requires you to provide your Github account credentials to Parity,
and allows you to request Kovan Ether once every 24 hours.

Kovan Fauctet

https://medium.com/compound-finance/the-beginners-guide-to-using-an-ethereum-test-network-95bbbc85fc1d 3/4
2/12/23, 4:44 PM The Beginners Guide to Using an Ethereum Test Network | by Geoff Hayes | Compound | Medium

Rinkeby
The Rinkeby Faucet requires that you make a social media post including your address
on either Facebook, Twitter or Google Plus. Once you do so, put the direct link to that
post in the input box and select 18.75 Ethers / 3 days from the dropdown on the right.

Rinkeby Faucet

Open in app Get unlimited access


Ethereum Blockchain Testing Development

Search Medium

https://medium.com/compound-finance/the-beginners-guide-to-using-an-ethereum-test-network-95bbbc85fc1d 4/4
2/12/23, 4:46 PM How to Claim Test ETH from Rinkeby Faucet - Becky | KAKI - Medium

Becky | KAKI Follow

Jul 17, 2021 · 1 min read · Listen

Save

How to Claim Test ETH from Rinkeby Faucet


1. Open your wallet, select the Rinkeby test network, and copy your wallet address

https://kakifi.medium.com/how-to-claim-test-eth-from-rinkeby-faucet-59783089d027 1/3
2/12/23, 4:46 PM How to Claim Test ETH from Rinkeby Faucet - Becky | KAKI - Medium

2. Post a tweet, the content is your wallet address, copy the link of this tweet.

3. Go to the Rinkeby faucet https://www.rinkeby.io/#faucet, enter your tweet link, click


on “give me ether” and wait till you pass the verification.

Open in app Get unlimited access

Search Medium

https://kakifi.medium.com/how-to-claim-test-eth-from-rinkeby-faucet-59783089d027 2/3
2/12/23, 4:46 PM How to Claim Test ETH from Rinkeby Faucet - Becky | KAKI - Medium

You are good to go! Good luck!

Ethereum Rinkeby Test Network Rinkeby Arbitrum Faucet

https://kakifi.medium.com/how-to-claim-test-eth-from-rinkeby-faucet-59783089d027 3/3
2/12/23, 4:48 PM Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network - GeeksforGeeks

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+

Ethereum Blockchain – Getting Free Test


Ethers For Rinkeby Test Network
Difficulty Level : Medium ● Last Updated : 11 May, 2022

Read Discuss

There is a term called gas that we all pay when we want to make a transaction or execute

a contract on the Ethereum blockchain platform. So, typically gas is the internal pricing

for running a transaction or contract in the Ethereum network.

Ever y time a transaction(development purpose) is to be carried out or any contract

deployed on the local blockchain, MetaMask displays a prompt, detailing the requested

transaction, along with the Gas price(ver y low) as well as any other Ether amount that

might have to be sent and for that, test ethers will be used for payment. Below is an

example of MetaMask prompt message for paying gas.

Note: Test ethers are used only for development purposes in a way they are fake ethers.

Start Your Coding Journey Now! Login Register


https://www.geeksforgeeks.org/ethereum-blockchain-getting-free-test-ethers-for-rinkeby-test-network/ 1/10
2/12/23, 4:48 PM Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network - GeeksforGeeks

Steps To Get Free Ethers

Step 1: Set up your MetaMask properly. 

First, go to the Chrome web store and search for MetaMask. You can get MetaMask

extension from here.

Install the extension.

For using MetaMask you need to finish the signup/new-account procedure.

Step 2: Switch your network to the Rinkeby test network in MetaMask. You will see your

current balance for the Rinkeby test network.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/ethereum-blockchain-getting-free-test-ethers-for-rinkeby-test-network/ 2/10
2/12/23, 4:48 PM Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network - GeeksforGeeks

Step 3: Copy your account address by just clicking on your account address.

Step 4: Go to the Rinkeby Faucet website using the below-given URL-

https://faucet.rinkeby.io/

Step 5: You will land on an inter face like this:

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/ethereum-blockchain-getting-free-test-ethers-for-rinkeby-test-network/ 3/10
2/12/23, 4:48 PM Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network - GeeksforGeeks

Step 6: Now there are two ways to get ether either using Twitter post or Facebook post.

You can go with any of them though going with Twitter will be an easy choice.

Step 7: Tweet the account address that you have copied earlier. Below is an example of

the tweet.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/ethereum-blockchain-getting-free-test-ethers-for-rinkeby-test-network/ 4/10
2/12/23, 4:48 PM Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network - GeeksforGeeks

Step 8: Copy your Tweet URL and paste it in the input box on the page of the Rinkeby

Faucet website.

Step 9: On the right side of the input box there is a “Give me Ether ” dropdown containing

three options with ether amounts click on any clicked amount of test ether will be

transferred to your given account address in the tweet.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/ethereum-blockchain-getting-free-test-ethers-for-rinkeby-test-network/ 5/10
2/12/23, 4:48 PM Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network - GeeksforGeeks

Step 10: The ether transfer process may take 2-15 minutes to be done. When test ethers

funded to your account you will see something like this.

Af ter the process completed you will see something like this in your MetaMask.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/ethereum-blockchain-getting-free-test-ethers-for-rinkeby-test-network/ 6/10
2/12/23, 4:48 PM Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network - GeeksforGeeks

Like 22

Previous Next

Related Articles

1. Ethereum (ETH) vs Ethereum Classic (ETC) in Blockchain

2. Use of Ethereum's RLPx in Ethereum Ecosystem

3. Blockchain - Hyperledger vs Ethereum


Start Your Coding Journey Now!
https://www.geeksforgeeks.org/ethereum-blockchain-getting-free-test-ethers-for-rinkeby-test-network/ 7/10
2/12/23, 4:48 PM Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network - GeeksforGeeks

4. How to Add Another Miner to Existing Private Ethereum Blockchain?

5. Ethereum Enterprise Alliance (EEA) in Blockchain

6. Components of Ethereum Network

7. How to Setup Your Own Private Ethereum Network?

8. Components of Blockchain Network

9. Helium Blockchain Network

10. Supercomputing Organized By Network Mining (SONM) in Blockchain

Ar ticle Contributed By :

raman111
@raman111

Vote for difficulty

Current difficulty : Medium

Easy Normal Medium Hard Expert

Improved By : unclebigbay

Article Tags : Blockchain

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/ethereum-blockchain-getting-free-test-ethers-for-rinkeby-test-network/ 8/10
2/12/23, 4:48 PM Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network - GeeksforGeeks

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Advertise with us Video Tutorials
Courses

News Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Start Your
WebCoding Journey Now!
Development Contribute
https://www.geeksforgeeks.org/ethereum-blockchain-getting-free-test-ethers-for-rinkeby-test-network/ 9/10
2/12/23, 4:48 PM Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network - GeeksforGeeks

Web Tutorials Write an Article


Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/ethereum-blockchain-getting-free-test-ethers-for-rinkeby-test-network/ 10/10
2/12/23, 4:50 PM Transferring Ether using Rinkeby/Metamask | by Paul Elis | Medium

Paul Elis Follow

Dec 15, 2018 · 1 min read · Listen

Save

Transferring Ether using Rinkeby/Metamask


Now that we have test Ether in one of our accounts we are going to create another
account to transfer Ether to. Let’s go to our Metamask extension within the browser
and do as shown:

Click the person icon in the top right and “Create Account”

https://medium.com/@paulelis/transferring-ether-using-rinkeby-metamask-7ff7a895009 1/4
2/12/23, 4:50 PM Transferring Ether using Rinkeby/Metamask | by Paul Elis | Medium

“Copy Address to clipboard”

https://medium.com/@paulelis/transferring-ether-using-rinkeby-metamask-7ff7a895009 2/4
2/12/23, 4:50 PM Transferring Ether using Rinkeby/Metamask | by Paul Elis | Medium

Open in app Get unlimited access

Search Medium

Then click “Send” from Account 1

Paste the copied Account 2 address in the “Recipient Address” field

https://medium.com/@paulelis/transferring-ether-using-rinkeby-metamask-7ff7a895009 3/4
2/12/23, 4:50 PM Transferring Ether using Rinkeby/Metamask | by Paul Elis | Medium

Let’s “Submit” !

Ethereum

https://medium.com/@paulelis/transferring-ether-using-rinkeby-metamask-7ff7a895009 4/4
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

Bahurudeen Follow

Feb 24, 2018 · 4 min read · Listen

Save

Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether.

In this blog let’s see what MetaMask is, how to setup and use it with Rinkeby Test
Network.

MetaMask is just an Ethereum Browser and Ether wallet. It interacts with Ethereum
Dapps and Smart Contracts without running a full Ethereum node. MetaMask add-on
can be installed on Chrome, Firefox, Opera, and the new Brave browser.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 1/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

First, let’s setup a MetaMask on Chrome browser. Open up a new Chrome browser
window and navigate to
https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbef
gpgknn and then click on ‘ADD TO CHROME’ to install MetaMask plugin.

After installing, click on the MetaMask icon on the top right corner of the chrome
browser. It will open up MediMask UI, scroll all the way down and click Accept to
agree MetaMask’s terms of use.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 2/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

Then enter password, confirm password, and then click Create for a new Ethereum
account. This account allows to send and receive Ether and also allows to deploy Smart
Contracts.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 3/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

MetaMask will show up 12 words recovery key (Seed) as below.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 4/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

These 12 words are the only way to restore MetaMask accounts if you forget the
password. It should be stored in a safe location. Then click on ‘I’VE COPIED IT
SOMEWHERE SAFE’. The main screen of MetaMask will open as below.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 5/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

In the upper left corner, click “Main Network” Then select “Rinkeby Test Network”

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 6/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

The Rinkeby Test Network is used to test the code and get free Ether to test Smart
Contracts.

Let’s see how to get free Ether for Rinkeby Test Network from
https://faucet.rinkeby.io/. First we need to publish a new public post with Ethereum
address. Open up MetaMask window, click on the 3 dots and then click on “Copy
Address to clipboard” to get the Account1 address.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 7/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

Open up a new browser window, navigate to https://plus.google.com/ , Sign in with


your google account, click on the little red circle on the right bottom corner of the page

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 8/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

Let’s Create the new public post with Rinkeby Test Network’s Address. Paste the
Account1 address in content area and click Post.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 9/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

The created post immediately displays on top of the page, Click on the arrow on the top
right corner of the post and copy the url to clipboard.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 10/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

Open up a new browser window and navigate to https://faucet.rinkeby.io/ then paste


the newly created post’s url on text area, and then select ‘18.75 Ethers / 3 days’. It takes
some time for processing.

Open up MetaMask window and make sure that 18.750 ETH is added to Account1.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 11/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

Let’s create an another account, click on Account menu and then click Create Account
for another new account.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 12/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

Open in app Get unlimited access

Search Medium

Initially Account2 has 0 ETH available balance. Let’s send 0.1 ETH to Account2 from
Account1. Copy Account2 address to clipboard make sure Account2 is selected.

Choose Account1 from account menu, and then click Send.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 13/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

Paste Account2 address in Recipient Address, then enter 0.1 Ether, and then click
Next.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 14/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

Then click Submit to confirm Transaction. It takes few seconds for processing.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 15/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

Choose Account2 and make sure 0.1 Ether is added.

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 16/17
2/12/23, 4:51 PM Setup a MetaMask Ethereum Wallet and use it to Send and Receive Ether. | by Bahurudeen | Medium

We will see how to create Smart Contracts and how to deploy it to Rinkeby Test
Network in the next post.

If this post is useful, please help others by clapping your hands below —
thanks!

Ethereum Metamask Smart Contracts Blockchain Ether

https://medium.com/@mail.bahurudeen/setup-a-metamask-ethereum-wallet-and-use-it-to-send-and-receive-ether-4f3b99360e4f 17/17
2/12/23, 4:54 PM Deploy your first smart contract in Ethereum network | by Shams Nahid | Medium

Shams Nahid Follow

Jan 11, 2020 · 5 min read · Listen

Save

Deploy your first smart contract in Ethereum


network
Originally published in blog.shams-nahid.com.

Source Code Live

Bitcoin raised the blockchain technology, where Ethereum took it to the next level.
Often said, Blockchin 2.0 , Ethereum proved the possibility of blockchain technology

https://bmshamsnahid.medium.com/deploy-your-first-smart-contract-in-ethereum-network-3b70ca6ed544 1/8
2/12/23, 4:54 PM Deploy your first smart contract in Ethereum network | by Shams Nahid | Medium

beyond the financial sector. This public blockchain network is famous for allowing the
implementation of smart contracts. Smart Contract acts as a locker where it can be
unlocked by certain conditions. Solidity programming language can be used to
develop these Smart Contract .

By the end of this article,

You will have a deployed smart contract in Ethereum network (Rinkeby Testnet)

You will interact with your smart contract using a react and node app.

Prerequisite Technologies In Your Machine


Node 10.17.0

React

MetaMask

Metamask Plugin Installation


Metamask is a pretty neat browser plugin. It allows an end-user to interact with a dAPP
on ethethreum network. With metamask , end-user do not have to run a ethereum node .

Metamask also, handle users Ethereum Wallet .

Install the Chrome Browser in your machine

Go to Chrome Web Store and search for Metamask

Open Metamask offered by https://metamask.io/

Click Add to Chrome and confirm by Add Extension

Now Metamask should be available in your Chrome Extension list

Create a Wallet
Using a wallet, end users are allowed to send and receive ethers from dApps.

Open Metamask and click Get Started

https://bmshamsnahid.medium.com/deploy-your-first-smart-contract-in-ethereum-network-3b70ca6ed544 2/8
2/12/23, 4:54 PM Deploy your first smart contract in Ethereum network | by Shams Nahid | Medium

If you already have a wallet then go to Import Wallet

To create a new wallet go for Create Wallet

Agree with Privacy Policy , put a password, and create the wallet

Reveal and save the Backup Phrase in a secure place

Now go to Next Section , select the words according to the phrase

Now your wallet is All Set Up , You should get your Account Address

Connect to Rinkeby network and get fake Ether

Testnet like Rinkeby , does not deal with actual money. To deploy and make a
transaction in ethereum testnet we will require the fake ether.

Open the Metamask plugin

On top-right switch to Rinkeby Network from Main Network

Go to free ether supplier site. We will follow their twitter instruction.

Go to Twitter and create a tweet of our Ethereum Account Address

If your Ethereum Account Address is 0x0000000000000000000000000000000000000000 ,

then just tweet the address

You can include anything with the address

It is valid, till the tweet contains the address.

Open the published tweet in a new page and copy the page link .

Put the tweet link in the free ether supplier the site and from the Give me ether ,

select a suitable package

Now in your Metamask , fake ether should appear

Sometimes it takes a little more time to transaction , so wait and also make sure
you Metamask is connected to the Rinkeby network.

https://bmshamsnahid.medium.com/deploy-your-first-smart-contract-in-ethereum-network-3b70ca6ed544 3/8
2/12/23, 4:54 PM Deploy your first smart contract in Ethereum network | by Shams Nahid | Medium

Run and Simulate Contract through Remix Ide


Remix is an online IDEto create a solidity smart contract. It also has the feature to
compile , run , deploy and simulate smart contracts.

Open Remix IDE.

Select environment Solidity

Go to File Explorer Tab and create a file Lottery.sol

Get the Contract Code

Go to Solidity Compiler Tab and Select

Compiler Version to 0.4.17

Language as Solidity

EVM as Compiler Default

Now click Compile Lottery.sol

You can enable auto-compile by check the checkbox Auto Compile

Go to Deploy And Run Transaction Tab and Deploy the contract in local EVM

Your contract functionality will be available in Deploy And Run Tracsaction tab,
under the Deployed Contract section

Deploy the contract to Rinkeby Network through Remix Ide


Testnets provide developers a place to kick the smart contract and test before the
real assets are involved. These Testnets behave very much like the main-net and does
not require actual money( ether ). Here we are going to try Rinkeby Testnet .

Make sure you run the Lottery contract using the previous section instructions

Open Metamask , put the password and make sure, you are connected to the Rinkeby

network.

Go to Deployed And Run Transaction tab and select


https://bmshamsnahid.medium.com/deploy-your-first-smart-contract-in-ethereum-network-3b70ca6ed544 4/8
2/12/23, 4:54 PM Deploy your first smart contract in Ethereum network | by Shams Nahid | Medium

Environment is Injected Web3

As account, your Metamask wallet address should be selected

Make sure you have enough ether in your wallet to deploy the contract

Now click Deploy . This will deploy your contract to the Rinkeby network.

In the Remix IDE , check Log Section and grab the Transaction Hash and store it.

Go to Ether Scan and search for the Transaction Hash . You will get the Deployed

Contract Address . Also, this Contract Address will be required further.

Verify and Publish Your Contract(Optional)


Everything on Ethereum Network is public, including smart contract byte-code . Byte-

code is low-level stuff and very difficult to understand. You can publish your solidity

source code by verify and publish in ether-scan . If you want more people to interact
with your smart contract , you should verify and publish your smart-contract .

From Ether Scan, search the Transaction Hash or Contract Address and go to
Contract Details page

From Contract Details , go to Contract tab

Click Verify and Publish , and set

Compiler Type as Solidity(Single File)

Compiler Version as 0.4.17

License Type as Whatever Your's Requirement

Click Continue and put Contract Code from Remix IDE or Gist

Click Verify and Publish and you should get the Contract Byte Code and Contract

ABI

Store the Contract Byte Code and Contract ABI for future use

https://bmshamsnahid.medium.com/deploy-your-first-smart-contract-in-ethereum-network-3b70ca6ed544 5/8
2/12/23, 4:54 PM Deploy your first smart contract in Ethereum network | by Shams Nahid | Medium

Clone Repo
This is a react app to interact with our lottery contract.

git clone https://github.com/bmshamsnahid/Decentralized-Lottery-App

Enable Environment
To run the react app, please ensure the following environment .

> Make sure `node.js` is installed. To check version, use `node -v`.
This is tested in node 10.17.0
>(Optional, only for node.js deployment) In `\config` directory,
create file `dev.js` and put local db url with username and password.
An example is provide in the same directory named `example-dev.js`
> To use your own contract, update the `/ui/src/contractConfig.js` as
your `Contract Address` and `Contract ABI`

Run Application
To run your app locally, you do not need a server . But for deployment, the static

react app should be hosted in node app .

Server

> Install server side dependency by `npm i` in the project-root


directory. In case you face any problem, use `yarn` package manager.
> Run server by `npm run dev`
> Server is running in `http://localhost:8080`

Client

> Go to `\ui` and install dependencies `npm i`


> Update `api url` to local node app `http://localhost:8080` in
`App.js` file.
> Run the front end `npm start`
https://bmshamsnahid.medium.com/deploy-your-first-smart-contract-in-ethereum-network-3b70ca6ed544 6/8
2/12/23, 4:54 PM Deploy your first smart contract in Ethereum network | by Shams Nahid | Medium

> Your app is available in `http://localhost:3000`


> Make sure `metamask` is installed
> Make sure you are connected to `Rinkeby` network and have enough
ether

You are all set to go.

Test Application
It is important to test your smart-contract before deployment.

> To install dependency, Go to root directory and run `npm i`


> Invoke unit-test by `npm run test`

A deployed version can be found here.

References:
Contract Source Code

Metamask Installation

Ethereum Contract

Verification & publish

TxAddress

Smart Contract Link

Udemy

TxHash: 0x3349da25727612e32d292b2fd1f1d2ac5d07b35b9b0f62f356f60d3aa65c6241

From account: 0x612a306d2707cf0B49A5d76594482f7AfCda506c

Contract address: 0x8C9815E2372bC6F9Dec915751B31666aB08b2edb

Meta text

https://bmshamsnahid.medium.com/deploy-your-first-smart-contract-in-ethereum-network-3b70ca6ed544 7/8
2/12/23, 4:54 PM Deploy your first smart contract in Ethereum network | by Shams Nahid | Medium

In this article, we will simulate a solidity smart contract in remix IDE . Then we will
cover test , deployment and interaction for the smart contract. For interaction we
will use the node server and react library. Also, make sure we remove read

dependency from metamask wallet.

Ethereum Smart Contracts React Nextjs Web 3


Open in app Get unlimited access

Search Medium

https://bmshamsnahid.medium.com/deploy-your-first-smart-contract-in-ethereum-network-3b70ca6ed544 8/8
2/12/23, 4:57 PM An Introduction of Solidity, Ethereum’s Programming Language | by Kevin Gabeci | DataDrivenInvestor

Published in DataDrivenInvestor

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Kevin Gabeci Follow

Aug 1, 2020 · 2 min read · · Listen

Save

An Introduction of Solidity, Ethereum’s


Programming Language
Solidity is an object-oriented programming language that is used for writing smart
contracts on various blockchain platforms. It is mostly associated with Ethereum as it
is developed by some core authors of the coin. It was first proposed in August 2014 by
computer scientist Gavin Wood and later acquired by the Ethereum project’s Solidity
team.

https://medium.datadriveninvestor.com/an-introduction-of-solidity-ethereums-programming-language-2ce325707f9e 1/4
2/12/23, 4:57 PM An Introduction of Solidity, Ethereum’s Programming Language | by Kevin Gabeci | DataDrivenInvestor

Photo by Clément H on Unsplash

Why Solidity?
Solidity is a statically-typed programming language designed for developing smart
contracts that run on the EVM. Solidity is compiled to bytecode that is executable on
the EVM. With Solidity, developers can write applications that implement self-
enforcing business logic embodied in smart contracts, leaving a non-repudiable and
authoritative record of transactions. Writing smart contracts in contract-specific
languages such as Solidity is claimed to be easy if you have prior programming
experience.

Strategic or Tactical Programming? The Road Ahead for Software


Engineers | Data Driven Investor
Ousterhout (2018) mentions in his book 'A Philosophy of Software
Design" some principles in order to dig deeper into…
www.datadriveninvestor.com

https://medium.datadriveninvestor.com/an-introduction-of-solidity-ethereums-programming-language-2ce325707f9e 2/4
2/12/23, 4:57 PM An Introduction of Solidity, Ethereum’s Programming Language | by Kevin Gabeci | DataDrivenInvestor

Its syntax is very similar to that of scripting languages like JavaScript, and it was
influenced by existing languages such as C++, Python, and JavaScript.Solidity uses a
vast number of programming concepts from other coding languages. For example, it
has variables, string manipulation, classes, functions, arithmetic operations, and so
on. While in a language like C, a programmer would be likely to create some form of a
function, like ‘int main’ and ‘main,’ Solidity works with a ‘contract’ that is created
analogously.

Is it worth learning it?


While jobs for blockchain are on the rise learning a programing language for said
blockchains, it’s a huge bonus. You won’t be without a job, but if you haven’t mastered
Open in app Sign up Sign In
another language before, you’ll find challenges in the learning process. If you are
committed to spending a few years learning it, then go ahead and do it since it’s not a
Search Medium
bad opportunity to start now.

You can use Solidity for several things, like creating your decentralized app or smart
contracts. dApps are on the rise now, and it’s a good skill to know how to write them
since the job market is going to need a lot more coders in the future specialized in this
specific thing.

Here’s my article about creating your cryptocurrency token using Solidity.

Gain Access to Expert View — Subscribe to DDI Intel

Ethereum Blockchain Solidity Cryptocurrency Programming

Get notified via email whenever Kevin Gabeci publishes an interesting article.
The more that you read, the more things you'll know. The more that you learn, the more places you'll go. So, don't hesitate
and subscribe to read the latest from me. Let's learn and grow together.

https://medium.datadriveninvestor.com/an-introduction-of-solidity-ethereums-programming-language-2ce325707f9e 3/4
2/12/23, 4:57 PM An Introduction of Solidity, Ethereum’s Programming Language | by Kevin Gabeci | DataDrivenInvestor

By signing up, you will create a Medium account if you don’t already have one. Review
our Privacy Policy for more information about our privacy practices.

Subscribe

About Help Terms Privacy

Get the Medium app

https://medium.datadriveninvestor.com/an-introduction-of-solidity-ethereums-programming-language-2ce325707f9e 4/4
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

Published in Coinmonks

ET Follow

Aug 5, 2018 · 14 min read · Listen

Save

Introduction to Solidity Programming and Smart


Contracts (For Complete Beginners)
Okay wait, slow down… What exactly is solidity and what makes these
contracts so “smart”?

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 1/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

**ATTENTION** → UPDATED April 14th 2019 for Solidity 0.5.7

Solidity is a brand new programming language native to Ethereum, the second largest
cryptocurrency by market capitalization, initially released in 2015. Ethereum is not
only a cryptocurrency capable of storing value or making payments, but a fully fledged
platform for creating what’s known as a smart contract.

For all intents and purposes, a smart contract is a programmable escrow of sorts, an
independent middleman or a fair judge capable of managing a financial transaction

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 2/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

between various parties and autonomously arbitrating a dispute.

Discover and review best Ethereum development


tools
What does this all mean?

Say a grandfather who is in his last years wants nothing more than to have his
inheritance delivered down to his family through means of a will when he passes. In a
traditional will, it would be clear who gets what, how much and when, solidified in a
legally bound document. When the time comes to actually distribute the sauce, a judge
from a court of law needs to revise the document and make decisions accordingly. A
common problem that arises within families is an argument about who gets what,
creating tension at best and destroying relationships at worst. During the court
hearing, This could influence the decision of the judge, which in turn could produce
unfair results and possibly create further damage to family bonds.

So that being said, what if we could streamline this process by drastically reducing this
problem?

If the will was a smart contract, a judge would not be necessary. Here’s where it gets
awesome. Gramps can actually make the contract hold assets on his behalf, and have
them programmatically released to his liking after his passing. In this scenario, the
code written in the contract itself would dictate the outcome, effectively eliminating
the need for an arbitrator. Sarah gets $10,000, Ben gets $5,000 and Julia gets $2,000. The
code executes and the assets in the form of a token or cryptocurrency get
automatically distributed to these parties without the need for human intervention.
While everyone involved may not be happy with the outcome, nobody can really argue
with lines of code on a screen. Sounds practical, right?

Keeping this example in mind, let’s get to the part you’ve all come here for. In this
lesson we will build gramps a simple will through a smart contract written in solidity.

Set up the Environment

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 3/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

Head over to Remix. This will serve as the development platform for writing your first
smart contract. Your screen should look like this or something similar:

Head over to the top left dropdown “Environment” and make sure “Javascript VM” is
selected. This means that all the code will run as a standalone, and not interact with
the actual Ethereum network in any way. Click the + icon in the top left corner to
create a new file, and call it “will.sol”. A tab will appear at the top which represents
which file is currently being edited.

2. Define the Version


In solidity, the first line must always state its current version. Is should look like this:

Version at the time of writing: 0.5.7

3. First Contract
Skip a line and type the following:

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 4/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

Each new contract must be prepended with “contract”, then the name with the first
letter always capitalized, followed by open/close curly brackets to contain the logic.
Use a double forward slash to write a comment, which is useful for describing for what
the code does without altering it.

4. Global Variables and the Constructor


Before we start writing code, we should already have the terms of the will clearly
defined. Let’s say gramps is leaving behind a fortune of 50 Ethers. 20 will go to his son
Conrad and the remaining 30 to his wife Lisa. Realistically, when gramps passes away,
an external program would call a function inside the contract to distribute the funds,
but we will take care of that ourselves for the purposes of this tutorial. Check the
comments section for discussion on this!

Let’s start by declaring:

1. The owner of the contract

2. The amount of fortune left behind

3. A switch that tells us if gramps is still alive

4. A constructor function that sets these values.

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 5/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

Line 5 declares the owner. When declaring variables in solidity, they must be
prepended with their type. Owner in this case is of type “address” which is unique to
solidity and represents an Ethereum wallet address. This will be useful later on when
calling specific functionality only meant for the owner (gramps).

Line 6 will hold the value of the fortune gramps is leaving behind. Its type is a uint or
“unsigned integer” which means it can only be a positive number. Solidity has many
types, but we will not cover all of them here. They can be found in the official
documentation for further reading.

Line 7 tells us whether gramps is deceased or not in the form of a boolean value, true
or false. It is set to false by default.

Lines 9–13 is the constructor function. This special function will execute automatically
upon the contract’s deployment.

The “public” keyword is what’s known as a “visibility modifier” which tells the contract
who is allowed to call the function. Public means that the function can be called within
the contract and outside of it by someone else or another contract.

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 6/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

The “payable” keyword is what makes solidity truly unique. It allows the function to
send and receive ether. The constructor has this modifier so that when we deploy the
contract we can initialize it with an ether balance, in this case 50. When the contract
receives ether, it will store it in its own address.

Here, we set the owner to “msg.sender”, which is a built-in global variable


representative of the address that is calling the function. In this case, it will be us
(gramps).

The fortune is set to “msg.value”, which is another built-in variable that tells us how
much ether has been sent.

Even though isDeceased is set to false by default, it’s set manually here to provide
clarity.

5. Modifiers
Modifiers are add-ons to functions that contain conditional logic. For example, I have a
function that turns off a light switch and a modifier that states the light switch must be
“on”. I add the modifier to function so that it can only be called if the switch is “on” and
will throw an error if the switch is “off”.

Line 15 declares the “onlyOwner” modifier. If added to a function, it can only be called
if the caller (msg.sender) is equivalent to the owner variable as stated above

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 7/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

(remember how we set the owner in the constructor). We will need this to allow the
distribution of funds, which will be implemented later.

The “require” keyword states that everything written within the following parenthesis
must be equal to true or else solidity will throw an error and the execution will stop.

The “_;” at the end tells the execution to shift to the actual function after it finishes
reading the modifier.

Line 20 declares the “mustBeDeceased” modifier. Once added to a function, it can only
be called if the value of “isDeceased” is true. We will also use this to allow for the
distribution of funds. There is currently no way to set it to true, but we will fix that
later.

As an aside, we could just write “require” underneath each function declaration, but
using modifiers is a great way to avoid repetition and to reuse code.

6. Inheritances
Now we must declare how the loot is divided amongst the family members. We will
need their public wallet keys (addresses) and their desired allotments.

As we stated before, Conrad will receive 20 ETH and Lisa will inherit 30. Let’s create a
list to store their wallet addresses and a function that sets the inheritance for each
address.

Line 25 declares an empty array called “familyWallets” for storing the family
members’ wallet addresses. This is a list-like data structure in which any element can
be indexed and subsequently accessed within it. Notice the keyword “payable” before
the brackets. This allows the address(es) to receive Ether. The square brackets after
“address” indicate it’s an array of items rather than a single variable.

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 8/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

Line 27 creates a mapping from an address type to a uint type named “inheritance” for
stashing the value of each address’ inheritance. This is a key/value pair data structure
in which the key can be called to obtain the value. It’s the equivalent of a “dictionary”
in other languages such as Python and Javascript.

Line 29 declares the function that adds an address to the array we just created, then
sets the inheritance given the address. When we call it, we must provide it with one
family member’s wallet address along with their allotted spoils. Notice the
“onlyOwner” modifier we added to this function. Can you guess why we stuck that in
there? (Hint: look at the “public” keyword.)

Line 30 simultaneously creates a wallet address and appends it to our “familyWallets”


array given the input parameter “wallet” with “.push”.

Line 31 takes the value of the key “wallet” (a parameter) from the “inheritance”
mapping we created earlier and sets it to the inheritance given the other parameter,
“inheritanceAmount”.

Notice how logically these steps connect starting from the first. We created a spot for
the wallets and the inheritance to live. The function would then populate those data
fields with the information we supply it!

7. Show me the Money


Let’s recap. So far we’ve learned about global variables and their types, the constructor,
special keywords such as “payable” and “public”, built-in variables like “msg.sender”,
modifiers and “require”, arrays, mappings and functions. We’ve built the framework,
now let’s tie it all together so we can complete our contract.

For the last coding part of the tutorial, we’ll implement a way the family can get paid
by looking through each of their addresses and sending them their respective dough.

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 9/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

Line 34 declares the “payout()” function. Note the “private” keyword. This visibility
modifier is the opposite of “public” as we’ve seen earlier on. It permits this function to
be called only within the contract as demonstrated on line 42. Security is the primary
purpose as it doesn’t allow anyone or any other contract to interact with it. Notice the
“mustBeDeceased” modifier tagged on at the end. It’s currently still impossible for this
function to execute because of it.

Line 35 is a for loop that iterates over the “familyWallets” array. The syntax is as
follows: Declare a counter variable (i), state the loop’s condition and increment (i)
every time one cycle is complete. The code within the block will execute up until the
counter is less than the length of the “wallets” array. (i) will start at 0 as stated, the logic
will execute, (i) will increment to 1 and the logic will execute again. The cycle repeats
until the condition is satisfied. Can you guess how many times it will complete the
task? (Hint: look at the array’s length)

Line 36 is the actual task we’ve been ranting about the entire lesson. “familyWallets[i]”
refers specifically to the element located at the i’th position in the “familyWallets”
array. During the first iteration, we know that (i) is equal to 0. We can thus surmise that
we want the first address in the list, as arrays always start at index 0. We then introduce
a new call to “.transfer()” on the address we just captured. This is one relatively
straightforward global method to transfer value that’s embedded within Solidity. It only
takes one argument, the amount we want to send. Being the savvy programmers we
are, we came prepared with a data structure that contains the information in question.
Can you remember where we kept it? “inheritance[familyWallets[i]]” refers directly to
the amount of inheritance we specified in the “inheritance” mapping for again, each

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 10/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

element located in the i’th position in the “familyWallets” array. Since i= 0 on the first
iteration, we want the inheritance of the first address in the list.

To summarize, this single line of code transfers funds from the contract’s address to a
receiver’s address which is pulled from a list with an amount equivalent to that same
address’ inheritance allocation.

Lines 40–42 is the function that gets called when gramps passes away. Here, we set the
value of the variable we declared right at the beginning, “isDeceased”, to true. Notice
the repeated use of “public” and “onlyOwner” keywords. Bearing that in mind, we can
finally call “payout()” to send forth the capital.

For the keen eyed readers, you may be thinking “isDeceased” is redundant. Technically
you’re correct. We could eliminate “deceased()” all together and change “private” to
“public” & “mustBeDeceased” to “onlyOwner” in “payout()”. It would produce the
exact same results. This switch simply aims to explore another means of
implementation in which we practice utilizing modifiers. It’s common practice to
make functions private and have them called by a public function elsewhere for
security purposes.

And we’re done!


Actually, not quite…

This smart contract is complete, but how do we actually use it? Now we can harvest the
fruits of our labour.

8. Contract Deployment & Interaction


Your screen should look like this:

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 11/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

Head over the Compile tab in the top right corner. Ensure your compiler version
matches the one below (0.5.7), and click Start to Compile.

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 12/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

You should see a blue box from Static Analysis. You are welcome to investigate further,
but feel free to ignore it for now. Head back to Run.

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 13/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

Ensure “Javascript VM” is selected for “Environment”. Under “Account”, clicking the
dropdown menu will reveal 5 addresses, each with a 100 ether balance. Select the first
one.

Deploying a contract to the Ethereum blockchain isn’t free. The deployer must pay a
nominal fee known as gas. Such a system is put in place to prevent people from
spamming the chain with infinite loops using all the network’s resources without

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 14/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

repercussion. If you wish to know more, MyEtherWallet has a comprehensive article


on the subject.

Leave the “Gas Limit” field as is.

The “Value” field indicates the amount of ether we want to initialize the contract with
when we hit deploy. Enter in 50. Remember how we added a “payable” modifier to our
constructor early on? Go ahead and hit “Deploy”.

You should notice 3 things right away. First of all, the balance of the selected account
should now read 49.9999… This is due to the 50 ether we gave to the contract, plus the
small fee for deploying it. The console at the bottom will also provide additional details
about the deployed instance, feel free to inspect it. The main thing to realize is this:

This is our contract instance! It generates its own address and displays the two public
functions we created. As the owner, the first thing we want to do it set the inheritances
of Conrad (20) and Lisa (30). Let’s say that Conrad’s address is the second one in the
dropdown, Lisa’s the third. Select the second one, copy it by clicking the clipboard icon
and paste it into the field above.

Before we execute, there are a couple of things to keep in mind. If you try to click the
shiny button, it will fail. Can you guess why? (Hint: look at our modifiers.) The other
caveat here is in the amount. When working with Ether, contracts read the numbers in
https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 15/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

Wei, which is a tiny fraction of Ether. So tiny in fact, that one ETH is equal to 1x10¹⁸
Wei. (That’s 1,000,000,000,000,000,000). Luckily, theres a tool that does the conversion
for us.

Separate the address with a comma and paste in the value of 20 Ether in Wei. To
answer the above question, make sure the first address in the dropdown is selected,
not the second. Any other address won’t work because of the “OnlyOwner” modifier!
(Whichever one is selected during deployment is crowned owner due to “owner =
msg.sender”)

Let’s launch the rocket and repeat the same steps for Lisa. You should see the console
outputting success messages. Inspect them and look for a section labeled “decoded
input”.

As you can see, it displays the inputs we provided it.

The estate is set, but the sad news is in. Gramps has passed away of a heart attack
during an arctic exploration expedition at the age of 73. He was an ambitious man,
always full of energy. He grabbed life by the balls at every corner and didn’t take no for
an answer. This dude even invested in crypto during the 2017 bull run and made some
bank. He knew this day would come so he packed his winnings into the will and
wished a prosperous life to his loved ones.

As we commemorate the death of a great man, we also call “deceased()” in his will.
The console will smile, and the addresses will increase in balance. Keep in mind here
that the account will have to spend some gas to execute the function. Open the
dropdown menu and indulge in your success. Yes, you’ve just created your first fully
functional smart contract! Go treat yourself to some ice cream, you deserve it!

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 16/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

If you’ve made it this far, you yourself are an exceptional human being. Maybe by the
time you hit your last days, this technology will be mainstream and you can create your
own an autonomous estate manager for your loved ones.

To terminate this tutorial, we must discuss one last question, one you may have been
wondering throughout the journey. How on earth is gramps suppose to call the
function if he’s dead?!? A futuristic solution would be to somehow have an IOT device
that can remotely track a heartbeat that would have the power to execute the function

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 17/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

if the beat stopped for more than x amount of time. Any other solution you can think
of? Post it in the comments!

-Etienne

For the thumbnail!

Join Coinmonks Telegram Channel and Youtube


Channel get daily Crypto News
Also, Read
Copy Trading | Crypto Tax Software

Grid Trading | Crypto Hardware Wallet

Crypto Telegram Signals | Crypto Trading Bot

What are the Trading Signals? | Bitstamp vs Coinbase

ProfitFarmers Review | How to use Cornix Trading Bot

How to Buy Domain Name on Unstoppable Domains?

Crypto Tax in India | altFINS Review | Prokey Review

Best Crypto Exchange | Best Crypto Exchange in India

Best Crypto APIs for Developers

Best Crypto Lending Platform

An ultimate guide to Leveraged Token

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 18/19
2/12/23, 4:59 PM Introduction to Solidity Programming and Smart Contracts (For Complete Beginners) | by ET | Coinmonks | Medium

Ethereum Solidity Tutorial Smart Contracts Programming

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Open
Emails in
willapp
be sent to [email protected]. Not you? Get unlimited access

Get this newsletter


Search Medium

https://medium.com/coinmonks/introduction-to-solidity-programming-and-smart-contracts-for-complete-beginners-eb46472058cf 19/19
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

Published in Coinmonks

Blessing Adesiji Follow

Jul 12, 2021 · 7 min read · Listen

Save

Learn Solidity 01: Writing your first Smart


Contract

Photo by Zoltan Tasi on Unsplash

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 1/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

I have been fascinated by blockchain technology for so many reasons, which I will not
discuss in this article. However, it’s not a new topic that cryptocurrency is the future of
money, and NFTs are doing incredibly impressive for digital artists.

So what is my aim with this article? I got interested in the blockchain space, and after
doing a lot of research, I couldn’t find enough learning guides like you would, for, say,
Data Science which is pretty standard. It would help if you understood that the reason
for this is that there is a shortage of Solidity programmers(about 200,000* developers in
the world) compared to other popular programming languages. Therefore, there aren’t
enough tutorials out there. Hence, I will be writing a series of articles on learning the
language, and you can learn from this to become a blockchain developer.

This is the first article of the series, and it will be on writing your first smart contract
with Solidity. There are many concepts that you might not be familiar with yet, and
that’s perfectly okay. I will do my best to break down each concept into bits as we move
along the series, and you can do more research from there.

To get started, here are a few questions that you should be asking; What is a Smart
Contract? What is Solidity? How does the blockchain work?

Follow along as I provide answers to these questions below.

What is a Smart Contract?


A “Smart Contract” is simply a program that runs on the Ethereum blockchain. It is a
collection of code (its functions) and data (its state) that resides at a specific address on
the Ethereum blockchain. Think of a smart contract as an account on the Ethereum
network, which can not be controlled by the user and runs as a program. However, a
user can interact with a smart contract by submitting transactions that execute a
function defined on the smart contract.

The way smart contracts ensure that transactions occur in real life is much more
complex, but here is a simple explanation to understand how things work.

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 2/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

Photo by Cedrik Wesche on Unsplash

Imagine that this article is for sale, and I am the seller, you the reader is the buyer, and
you are buying this article by using an affiliate link you saw on the internet. We can
deploy a smart contract for this transaction, and here’s how the exchange might occur.

You, the reader, creates a transaction that sends the price of this article to the seller in
exchange for a copy of this article. Like you would usually in a normal bank
transaction, you will provide my address as an input to the smart contract’s address.
The smart contract will then carry out this transaction by verifying that you have
enough money in your wallet and that I also have a copy of this article ready for sale.
Then, it deducts the money from your wallet, sends it to my wallet, tells me to send you
a copy of the article, and finally sends the affiliate commission to the owner of the
affiliate link after deducting that from my wallet.

The above is how smart contracts can facilitate transactions between users who do not
trust each other, and it is used in the real world to carry out much more complex
transactions.

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 3/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

This leads us to the following question: What is Solidity?

What is Solidity?
We already established the fact that Smart Contracts are software programs. For
Ethereum, you can write smart contracts using a statically-typed language called
Solidity, which is the most widely used smart contract programming language at the
moment. Solidity is a full-featured language for writing general-purpose smart
contracts, and it looks like JavaScript.

How does the blockchain work?


To answer the last question, I think it’s an important concept to know. I will share a
good video by Anders Brownworth, it explains the concept: How does the blockchain
work?

Watch here; an elementary visual introduction to the concepts behind how the
blockchain works.

Now that you have a good understanding of the concepts above let’s see how you can
write your first smart contract.

Step 1 — Setup Remix IDE


1.1 — The first step is setting up the Remix IDE. Remix IDE is a browser-based
development environment for Smart Contracts. The IDE provides several plugins and
compilers for different solidity versions.

To launch the Remix IDE, visit http://remix.ethereum.org; you will see the page below,
which might be different depending on when you are reading this article.

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 4/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

Remix Home Page

Notice that in the image above, you can see “Featured Plugins” because the Remix IDE
is built with a pluggable architecture, which means that all the operations are
performed using plugins.

1.2 — The next thing to do is to enable the Solidity compiler plugins, as shown below.

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 5/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

Enable Plugins

1c — After enabling the plugin, click on the “Solidity compiler” button, and select the
compiler configuration shown in the image below.

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 6/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

Compiler Configuration

It is noteworthy to mention that compiler versions in Solidity are tricky to work with,
and the advice is that you should try not to work with the most recent version.
Interestingly, you will find some legacy projects still running on older solidity versions,
and this is okay. In summary, try to stick with the version you see in a particular
tutorial if you are a beginner.

In the image above, you will see that we are working with compiler version 0.8.1,
which might not be the recent version. Also, you can set the compiler version in the
https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 7/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

Solidity source file by using the “pragma” line at the beginning of the file. The Pragma
line is just a way of telling the compiler the version you are working with.

Now that everything is all set let’s write our first smart contract in the next step.

Step 2 — Write your first Smart Contract


Like any other programming language, the first step is creating a project file for the
language. Here, you will create a file titled, “MyFirstSmartContract.sol”. The “sol” file
extension stands for Solidity, just like “py” is for Python.

See the images below to create this file in the Remix IDE.

2.1 — Create Workspace

Create workspace

2.2 — Create the file; MyFirstSmartContract.sol

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 8/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

Create a file

2.3 — Write the code

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.1;
contract MyFirstContract {
string public myString = “Hello World”;
}

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 9/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

Part 1

`// SPDX-License-Identifier: GPL-3.0` — Is the Software Package Data Exchange® (SPDX®)


identification used to specify the license under which the Solidity file will be
distributed. It is recommended that it is included in your code, and the compiler will
throw a warning message if it is missing from your file.

Part 2

pragma solidity ^0.8.1, the ^0.8.1 means version between 0.8.1 and 0.9.0, inclusive of
0.8.1 but not 0.9.0. In other words >=0.8.1 and <0.9.0.

The pragma keyword instructs the compiler to enable or check specific features.
Finally, the version pragma is a mechanism that informs the compiler about the
Solidity file’s compiler version.

Part 3

contract MyFirstContract is the beginning of the code, just like the Class keyword in the
Python programming language. The “myString” is a public storage variable to hold
“Hello World.” You will learn more about this as we proceed through the series.

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 10/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

Part 4

Notice that the compiler displayed a green icon, and this signifies that the compilation
is successful because you enabled auto-compile in the previous section.

Congratulations 🎉🎉
So there you have it; Congratulations, you just wrote your first smart contract. In the
next article, we will discuss how you can deploy this smart contract to an actual
blockchain.

* — Estimated figure

Up next …
If you don’t want to miss the next article, consider signing up for my newsletter, and
you will receive a notification in your email when the article is ready. Remember, these
article series aim to break down complex concepts in blockchain development,
especially the Ethereum network.

Get to Know me
I write about exciting topics in Data Science, Software Development, and Blockchain
Tech.

Follow me on my social media for more updates; Twitter and LinkedIn. Also, don’t
hesitate to write me an email for more information.

Blockchain Ethereum Smart Contracts Solidity Blockchain Technology

Sign up for Coinmonks


By Coinmonks

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 11/12
2/12/23, 5:01 PM Learn Solidity 01: Writing your first Smart Contract | by Blessing Adesiji | Coinmonks | Medium

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
Open
inbox,in
byapp
CoinCodeCap.com Take a look. Get unlimited access

Emails will be sent to [email protected]. Not you?


Search Medium

Get this newsletter

https://medium.com/coinmonks/learn-solidity-01-writing-your-first-smart-contract-528cad29ba99 12/12
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Published in The Glitcher

Pranay Bathini Follow

Jun 26, 2021 · 8 min read · Listen

Save

Solidity for Beginners: Creating Smart Contracts

Before diving into solidity, let’s understand where solidity originated from and what
solidity means, and why it should be used?

I recommend reading this article to have a theoretical understanding of blockchain


and Ethereum before diving in.

In this article, we are going to learn the following things.

What is Solidity?

Running Smart contracts in Solidity using Remix IDE?

Smart contract creation


https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 1/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Deployment of Smart contracts to test blockchain.

Connecting Remix IDE with Metamask

Deploying the contract to Ropsten test network using Metamask.

Solidity
Solidity is an object-oriented, high-level language(Human readable) for implementing
smart contracts.

But what are smart contracts?


Smart contracts are a piece of code uploaded to the blockchain. The code will contain
public functions which can be called by anyone connected to the blockchain from
their computer.

The blockchain is distributed in nature. It means there will be more than one server(a
network of computers) that will be running your code, verifying each other making
sure no one cheats in the network.

The distributed nature of blockchain makes it decentralized(No single point of


control). The control is distributed among the participating nodes. This decentralized
nature allows people to develop decentralized applications what are so-called DApps.

There are a lot of advantages and a change in developing tactics these DApps bring in.
One of them is the immutability of smart contracts. Once deployed to Ethereum, they
cannot be changed. This is to enforce the trust factor that the code is deployed the
same way to everyone.

This also means the developer has to test the code for all corner cases before deploying
to the blockchain. This changes the traditional way of shipping buggy code first and
improving it later.

Solidity Features
Statically typed — The type of variable declared is known at compile time.
https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 2/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Inheritance — Contracts can inherit from other contracts

Function Modifiers, State Variable Accessors, Fallback Functions, Enums

are among some which we will discuss in great detail with examples.

Using Solidity: The easy way


The local installation of Solidity is a long process where we have to install node, npm,
ganache-cli or testrpc for our private blockchain, solcjs for compiling our solidity code,
and web3js for interaction.

So, we are going to take the easy way of using remix IDE which is an online IDE and we
will use two different kinds of test networks to deploy our code.

Installing Remix via docker


Don’t worry, this is the only big step which we are going to do.

If you don’t have docker, install it from here. Trust me docker will save a lot of valuable
time which we are going to lose in the installation process and configuration.

Once you have installed docker and running it, execute the below command.

docker pull remixproject/remix-ide:latest

This command will pull the latest version of IDE into your system. Now let’s run it.
Execute the below command to run it.

docker run -p 8080:80 remixproject/remix-ide:latest

Now your IDE is running. Go to http://localhost:8080 and you can use you Remix
instance. You should be able to see a screen like below.
https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 3/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Your First Program in Solidity


Let’s create a simple contract that lets you store your name on the blockchain and
retrieve it.

The contract will look like below.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 4/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

1 // SPDX-License-Identifier: GPL-3.0
2
3 pragma solidity >=0.7.0 <0.9.0;
4
5 contract NameStorage {
6
7 string name;
8
9
10 function store(string memory _name) public {
11 name = _name;
12 }
13
14 function retrieve() public view returns (string memory){
15 return name;
16 }
17 }

NameStorage.sol hosted with ❤ by GitHub view raw

Let’s understand the code line by line.

The first line specifies which version of the compiler that code should be interpreted
in. This is done with the help of the pragma directive.

Why we need to specify the version?


The only constant in software is change. So, if something new adds up in future
versions, the existing code should run without breaking. This is to prevent future
issues. This can be specified in two ways.

pragma solidity ^0.8.4;

This line tells the compiler to use the 0.8.4 version. The ^ symbol prevents the code
from being compiled from a higher version.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 5/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

pragma solidity >=0.7.0 <0.9.0

This tells only the compiler greater than or equal to 0.7.0 and less than 0.9.0 can
compile the code.

In the next line, the contract is defined by the contract keyword and it is similar to how
the classes are defined. A solidity contract is a collection of code(its functions) and
data(state variables) and it resides at a specific address on the Ethereum blockchain.

Inside the contract, we define a state variable to store our name as a string. All the
variables are by default storage type which means they will be occupying space inside
the contract when deployed on the blockchain.

Note that Solidity is statically typed which means we need to define the type of variable
while writing the contract and it will be resolved at compile time.

In the next lines, we defined two functions, one for taking the input and storing the
name and the other for retrieving the stored name from the blockchain.

Note that both are defined as scope public which means anyone on the chain can call
the functions.

We will discuss all the language-specific constructs with detailed examples in the next
set of articles.

For now, let’s compile the contract and deploy it.

Compiling the contract


In the left vertical tab, click on the solidity compiler. You will see the below screen.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 6/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Click on the compile NameStorage.sol. It should show the green tick mark as above.

Note that the compiler version should be between 0.7.0 and 0.9.0. I have selected 0.8.1
here.

Once compiled, the compiler would generate a byte code that is machine-
understandable like below

1 {
2 "generatedSources": [],
3 "linkReferences": {},
4 "object": "608060405234801561001057600080fd5b50610484806100206000396000f3fe6080604052348015610010
5 "opcodes": "PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH2 0x10 JUMPI PUSH1 0x0 DUP1 REV
6 "sourceMap": "71:210:0:-:0;;;;;;;;;;;;;;;;;;;"
7 }

ByteCode.json hosted with ❤ by GitHub view raw

Now, let’s deploy it to the blockchain.

Deploying the contract

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 7/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Next, head to the deploy and run transactions tab. You should be able to see the below
screen.

The menu can be overwhelming but let’s focus on what we need to do. There will be a
lot of test account with 100 (fake/test) Ether.

Click on deploy and the contract will be deployed to the blockchain and a contract
address will be returned as below.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 8/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Our contract is deployed at address


0xa131AD247055FD2e2aA8b156A11bdEc81b9eAD95.

Now, if you observe our balance will be 99.999 something.

For deploying on the blockchain, some Ether has to be spent which is known as gas.

Storing Our Name


In the left bottom, type your name in the textbox and click on store. This would store
our name on the blockchain and it would cost us some gas as well as shown below.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 9/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Now click on the retrieve, to get the name stored on the contract. If you observe this
properly, this operation does not cost us any gas.

Only write operations cost us gas as the same should be replicated to thousands of
servers.

Remember, our functions are defined as public, so anyone on the blockchain can call
them.

You can select a different account from the accounts at the left top corner and call
retrieve.

It would give you output as ‘pranay’. As we discussed, this operation would not cost us
any gas. It would be 100 ether.

Now, store another name from the same account and retrieve it like below.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 10/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

If you observe, our old name doesn’t exist anymore. It was over-written by new value
and it can be done by anyone.

In the next articles, we will see how to restrict writing to contracts.

Connecting Metamask with Remix IDE


Install Metamask chrome extension from here. Once installed, create a password,
store the passphrase in a safe location. Do not share it with anyone.

Once you get to the main screen, select Ropsten test network. You can also deploy to
Ethereum mainnet but it will cost you actual money in ether.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 11/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

The ether in my account is test (fake) Ether. You can send test Ether to your account
from metamask faucet.

Deploying on Ropsten Test environment


Come back to Remix IDE and go to deploy and run the transactions tab and select
Injected Web3 as Environment.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 12/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Once you selected injected web3, remix IDE will try to connect with Metamask wallet
like above.

Click Next and Connect.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 13/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

You should be able to see your Metamask account in the deploy tab and also your test
ether in your account.

Now Click on deploy since it is already compiled. You will see a notification from
Metamask like below for confirmation.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 14/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Click confirm and the contract will be deployed to the test blockchain Ropsten
network.

On the terminal in ‘Deploy and Run Transactions’ tab, you will see the transaction
details like below.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 15/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Open in app Get unlimited access

Search Medium

Once you click on the URL of Ropsten displayed, it will display more information about
the transaction.

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 16/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

You can verify on Metamask too about the transaction and can see gas used on contract
deployment.

Now, you can go back to Remix IDE and store your name in the contract and retrieve it
as we did earlier.

If you like the post, consider supporting us by sending some ERC20 tokens to the below
address.

0xdd2f4D03E817f4Fbaf233cAd8Ea829229fA6d592

Keep Experimenting 🔎.

Keep Learning 🚀

This blog was originally published on the https://www.thecryptoinsight.com .

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 17/18
2/12/23, 5:03 PM Solidity for Beginners: Creating Smart Contracts | by Pranay Bathini | The Glitcher | Medium

Solidity Smart Contracts Metamask Blockchain Cryptocurrency

Sign up for The Glitcher


By The Glitcher

Round-up of recent blog posts Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/the-glitcher/solidity-for-beginners-creating-smart-contracts-7d9932101b36 18/18
2/12/23, 5:12 PM Solidity: Variables and Value Data Types | by Mary Mazi | Medium

Mary Mazi Follow

Feb 19, 2022 · 4 min read · Listen

Save

Solidity: Variables and Value Data Types

Photo by environmatic on iStock

In programming languages, data types are a means of specifying the type of value that
a variable possesses. If variables are containers that hold data, then data type is the
type of container which tells that what kind of stuff can be put in it.

https://medium.com/@mazma/solidity-variables-and-value-data-types-e2b29bddcaf7#:~:text=There are three types of,values during a program executi… 1/5


2/12/23, 5:12 PM Solidity: Variables and Value Data Types | by Mary Mazi | Medium

Data types also determine what operations and actions can be performed on a given
data. A solid understanding of data types is highly useful in ensuring that data is
collected in the preferred format and the value of each property is as expected.

Types of Variables
There are three types of variables in Solidity:

1. State Variables: These are variables whose values are stored permanently on the
blockchain. They are declared inside of a contract but outside a function.

2. Local Variables: These are variables defined within a function to temporarily hold
values during a program execution. They cannot be accessed outside the function
in which they are defined and they exist only while the function is executing.

3. Global Variables: These are special variables that exist in the global namespace
and are used to retrieve information about the blockchain.

Defining Variables
When declaring a variable in Solidity, you have to specify the data type first, followed
with an access modifier, and the variable name.

Access Modifiers are the keywords used to specify the accessibility or scope. of a
variable or function. The scope of local variables is limited to function in which they
are defined but state variables and functions can have the following scope:

Public
Both state variables and functions can be marked as public. Public state variables and
https://medium.com/@mazma/solidity-variables-and-value-data-types-e2b29bddcaf7#:~:text=There are three types of,values during a program executi… 2/5
2/12/23, 5:12 PM Solidity: Variables and Value Data Types | by Mary Mazi | Medium

functions can both be accessed from the outside and the inside. The Solidity compiler
automatically creates a getter function for them.

Private
This is the most restrictive visibility. State variables and functions marked as private
are only visible and accessible in the same contract.

Private is only a code-level visibility modifier. A


contract marked as private is still visible to observers
of the blockchain, it is just not accessible for other
contracts.
Internal
This is the default visibility for state variables. Internal functions and state variables
can both be accessed from within the same contract and in deriving contracts. They
aren’t accessible from the outside.

External
Only functions can be marked external. External functions are meant to be called by
other contracts. They cannot be called internally.

If you do not specify any access modifier when declaring a variable, it will be
considered as a private.

//STRUCTURE
<type> <access modifier> <variable name>;`

Data Types
Solidity is a statically typed language. As a result, the data type of each variable (state
and local) needs to be specified. Data types in Solidity can be classified into two types:

1. Value type: This is a type that holds the data directly in the memory owned by it.
Variables of this type are always passed by value. This means that their values are
https://medium.com/@mazma/solidity-variables-and-value-data-types-e2b29bddcaf7#:~:text=There are three types of,values during a program executi… 3/5
2/12/23, 5:12 PM Solidity: Variables and Value Data Types | by Mary Mazi | Medium

always copied when they are used in assignments or as function arguments.

2. Reference type: These are variables whose values are references to where the
actual data is stored in memory.

A Closer Look at Value Types


The value types supported in Solidity are:

1. Boolean
bool : The possible values are constants true and false .

2. Integer
int / uint : Signed integers are declared with the int keyword, unsigned integers
with the uint and both take up 32 bytes by default. You can specify the exact
number of bits your variable can hold if the default size of 32 bytes is too much.
You do this in steps of 8 starting from 8 up till 256. For example int128 / uint128 .

3. Fixed Point Number


fixed / ufixed : Used to represent numbers with a fixed number of decimal places.
No matter how large or small the fractional part is, it will always use the same
number of bits. This is however an upcoming type and cannot be used yet.

4. Address
address : Holds a 20 byte value (size of an Ethereum address).
address payable : Holds same size as address , but with the additional members
transfer and send .

The difference between both address types is that address payable is an address
you can send Ether to, while a plain address cannot be sent Ether.

5. Fixed-size Byte Array


This contains a sequence of bytes from one to up to 32. The length of the array
must always be specified in the type declaration. They are declared in the following
way bytes1 , bytes2 , bytes3 all the way up to bytes32 . byte is an alias for bytes1 .

6. Literals
Literals refer to fixed values that the program may not alter during its execution.

https://medium.com/@mazma/solidity-variables-and-value-data-types-e2b29bddcaf7#:~:text=There are three types of,values during a program executi… 4/5


2/12/23, 5:12 PM Solidity: Variables and Value Data Types | by Mary Mazi | Medium

These fixed values are also called constants. These include address literals, rational
and integer literals, string literals, hexadecimal literals.

7. Enums
Enums are one way to create a user-defined type in Solidity. They restrict a variable
to have one of only a few predefined values.

Open in app Get unlimited access

Search Medium

https://medium.com/@mazma/solidity-variables-and-value-data-types-e2b29bddcaf7#:~:text=There are three types of,values during a program executi… 5/5


2/12/23, 5:14 PM Learning Solidity — State Variables, Functions and Function Modifiers | by theblockchainchick | Medium

theblockchainchick Follow

Mar 7, 2019 · 3 min read · Listen

Save

Learning Solidity — State Variables, Functions


and Function Modifiers
(Part II)

https://gyanlakshmi.medium.com/learning-solidity-state-variables-functions-and-function-modifiers-7fcc3ecc9fc8 1/7
2/12/23, 5:14 PM Learning Solidity — State Variables, Functions and Function Modifiers | by theblockchainchick | Medium

Learning Solidity — State variables, Functions and Function Modifiers

https://gyanlakshmi.medium.com/learning-solidity-state-variables-functions-and-function-modifiers-7fcc3ecc9fc8 2/7
2/12/23, 5:14 PM Learning Solidity — State Variables, Functions and Function Modifiers | by theblockchainchick | Medium

This is the second tutorial in my Solidity programming series. This tutorial will give
you a quick introduction the various data types, functions and functions modifiers
before tackling the next levels of difficulty.

What are State Variables?

State variables are variables whose values are permanently stored in the contract
storage. Solidity is a statically typed language and hence, the type of each variable
needs to be specified explicitly.

There are different types of variables that Solidity allows you to define. The following
are a few variable types that you will use often in your contracts in the format:

Data Type: value that it takes

Example: An example declaration

Some of the data types are:

Integers : uint8-uint256 (in steps of 8)/int8-int256 (in steps of 8)

uint and int are by default uint256 and int256 respectively.

Example:

uint8 i;

Boolean : bool (values-true or false)

Example:

bool a;

Address: address and address payable

address : can hold a 20 byte value(size of an Ethereum address)

address payable: same as address but with additional members transfer and send.

https://gyanlakshmi.medium.com/learning-solidity-state-variables-functions-and-function-modifiers-7fcc3ecc9fc8 3/7
2/12/23, 5:14 PM Learning Solidity — State Variables, Functions and Function Modifiers | by theblockchainchick | Medium

The address payable is an address to which you can send ethers whereas you cannot
send any to the address variable.

Example:

address payable addr1;

address addr2;

Fixed size byte arrays: byte1-byte32

Example:

bytes32 constant bytesText = “HelloWorld”;

String Literals: string/bytes32

Example:

string newWord;

Enum: enum

Example:

enum accountTypes { Savings, Current, Joint}

accountTypes account;

Arrays: uint[]/uint[20]

Example:

uint[20] intArr;

bytes[] byteArr;

string[4] stringArr;

address[] addrArr;

https://gyanlakshmi.medium.com/learning-solidity-state-variables-functions-and-function-modifiers-7fcc3ecc9fc8 4/7
2/12/23, 5:14 PM Learning Solidity — State Variables, Functions and Function Modifiers | by theblockchainchick | Medium

Structs: struct

Solidity allows us to define new types in the form of struct.

Example:

struct student {

uint rollnumber;

string name;

uint age;

There are also several other data types that you can look up on:
https://solidity.readthedocs.io/en/v0.5.4/types.html#types.

Boolean, Integers etc. are called value types since they are always passed by value.

What are Functions?

Functions are the executable code that you write in your smart contract. The functions
work together to implement your business logic.

Functions can be defined using the function keyword. The syntax to define a function
is as follows:

function functionName() Function Visibility {}

The function visibility can be external, public, private or internal.

External functions: External functions can be called from other contracts or


transactions. Calling an external function internally is not recommended. When
receiving large amounts of data, external functions can prove to be very efficient.

Public functions: Public functions can be called externally and internally.

https://gyanlakshmi.medium.com/learning-solidity-state-variables-functions-and-function-modifiers-7fcc3ecc9fc8 5/7
2/12/23, 5:14 PM Learning Solidity — State Variables, Functions and Function Modifiers | by theblockchainchick | Medium

Private functions: Private functions and variables are visible only to the contract in
which they are declared. They cannot be inherited/derived.

Internal functions: Internal functions can be accessed internally by the contract


without using the keyword this.

Functions can also be declared as view which means that they will not modify ant state
variables.

What are the different Function Modifiers?

Function Modifiers in Solidity are used to modify the behavior of a function. These are
especially useful in a language like Solidity where the contracts once written and
deployed cannot be changed so easily.

Therefore, a lot of pre-requisites and checks are required to be done in functions prior
to executing a critical statement. Modifiers can be inherited overridden by derived
contracts.

You can define a modifier using the modifier keyword.

Examples:

// This modifier requires that only owner calls this function.The


function is the function in which the modifier is written.
modifier onlyOwner {
require(
msg.sender == owner,
"Only owner can call this function."
);
_;
}
//This modifier checks if the msg.value is greater than the price that
was passed as an argument and takes some action based on that.
modifier costs(uint price) {
if (msg.value >= price) {
_;
}
}

https://gyanlakshmi.medium.com/learning-solidity-state-variables-functions-and-function-modifiers-7fcc3ecc9fc8 6/7
2/12/23, 5:14 PM Learning Solidity — State Variables, Functions and Function Modifiers | by theblockchainchick | Medium

The ‘_’ space refers to a function body that is yet to be written by the derived contracts
that will derive these modifiers.

There is a lot more on functions, function modifiers and state variables on the Solidity
docs but the above basics should be enough to get you up and running with writing
your smart contracts for use cases that you have in mind.

The next blog on this series will explore some more topics related to Solidity
programming.

Ethereum Solidity Solidity Tutorial Programming Blockchain


Open in app Get unlimited access

Search Medium

https://gyanlakshmi.medium.com/learning-solidity-state-variables-functions-and-function-modifiers-7fcc3ecc9fc8 7/7
2/12/23, 5:17 PM State/Local Variables & the Stack Limit | by Horizontal | Medium

Horizontal Follow

Oct 2, 2018 · 2 min read · Listen

Save

State/Local Variables & the Stack Limit

In Solidity there are two different types of variables available, state and local.
State variables are used for permanent storage and cost gas store data in
these variables. Like global variables they lay outside the scope of your functions.
Local variables are local to the scope of your functions, basically variables that you
declare in your functions. By default local variables are stored in memory not storage.

Unlike storage, memory is temporary and does not cost gas to use. Even though local
variables use memory by default, if you use a struct, array, or mapping as a local
variable then it will default to storage instead of memory. After you are finished setting
up your variables and functions and you want to compile the smart contract, you may
run into an error.

Stack limit error

The stack too deep error means you are using too many local variables inside one of
your functions. Each local variable takes up a slot in the stack thus increasing the stack
size. The stack limit is determined by how many local variables you can have per
function which is 16. So if you’re creating a function to view data, you should use a
helper function that returns those values instead of returning them one by one.

https://medium.com/@horizontal/state-local-variables-the-stack-limit-e6d4389e2fba 1/2
2/12/23, 5:17 PM State/Local Variables & the Stack Limit | by Horizontal | Medium

Stack too deep

Open in app Get unlimited access

Search Medium

Stack too good

Java Script Solidity Blockchain Smart Contracts Web Development

https://medium.com/@horizontal/state-local-variables-the-stack-limit-e6d4389e2fba 2/2
2/12/23, 5:19 PM What are Solidity variables?. Enjoy the resources to this stream… | by Cryptoverse DAO | Coinmonks | Medium

Published in Coinmonks

Cryptoverse DAO Follow

Aug 2, 2022 · 5 min read · Listen

Save

What are Solidity variables?


Enjoy the resources to this stream while watching the video on our YouTube!

YouTube: https://youtu.be/537AZqx_5Ec

Discord: https://discord.gg/J73qhkj7kr

Twitter: https://twitter.com/CryptoverseDAO

Linktree: https://linktr.ee/cryptoversedao

Variable Types in Solidity:

Undoubtedly, variables are an important requirement for writing programs in any


programming language. So, you would also need variables in a Solidity tutorial to
understand how they can help in storing different information. It is essential to
observe that variables are just reserved memory locations for storing values.
Therefore, you could inherently reserve a certain amount of space in memory with the
creation of a variable.

The sheer variety of variables required in Solidity might create doubts such as ‘is
solidity easy to learn?’ although without confusion. Users could store information
related to different data types such as character, floating-point, double floating-point,
wide character, Boolean, integers, and others. The operating system ensures memory
https://medium.com/coinmonks/what-are-solidity-variables-eecee946d4ca 1/7
2/12/23, 5:19 PM What are Solidity variables?. Enjoy the resources to this stream… | by Cryptoverse DAO | Coinmonks | Medium

allocation and selection of entities to store in reserved memory according to the


variable’s data type.

Value Types

A detailed overview of any tutorial on solidity blockchain programming language


would help you find different data types. Solidity enables a formidable assortment of
in-built and user-defined data types. Here are important data types that you could find
in solidity,

Boolean
Signed and unsigned integers
Signed integer from 8 bits to 256 bits
Unsigned integer from 8 bits to 256 bits
Signed and unsigned fixed-point numbers varying in sizes
Signed fixed-point number, represented by fixedMxN, with M representing number of
bits accounted by type with N representing decimal points. M must be divisible by 8
while ranging from 8 to 256. On the other hand, N could vary from 0 to 80. The value of
fixed is similar to fixed128x18.
Unsigned fixed-point number, represented by ufixedMxN with M and N representing
the same as above. The value of ufixed also remains similar to ufixed128x18.

Address

The ‘address’ element in the solidity tutorial refers to the 20-byte value, which
represents the size of the Ethereum address. An address could basically help in getting
the balance by using the method of ‘.balance.’ The method could help in transferring
the balance to other addresses through the ‘.transfer’ method. Here is an example of
the use of the address in Solidity.

address x = 0x212;

address myAddress = this;

if (x.balance< 10 &&myAddress.balance>= 10) x.transfer(10);

Understanding Variables in Solidity

https://medium.com/coinmonks/what-are-solidity-variables-eecee946d4ca 2/7
2/12/23, 5:19 PM What are Solidity variables?. Enjoy the resources to this stream… | by Cryptoverse DAO | Coinmonks | Medium

The perception of variables is also one of the crucial requirements to learn solidity.
You can find support for three variable types such as state variables, local variables,
and global variables in Solidity. State variables are the ones that have their values
stored permanently in contract storage. The local variables are the ones that have their
value present for the course of execution of a function.

On the other hand, global variables are special variables that are present in the global
namespace and help in obtaining information regarding blockchain. It is important to
verify that as a statically typed language, Solidity requires a specification for state or
local variable type at the time of declaration. All the declared variables are associated
with a default value according to its type without any concept of “null” or “undefined.”
Let’s reflect a bit more on the types of variables in Solidity.

State Variable

You can find state variables where the values are stored permanently in contract
storage. The example of a state variable is clearly evident in the following example,

pragma solidity ^0.5.0;

contract SolidityTest {

uintstoredData; // State variable

constructor() public {

storedData = 10; // Using State variable

Local Variable

The value of local variables is accessible only within the function that has been used
for defining it. It is also important to note that function parameters are local in nature
to the concerned function as in the following example.

https://medium.com/coinmonks/what-are-solidity-variables-eecee946d4ca 3/7
2/12/23, 5:19 PM What are Solidity variables?. Enjoy the resources to this stream… | by Cryptoverse DAO | Coinmonks | Medium

pragma solidity ^0.5.0;

contract SolidityTest {

uintstoredData; // State variable

constructor() public {

storedData = 10;

function getResult() public view returns(uint){

uint a = 1; // local variable

uint b = 2;

uint result = a + b;

return result; //access the local variable

}
]
Global Variables

Global variables are quite unique when it comes to a solidity tutorial. They are ideal for
obtaining information regarding blockchain and associated transaction properties.
Here is an outline of the global variables in Solidity, along with their functions.

blockhash(uintblockNumber) returns (bytes32): Represents hash of the concerned


block and works only for the 256 latest blocks while ignoring current blocks.
block.coinbase (address payable): Shows the address of current block miner.
block.difficulty (uint): Points out the difficulty of a block.
block.gaslimit (uint): Shows the gaslimit of current block.
block.number (uint): Shows the current block number.
block.timestamp (uint): Displays the timestamp of current block in terms of the
https://medium.com/coinmonks/what-are-solidity-variables-eecee946d4ca 4/7
2/12/23, 5:19 PM What are Solidity variables?. Enjoy the resources to this stream… | by Cryptoverse DAO | Coinmonks | Medium

seconds passed since the unix epoch.


msg.sig (bytes4): Can find out the first four bytes of the function identifier or calldata.
msg.data (bytes calldata): Shows the complete calldata.
now (uint): You can find the information of the current block timestamp.

Variable Name Rules

You should also search for the ideal practices to name variables in a solidity tutorial. It
is important to abide by the following rules thoroughly for naming variables in the
Solidity programming language.

The foremost condition for naming variables in Solidity is that you cannot begin the
name with numerals. So, you could not use any numeral between 0 and 9 to start the
variable name in Solidity. It is mandatory to start the variable name with a letter or an
underscore character. Therefore, 023Freedom is not a valid variable name, while
Freedom023 or _023Freedom are valid choices.
The solidity best practices for naming variables also point out towards case-sensitivity
of solidity variable names. For example, freedom and Freedom are considered two
different variables.
The next most important practice in creating a suitable variable name refers to staying
away from using reserved keywords. Reserved keywords such as Boolean or break
variables names are not eligible for Solidity variable names.

The final aspect in understanding the use of variables for starting the applications of
Solidity is variable scope. The variable scope is important in the solidity tutorial as it
differs for local variables and state variables. Local variables are restricted only to the
function where they are defined.

On the other hand, state variables in a solidity tutorial would refer to public, private,
and internal scope. It is possible to access public state variables internally and through
messages. Private state variables are open for access internally only from the current
contract. Internal state variables allow for internal access only through the current
contract.

https://medium.com/coinmonks/what-are-solidity-variables-eecee946d4ca 5/7
2/12/23, 5:19 PM What are Solidity variables?. Enjoy the resources to this stream… | by Cryptoverse DAO | Coinmonks | Medium

New to trading? Try crypto trading bots or copy


trading

Solidity Cryptocurrency Ethereum Blockchain Education

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter


Open in app Get unlimited access

https://medium.com/coinmonks/what-are-solidity-variables-eecee946d4ca 6/7
2/12/23, 5:19 PM What are Solidity variables?. Enjoy the resources to this stream… | by Cryptoverse DAO | Coinmonks | Medium

Search Medium

https://medium.com/coinmonks/what-are-solidity-variables-eecee946d4ca 7/7
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium

Yang Nana Follow

Mar 29, 2018 · 6 min read · Listen

Save

Solidity function types


Reference: http://solidity.readthedocs.io/en/v0.4.21/types.html

Function types are the types of functions. Variables of function type can be assigned
from functions and function parameters of function type can be used to pass functions
to and return functions from function calls. Function types come in four flavours —
internal, external, public and private functions:

Internal functions can only be called inside the current contract (more specifically,
inside the current code unit, which also includes internal library functions and
inherited functions) because they cannot be executed outside of the context of the
current contract. Calling an internal function is realized by jumping to its entry label,
just like when calling a function of the current contract internally.

External functions consist of an address and a function signature and they can be
passed via and returned from external function calls. Can be called from outside, can’t
be call from inside (functions from same contract, functions from inherited contracts)

Private functions can only be called from inside the contract, even the inherited
contracts can’t call them.

Public functions can be called from anywhere.

external :External functions are part of the contract interface, which means they can be
called from other contracts and via transactions. An external function f cannot be called

https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 1/9
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium

internally (i.e. f() does not work, but this.f() works). External functions are sometimes
more efficient when they receive large arrays of data.

public :Public functions are part of the contract interface and can be either called internally
or via messages. For public state variables, an automatic getter function is generated.

internal :Those functions and state variables can only be accessed internally (i.e. from
within the current contract or contracts deriving from it), without using this .

private :Private functions and state variables are only visible for the contract they are
defined in and not in derived contracts.

Function types are notated as follows:

function (<parameter types>) {internal|external|public|private}


[pure|constant|view|payable] [(modifiers)] [returns (<return types>)]

(Please refer this post if you consider using multiple modifiers:


https://medium.com/@yangnana11/how-to-use-multiple-modifiers-in-dapp-
767df776051f )


Functions can be declared pure in which case they promise not to read from or modify
the state.

In addition to the list of state modifying statements explained above, the following are
considered reading from the state:

1. Reading from state variables.

2. Accessing this.balance or <address>.balance .

3. Accessing any of the members of block , tx , msg (with the exception of msg.sig

and msg.data ).

4. Calling any function not marked pure .

https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 2/9
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium

5. Using inline assembly that contains certain opcodes.

pragma solidity ^0.4.16;


contract C {
function f(uint a, uint b) public pure returns (uint) {
return a * (b + 42);
}
}


In contrast to the parameter types, the return types cannot be empty — if the function
type should not return anything, the whole returns (<return types>) part has to be
omitted.

By default, function types are internal, so the internal keyword can be omitted. In
contrast, contract functions themselves are public by default, only when used as the
name of a type, the default is internal.

There are two ways to access a function in the current contract: Either directly by its
name, f, or using this.f . The former will result in an internal function, the latter in
an external function.

If a function type variable is not initialized, calling it will result in an exception. The
same happens if you call a function after using delete on it.

If external function types are used outside of the context of Solidity, they are treated as
the function type, which encodes the address followed by the function identifier
together in a single bytes24 type.

Note that public functions of the current contract can be used both as an internal and
as an external function. To use f as an internal function, just use f, if you want to use
its external form, use this.f .

Additionally, public (or external) functions also have a special member called
selector , which returns the ABI function selector:

https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 3/9
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium

pragma solidity ^0.4.16;


contract Selector {
function f() public view returns (bytes4) {
return this.f.selector;
}
}

Example that shows how to use internal function types:

pragma solidity ^0.4.16;


library ArrayUtils {
// internal functions can be used in internal library functions
because
// they will be part of the same code context
function map(uint[] memory self, function (uint) pure returns (uint)
f)
internal
pure
returns (uint[] memory r)
{
r = new uint[](self.length);
for (uint i = 0; i < self.length; i++) {
r[i] = f(self[i]);
}
}
function reduce(
uint[] memory self,
function (uint, uint) pure returns (uint) f
)
internal
pure
returns (uint r)
{
r = self[0];
for (uint i = 1; i < self.length; i++) {
r = f(r, self[i]);
}
}
function range(uint length) internal pure returns (uint[] memory r)
{
r = new uint[](length);
for (uint i = 0; i < r.length; i++) {
r[i] = i;
}

https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 4/9
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium

}
}
contract Pyramid {
using ArrayUtils for *;
function pyramid(uint l) public pure returns (uint) {
return ArrayUtils.range(l).map(square).reduce(sum);
}
function square(uint x) internal pure returns (uint) {
return x * x;
}
function sum(uint x, uint y) internal pure returns (uint) {
return x + y;
}
}

Another example that uses external function types:

pragma solidity ^0.4.21;


contract Oracle {
struct Request {
bytes data;
function(bytes memory) external callback;
}
Request[] requests;
event NewRequest(uint);
function query(bytes data, function(bytes memory) external callback)
public {
requests.push(Request(data, callback));
emit NewRequest(requests.length - 1);
}
function reply(uint requestID, bytes response) public {
// Here goes the check that the reply comes from a trusted source
requests[requestID].callback(response);
}
}
contract OracleUser {
Oracle constant oracle = Oracle(0x1234567); // known contract
function buySomething() {
oracle.query("USD", this.oracleResponse);
}
function oracleResponse(bytes response) public {
require(msg.sender == address(oracle));
// Use the data
}
}

https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 5/9
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium

And another example:

CryptoKitties source code has this external function. The function looks like this:

function getKitty(uint256 _id) external view returns (


bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
) {
Kitty storage kit = kitties[_id];
// if this variable is 0 then it's not gestating
isGestating = (kit.siringWithId != 0);
isReady = (kit.cooldownEndBlock <= block.number);
cooldownIndex = uint256(kit.cooldownIndex);
nextActionAt = uint256(kit.cooldownEndBlock);
siringWithId = uint256(kit.siringWithId);
birthTime = uint256(kit.birthTime);
matronId = uint256(kit.matronId);
sireId = uint256(kit.sireId);
generation = uint256(kit.generation);
genes = kit.genes;
}

And we have another sol file from another contract call this function

pragma solidity ^0.4.19;


import "./zombiefactory.sol";
contract KittyInterface {
function getKitty(uint256 _id) external view returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 6/9
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium

uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
);
}
contract ZombieFeeding is ZombieFactory {
address ckAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
KittyInterface kittyContract = KittyInterface(ckAddress);
function feedOnKitty(uint _zombieId, uint _kittyId) public {
uint kittyDna;
(,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId);
feedAndMultiply(_zombieId, kittyDna);
}
}

Getter Functions
The compiler automatically creates getter functions for all public state variables. For
the contract given below, the compiler will generate a function called data that does
not take any arguments and returns a uint , the value of the state variable data . The

initialization of state variables can be done at declaration.

pragma solidity ^0.4.0;


contract C {
uint public data = 42;
}
contract Caller {
C c = new C();
function f() public {
uint local = c.data();

https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 7/9
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium

}
}

The getter functions have external visibility. If the symbol is accessed internally (i.e.
without this. ), it is evaluated as a state variable. If it is accessed externally (i.e. with
this. ), it is evaluated as a function.

pragma solidity ^0.4.0;


contract C {
uint public data;
function x() public {
data = 3; // internal access
uint val = this.data(); // external access
}
}

The next example is a bit more complex:

pragma solidity ^0.4.0;


contract Complex {
struct Data {
uint a;
bytes3 b;
mapping (uint => uint) map;
}
mapping (uint => mapping(bool => Data[])) public data;
}

It will generate a function of the following form:

function data(uint arg1, bool arg2, uint arg3) public returns (uint a,
bytes3 b) {
a = data[arg1][arg2][arg3].a;
b = data[arg1][arg2][arg3].b;
}

https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 8/9
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium

Note that the mapping in the struct is omitted because there is no good way to provide the key
for the mapping.

Ethereum Solidity Smart Contracts


Open in app Get unlimited access

Search Medium

https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 9/9
2/12/23, 5:23 PM Getter and Setter Methods in JavaScript | by Manuela Sanchez | Medium

Manuela Sanchez Follow

Mar 25, 2019 · 3 min read · Listen

Save

Getter and Setter Methods in JavaScript

Learning new concepts can make your head spin. Getter and Setter methods in
JavaScript made my head spin. I personally did not understand how and when to use
these methods and even if I needed them. Once I understood this concept I saw the use
in these method and hopefully you all will too after reading this blog.

https://medium.com/@m.sanchez947/getter-and-setter-methods-in-javascript-1fcda13a2344 1/4
2/12/23, 5:23 PM Getter and Setter Methods in JavaScript | by Manuela Sanchez | Medium

Getter and Setter methods allow you to access and change information within an
object. Let’s create an object to put them in practice.

let person = {
first_name: "Manuela",
last_name: "Sanchez"
}

Here we created an Object of a person and we want to begin to add functionality to it


where we can call this object and get the person’s full name. We will use the Getter
method to do this

let person = {
first_name: "Manuela",
last_name: "Sanchez",

get fullName() {
return `${this.first_name} ${this.last_name}`;
}
};

When using the getter method you call it by using the syntax get followed by a method
name fullName() and the condition {return`${this.first_name} ${this.last_name}}` .

Now try to console.log(person.fullName) and watch it spit out the full name “Manuela
Sanchez” as a string. Cool right! But let’s say we want your name is not Manuela
Sanchez and you want to change it to yours. Getter Methods allow you to read data but
not change it. Right now if you try to set fullName to a variable you will get an error
and this is when the Setter method comes into play.

let person = {
first_name: "Manuela",
last_name: "Sanchez",

get fullName() {
return `${this.first_name} ${this.last_name}`;
}

set fullName(value) {
https://medium.com/@m.sanchez947/getter-and-setter-methods-in-javascript-1fcda13a2344 2/4
2/12/23, 5:23 PM Getter and Setter Methods in JavaScript | by Manuela Sanchez | Medium

[this.first_name, this.last_name] = value.split(" ");


}
};

When calling the Setter method it is as easy as saying set followed by the function
fullName(value) and the condition [this.fist_name, this.last_name] = value.split("

") . Make sure to pass in an argument in your function to represent the change. Since
fullName() gives us the string of the person’s full name we will use (value) to
represent the new string. Now let’s try to change our data person.fullName = "John

Smith" . If you did this in your console you will notice you did not get any errors!

Let see what happens if we call console.log(person.first_name) and


console.log(person.last_name). We will get the value of both “John” and “Smith”. Great!
We changed the our data. Both of these methods work together to make magic happen.
We are able to get a string of a full name and change the full name.

Getter and Setter methods go more in depth than this blog. With this tool we are also
able to create hidden functions for your users not to have access to. They create
security and value to an object. I wont go into more detail about this but this is a good
article to read all about how that works.

John Resig - JavaScript Getters and Setters


Edit description
johnresig.com

There are also different ways you can call getter and setter methods and these two
articles are great for that. Hopefully I gave you all the insight of the basic functionality
of getter and setter methods in JavaScript to stop your head from Spinning and give
you a better since of direction.

Working with objects

https://medium.com/@m.sanchez947/getter-and-setter-methods-in-javascript-1fcda13a2344 3/4
2/12/23, 5:23 PM Getter and Setter Methods in JavaScript | by Manuela Sanchez | Medium

JavaScript is designed on a simple object-based paradigm. An object is


a collection of properties, and a property is an…
developer.mozilla.org

Property getters and setters


There are two kinds of properties. The first kind is data properties. We
already know how to work with them. Actually…
javascript.info

Java Script Getter Methods


Open in app Get unlimited access

Search Medium

https://medium.com/@m.sanchez947/getter-and-setter-methods-in-javascript-1fcda13a2344 4/4
2/12/23, 5:25 PM What is the difference between View & Pure Function Modifier in Solidity? | by Yong kang Chia | Medium

Yong kang Chia Follow

Mar 10, 2022 · 1 min read · Listen

Save

What is the difference between View & Pure


Function Modifier in Solidity?
Function modifiers
You want to create a function without actually changing the state in Solidity — e.g. it
doesn’t change any values or write anything.

What modifier could you use?

View
So in this case we could declare it as a view function, meaning it’s only viewing the data
but not modifying it:

function sayHello() public view returns (string memory) {

Pure
Solidity also contains pure functions, which means you’re not even accessing any data
in the app. Consider the following:

function _multiply(uint a, uint b) private pure returns (uint) {


return a * b;
}

https://extremelysunnyyk.medium.com/what-is-the-difference-between-view-pure-function-modifier-in-solidity-a06c71f0c3e7 1/2
2/12/23, 5:25 PM What is the difference between View & Pure Function Modifier in Solidity? | by Yong kang Chia | Medium

This function doesn’t even read from the state of the app — its return value depends
only on its function parameters. So in this case we would declare the function as pure.

Open in app Get unlimited access


Note: It may be hard to remember when to mark functions as pure/view. Luckily the
Solidity compiler is good about issuing warnings to let you know when you should use
Search Medium
one of these modifiers.

Adapted from CryptoZombies

Solidity Ethereum

https://extremelysunnyyk.medium.com/what-is-the-difference-between-view-pure-function-modifier-in-solidity-a06c71f0c3e7 2/2
2/12/23, 5:27 PM Solidity: The pure getter and view functions | by Bruno Delb | Crypto DevOps Academy | Medium

Published in Crypto DevOps Academy

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Bruno Delb Follow

Jul 5, 2022 · 2 min read · · Listen

Save

Solidity: The pure getter and view functions


Solidity provides two particular types of getter functions: view and pure .

The view functions


view allows the state to be read but does not allow the state to be modified:

uint public a = 1;
function viewFunction(uint b) public view returns (uint) {
return a + b;
}

Let’s compile and deploy the contract. Then call the viewFunction() function:

https://medium.com/cryptodevopsacademy/solidity-the-pure-getter-and-view-functions-281bff8fde23 1/4
2/12/23, 5:27 PM Solidity: The pure getter and view functions | by Bruno Delb | Crypto DevOps Academy | Medium

The result is 3 = 1 + 2.

The view functions therefore ensure that they will not modify the state. The following
statements modify the state:

Modify a state variable,

Emit an event,

Create a contract,

Use self-destruct,

Send Ether via a call,

Call a function that is not marked view or pure ,

Use a low level call,

Use an inline assembly containing some opcodes.

Getter methods are by default view functions.

The pure functions


pure forbids the reading or modification of the state :

function pureFunction(uint x, uint y) public pure returns (uint) {


return x + y;
}

Let’s compile and deploy the contract. Then call the pureFunction() function:

https://medium.com/cryptodevopsacademy/solidity-the-pure-getter-and-view-functions-281bff8fde23 2/4
2/12/23, 5:27 PM Solidity: The pure getter and view functions | by Bruno Delb | Crypto DevOps Academy | Medium

The function returns the value 3 = 1 +2.

The pure functions make sure that they do not read or modify the state.

The following statements are considered to read the state:

Read a state variable,

Accessing address(this).balance or <address>.balance ,

Access a special variable block , tx , msg ( msg.sig and msg.data can be read),

Call a pure unmarked function,

Use an inline assembly containing certain opcodes.

Open in app Sign up Sign In

Solidity Blockchain Ethereum


Search Medium

https://medium.com/cryptodevopsacademy/solidity-the-pure-getter-and-view-functions-281bff8fde23 3/4
2/12/23, 5:27 PM Solidity: The pure getter and view functions | by Bruno Delb | Crypto DevOps Academy | Medium

Get an email whenever Bruno Delb publishes.

Your email

Subscribe

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

About Help Terms Privacy

Get the Medium app

https://medium.com/cryptodevopsacademy/solidity-the-pure-getter-and-view-functions-281bff8fde23 4/4
2/12/23, 5:29 PM Solidity - View and Pure Functions - GeeksforGeeks

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+

Solidity – View and Pure Functions


Last Updated : 11 May, 2022

Read Discuss Courses Practice Video

The view functions are read-only function, which ensures that state variables cannot be

modified af ter calling them. If the statements which modif y state variables, emitting

events, creating other contracts, using selfdestruct method, transferring ethers via

calls, Calling a function which is not ‘view or pure’, using low-level calls, etc are present

in view functions then the compiler throw a warning in such cases. By default, a get

method is view function.

Example : In the below example, the contract Test defines a view function to calculate

the product and sum of two unsigned integers.

Solidity

// Solidity program to 


// demonstrate view
// functions
pragma solidity ^0.5.0;
  
// Defining a contract
contract Test {
      
    // Declaring state 
    // variables
    uint num1 = 2; 
    uint num2 = 4;
  
   // Defining view function to  
   // calculate product and sum 
   // of 2 numbers
Start Your Coding Journey Now!
   function getResult( Login Register
https://www.geeksforgeeks.org/solidity-view-and-pure-functions/ 1/7
2/12/23, 5:29 PM Solidity - View and Pure Functions - GeeksforGeeks

   ) public view returns(


     uint product, uint sum){
       uint num1 = 10;
       uint num2 = 16;
      product = num1 * num2;
      sum = num1 + num2; 
   }
}

Output : 

The pure functions do not read or modif y the state variables, which returns the values

only using the parameters passed to the function or local variables present in it. If the

Start Your Coding Journey Now!


statements which read the state variables, access the address or balance, accessing any

https://www.geeksforgeeks.org/solidity-view-and-pure-functions/ 2/7
2/12/23, 5:29 PM Solidity - View and Pure Functions - GeeksforGeeks

global variable block or msg, calling a function which is not pure, etc are present in pure

functions then the compiler throws a warning in such cases.

Example : In the below example, the contract Test defines a pure function to calculate

the product and sum of two numbers.

Solidity

// Solidity program to  


// demonstrate pure functions
pragma solidity ^0.5.0;
  
// Defining a contract
contract Test {
  
    // Defining pure function to 
    // calculate product and sum
   // of 2 numbers
   function getResult(
   ) public pure returns(
     uint product, uint sum){
      uint num1 = 2; 
      uint num2 = 4;
      product = num1 * num2;
      sum = num1 + num2; 
   }
}

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-view-and-pure-functions/ 3/7
2/12/23, 5:29 PM Solidity - View and Pure Functions - GeeksforGeeks

Output : 

Like 9

Previous Next

Related Articles

1. Solidity - Functions
Start Your Coding Journey Now!
https://www.geeksforgeeks.org/solidity-view-and-pure-functions/ 4/7
2/12/23, 5:29 PM Solidity - View and Pure Functions - GeeksforGeeks

2. Solidity - While, Do-While, and For Loop

3. Solidity - Break and Continue Statements

4. Solidity - Enums and Structs

5. Creating a Smart Contract that Returns Address and Balance of Owner using
Solidity

6. Dynamic Arrays and its Operations in Solidity

7. Introduction to Bytecode and Opcode in Solidity

8. Difference Between this and address(this) in Solidity

9. Solidity - Types

10. What are Events in Solidity?

Ar ticle Contributed By :

jeeteshgavande30
@jeeteshgavande30

Vote for difficulty

Easy Normal Medium Hard Expert

Article Tags : Solidity-Functions, Blockchain, Solidity

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-view-and-pure-functions/ 5/7
2/12/23, 5:29 PM Solidity - View and Pure Functions - GeeksforGeeks

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Advertise with us Video Tutorials
Courses

News Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Start Your
WebCoding Journey Now!
Development Contribute
https://www.geeksforgeeks.org/solidity-view-and-pure-functions/ 6/7
2/12/23, 5:29 PM Solidity - View and Pure Functions - GeeksforGeeks

Web Tutorials Write an Article


Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-view-and-pure-functions/ 7/7
2/12/23, 5:31 PM Solidity Tutorial : all about Constructors | by Jean Cvllr | Coinmonks | Medium

Published in Coinmonks

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Jean Cvllr Follow

Aug 13, 2021 · 6 min read · · Listen

Save

Solidity Tutorial : all about Constructors

This article covers constructors, a function in Solidity that runs only once, when the
contract is deployed onto the Ethereum network.

Table of Contents
https://medium.com/coinmonks/solidity-tutorial-all-about-constructors-46a10610336#:~:text=How to define a constructor in Solidity%3F,it is a special f… 1/10
2/12/23, 5:31 PM Solidity Tutorial : all about Constructors | by Jean Cvllr | Coinmonks | Medium

Introduction

How to define a constructor

Public vs Internal Constructors

Constructors’ parameters and inheritance

Payable Constructor

Introduction
Constructors are a common concept in OOP. In many programming languages, when
defining classes, you can also define a magic method that will run once, at the time a
new instance of the object is created.

In the case of Solidity, the code defined inside the constructor will run only once, at
the time the contract is created and deployed in the network.

An important point to mention is the following:

The bytecode deployed on the network does not


contain the constructor code, since the constructor
code runs only once on deployment.
OpenZeppelin explains the idea more precisely in the second part of their article series
“Deconstructing a Solidity Contract”:

The constructor code is part of the creation code, not


part of the runtime code.
How to define a constructor in Solidity?

https://medium.com/coinmonks/solidity-tutorial-all-about-constructors-46a10610336#:~:text=How to define a constructor in Solidity%3F,it is a special f… 2/10


2/12/23, 5:31 PM Solidity Tutorial : all about Constructors | by Jean Cvllr | Coinmonks | Medium

You define a constructor in Solidity with the keyword constructor() followed by


parentheses. Note that you do not need to add the function keyword, since it is a
special function.

contract Example {
constructor() {
// code running when contract deployed...
}
}

NB: Prior to version 0.4.22 of Solidity, constructors were defined as functions with the same
name as the contract (like in JAVA?). This syntax was deprecated and is not allowed anymore
since version 0.5.0

Constructors are optional


Like when creating a class in other programming language.

If there is no constructor specified in the contract, the contract will assume the default
empty constructor, equivalent to constructor() {} .

Public vs Internal Constructors

Before Solidity 0.7.0


Prior to Solidity 0.7.0, contract’s constructors in Solidity could be defined with the
following 2 visibilities: public (default) or internal .

The main difference between the two is simple.

A contract defined with an internal constructor cannot


be deployed.

https://medium.com/coinmonks/solidity-tutorial-all-about-constructors-46a10610336#:~:text=How to define a constructor in Solidity%3F,it is a special f… 3/10


2/12/23, 5:31 PM Solidity Tutorial : all about Constructors | by Jean Cvllr | Coinmonks | Medium

Therefore if contract has an internal constructor, you cannot deploy the contract at
all.

Neither directly

Nor via an other contract.

If you try to do so by selecting the contract in Remix and click on the Deploy button,
the IDE will return you the following error message.

Error message from Remix, when trying to deploy a contract with an internal constructor.

Similarly, contracts with internal constructors cannot be created directly within other
contracts. The code snippet below will not compile.

pragma solidity 0.5.0;

contract C {
constructor() internal {}
}
contract D {

function tryDeploying() public {


C c = new C();
}

https://medium.com/coinmonks/solidity-tutorial-all-about-constructors-46a10610336#:~:text=How to define a constructor in Solidity%3F,it is a special f… 4/10


2/12/23, 5:31 PM Solidity Tutorial : all about Constructors | by Jean Cvllr | Coinmonks | Medium

Prior to Solidity <0.7.0

But with the release of Solidity 0.7.0 and its new breaking changes, internal

constructors are deprecated and just an old story, and the message from the picture
above has been removed.

Since Solidity 0.7.0


If you are writing contracts with a Solidity compiler greater than 0.7.0, you do not have
to worry about internal constructors anymore.

In fact, you just have to 1) remove the internal keyword in your constructor, and 2)
define your contract as abstract .

New Solidity >0.7.0 era ! 😃

Final Note on “internal constructors” (= abstract contracts)


Following on the difference between both constructor visibility, the final question is:

if the contract intends to be inherited, should the


constructor be defined as internal or public? (= the
contract defined as abstract or not?)
https://medium.com/coinmonks/solidity-tutorial-all-about-constructors-46a10610336#:~:text=How to define a constructor in Solidity%3F,it is a special f… 5/10
2/12/23, 5:31 PM Solidity Tutorial : all about Constructors | by Jean Cvllr | Coinmonks | Medium

Answer: if the contract is not intended to be created directly, but rather inherited, it
might be safer to use an internal constructor (= define the contract as abstract ! 😉).
This will prevent the contract to be created directly.

An internal constructor / abstract contract enables the child contract that inherits from
it to either setup some default logic on deployment (specific to the abstract contract).
This initial deployment logic can be dynamic, by declaring the constructor with
parameters. This will be the next topic of our article.

Constructors’ parameters and inheritance


We have seen previously that a constructor can accept arguments by defining it with
parameters like functions.

But what about if a contract B derived from another contract A that has a constructor
argument?

Let’s see with an example.

pragma solidity 0.8.0;


contract Animal {

uint feet;
bool canSwim;

constructor(uint _feet, bool _canSwim) {


feet = _feet;
canSwim = _canSwim;
}
}
// how to derive from Animal while passing constructors arguments?
contract Lion {

https://medium.com/coinmonks/solidity-tutorial-all-about-constructors-46a10610336#:~:text=How to define a constructor in Solidity%3F,it is a special f… 6/10


2/12/23, 5:31 PM Solidity Tutorial : all about Constructors | by Jean Cvllr | Coinmonks | Medium

If a base contract has arguments, derived contracts need to specify all of them. This
can be done in 2 ways:

Directly in the inheritance list


This is useful if you already know the values in advance, and these can be hardcoded in
the code.

contract Lion is Animal(4, true) {


}

The way is more convenient if the constructor arguments are constants and they
define the behaviour of the contract, or describes it.

A great example is when creating a standard ERC20 contract.

Through the derived constructor, like a “modifier”


This way can be used if the constructor arguments of the base contract depend on
those of the derived contract.

To illustrate, let’s extend add another state variable to our Animal contract.

contract Animal {

string name;
uint feet;
bool canSwim;

constructor(string memory _name, uint _feet, bool _canSwim) {


name = _name;
feet = _feet;
canSwim = _canSwim;
}
}
contract Lion is Animal {

constructor(string memory _name)


Animal(_name, 4, true)
{
// ...
https://medium.com/coinmonks/solidity-tutorial-all-about-constructors-46a10610336#:~:text=How to define a constructor in Solidity%3F,it is a special f… 7/10
2/12/23, 5:31 PM Solidity Tutorial : all about Constructors | by Jean Cvllr | Coinmonks | Medium

}
}

NB: specifying the arguments in both places (inheritance list + modifier in derived
constructor) will generate an error.

NB2: If a derived contract does not specify the arguments to all of its base contracts’
constructors, it will be abstract.

Payable Constructor
Constructors can accept Ethers. In this case, they should be mentioned with the
keyword “payable”. In the Remix IDE, the “deploy” button will change color (shown in
red) if the constructor accept ether.

If you try to add ether when deploying a contract defined with a non payable
constructor, it will throw you an exception and revert.

The difference between a payable and non payable constructor is also reflected in the
creation code.

If the constructor is non-payable, the creation code contains 8 low-levels instructions


(in EVM assembly), that check if some ethers has been sent to the contract once it has
been deployed. If it is the case, the check fails and the contract reverts.

You can see the example here: https://blog.openzeppelin.com/deconstructing-a-


solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c/

If the constructor is defined as payable , this 8 EVM instructions are removed and not
present.

What you can’t and shouldn’t do with Constructors !


You cannot access functions externally in the constructor, because the contract
functions do not exist yet (as the contract has not been deployed yet).

Constructors can not be declared in an interface.

https://medium.com/coinmonks/solidity-tutorial-all-about-constructors-46a10610336#:~:text=How to define a constructor in Solidity%3F,it is a special f… 8/10


2/12/23, 5:31 PM Solidity Tutorial : all about Constructors | by Jean Cvllr | Coinmonks | Medium

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also, Read
Crypto Copy Trading Platforms | Coinmama Review

Crypto exchanges in India | Bitcoin Savings Account

OKEx vs KuCoin | Celsius Alternatives | How to Buy VeChain

Binance Futures Trading | 3Commas vs Mudrex vs eToro

How to buy Monero | IDEX Review | BitKan Trading Bot

Solidity Ethereum Smart Contracts Blockchain Programming

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Your email

Get this newsletter

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

https://medium.com/coinmonks/solidity-tutorial-all-about-constructors-46a10610336#:~:text=How to define a constructor in Solidity%3F,it is a special f… 9/10


2/12/23, 5:31 PM Solidity Tutorial : all about Constructors | by Jean Cvllr | Coinmonks | Medium

About Help Terms Privacy

Open in app Sign up Sign In

Get the Medium app


Search Medium

https://medium.com/coinmonks/solidity-tutorial-all-about-constructors-46a10610336#:~:text=How to define a constructor in Solidity%3F,it is a special… 10/10


2/12/23, 5:33 PM How to write constructor in Solidity version 0.4.22 and above. | by Hideyoshi Moriya | Medium

Hideyoshi Moriya Follow

May 19, 2018 · 1 min read · Listen

Save

How to write constructor in Solidity version


0.4.22 and above.
Up to Solidity 0.4.21
Up to Solidity 0.4.21, constructor can be defined by the same name of its contract
name.

However, this can possibly cause unintended bugs when contracts are renamed
and their constructors are not renamed.

In Solidity, “contract” is almost the same as “class” in ordinal programming


language.

Example: Contract “Piyo”


A constructor name should be defined as the function which has the same name of
the contract name “Piyo”.

pragma solidity 0.4.21;

contract Piyo {
string public message;

// Constructor
function Piyo(string _message) public {
message = _message;
}

https://piyopiyo.medium.com/how-to-write-constructor-in-solidity-version-0-4-22-and-above-dcb8c042974f 1/3
2/12/23, 5:33 PM How to write constructor in Solidity version 0.4.22 and above. | by Hideyoshi Moriya | Medium

Solidity 0.4.22 and above


Use a constructor keyword and create an anonymous function

Not function constructor(args) {...} but constructor (args) {...} .

Example: Contract “Piyo”


A constructor should be defined by using a constructor keyword.

pragma solidity 0.4.22;

contract Piyo {
string public message;
// Constructor
constructor (string _message) public {
message = _message;
}

Notes
In solidity version 0.4.22, a constructor can be defined with both the new and old
way.

However, one of them can be used. This is possible to cause unintended bugs. In
my experiment, a constructor which is called first is used.

This issue has been fixed in Solidity 0.4.23.


Open in app Get unlimited access

Support Search Medium


If you find this article is helpful, it would be greatly appreciated if you could tip Ether
to the address below. Thank you!

https://piyopiyo.medium.com/how-to-write-constructor-in-solidity-version-0-4-22-and-above-dcb8c042974f 2/3
2/12/23, 5:33 PM How to write constructor in Solidity version 0.4.22 and above. | by Hideyoshi Moriya | Medium

0x0089d53F703f7E0843953D48133f74cE247184c2

Ethereum Solidity Blockchain

https://piyopiyo.medium.com/how-to-write-constructor-in-solidity-version-0-4-22-and-above-dcb8c042974f 3/3
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+

Solidity – Constructors
Difficulty Level : Medium ● Last Updated : 11 May, 2022

Read Discuss Courses Practice Video

A constructor is a special method in any object-oriented programming language which

gets called whenever an object of a class is initialized. It is totally different in case of

Solidity, Solidity provides a constructor declaration inside the smar t contract and it

invokes only once when the contract is deployed and is used to initialize the contract

state. A default constructor is created by the compiler if there is no explicitly defined

constructor.

Creating a constructor

A Constructor is defined using a constructor keyword without any function name

followed by an access modifier. It ’s an optional function which initializes state variables

of the contract. A constructor can be either internal or public, an internal constructor

marks contract as abstract. 

Syntax :

constructor() <Access Modifier> {


}

Example : In the below example, in the contract constructorExample, a constructor is

created to initialize the state variable str. 

Solidity

Start Your Coding Journey Now! Login Register


https://www.geeksforgeeks.org/solidity-constructors/ 1/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

// Solidity program to demonstrate


// creating a constructor
pragma solidity ^0.5.0;       
         
// Creating a contract
contract constructorExample {       
         
    // Declaring state variable
    string str;       
             
    // Creating a constructor
    // to set value of 'str'
    constructor() public {                 
        str = "GeeksForGeeks";       
    }       
      
    // Defining function to
    // return the value of 'str' 
    function getValue(
    ) public view returns (
      string memory) {       
        return str;       
    }     
}

Output : 

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-constructors/ 2/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

Constructor in Inheritance

In case if a constructor is not defined then the default constructor is called, but if the

constructor is defined in a parent contract and having some arguments then the child

contract should also provide the required parameters to the constructor. If the child

contract is not passing any parameter to the parent ’s constructor the child contract will

become an abstract contract. There are two ways of calling a parent contract ’s

constructor: 

1. Direct Initialization: In the below example, the direct initialization method is used to

initialize the constructor of the parent class.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-constructors/ 3/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

Solidity

// Solidity program to demonstrate


// Constructor in Inheritance
pragma solidity ^0.5.0;
 
// Creating a contract
contract Base {
 
   // Declaring variable
   uint data;
 
   // Defining a constructor
   constructor(uint _data) public {
      data = _data;  
   }
 
   // Defining function
   function Print(
   ) public  returns(string memory){
       return "Direct Initialization";
   }
 
}
 
// Child contract inheriting
// the parent contract 'Base'
contract Derived is Base(2){
 
    // Defining a constructor
    constructor() public {}
 
   // Defining function to access
   // variable of parent contract
   function getData(
   ) external returns(uint){
       uint result = data ** 2;
       return result;
   }
}
 
// Caller contract
contract caller{
 
   // Creating an object of child contract
    Derived c = new Derived();
 
Start Your Coding Journey Now!
   // Accessing functions of parent

https://www.geeksforgeeks.org/solidity-constructors/ 4/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

   // and child contract using


   // object of child contract
    function getResult() public returns(uint){
        c.Print();
        return c.getData();
    }
}

Output : 

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-constructors/ 5/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

2. Indirect Initialization: In the below example, the indirect initialization using

Base(string(abi.encodePacked(_info, _info))) is done to initialize the constructor of the

base class.

Solidity

// Solidity program to demonstrate


// Indirect Initialization
pragma solidity ^0.5.0;
 
// Creating a contract
contract Base {
 
   // Declaring state variable
   string str;
 
   // Defining a constructor
   constructor(
     string memory _str) public {
      str = _str;  
   }
 
   // Defining a function
   function Print(
   ) public returns(string memory){
       return "Indirect Initialization";
   }
}
 
// Child contract inheriting
// parent contract 'Base'
contract Derived is Base {
 
   // Defining a constructor
   constructor(
     string memory _info) Base(
     string(abi.encodePacked(
       _info, _info))) public {}
 
   // Defining function to
   // return value of parent
   // contract variable 'str'
Start Your Coding Journey Now!
   function getStr(

https://www.geeksforgeeks.org/solidity-constructors/ 6/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

   ) public view returns(string memory){


       return str;
   }
}
 
// Caller contract
contract caller {
 
    // Creating an object of
    // child contract
    Derived c
      = new Derived("GeeksForGeeks");
 
    //Defining a function to access
    // functions of the parent
    //contract and child contract
    function getResult() public view{
        c.Print();
        c.getStr();
    }
}

Output : 

Start Your Coding Journey Now!


Need of Constructors

https://www.geeksforgeeks.org/solidity-constructors/ 7/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

Constructors are ver y useful in a smar t contract, a parameter value can be defined at the

run time and can also restrict the method call. Constructor overloading is not suppor ted

in Solidity, it only allows one constructor at a time.

Example : In the below example, the contract constructorExample consists of a

constructor to demonstrate the need for the constructor.

Solidity

// Solidity program to demonstrate


// Need of constructors
pragma solidity ^0.5.0;       
         
// Creating a contract
contract constructorExample {       
         
    // Declaring state variable
    string str;       
    address private owner
      = 0x62Ab98A0efB752C48bd82836D0b4335018B9B97e;
 
    // Defining constructor
    constructor(string memory string) public {                 
        if(msg.sender == owner){   
            str = string;   
        }       
    }       
     
    // Defining function to
    // return value of 'str'  
    function getValue() public view returns (
      string memory) {       
        return str;       
    }     
}

Start Your Coding Journey Now!


Output : 

https://www.geeksforgeeks.org/solidity-constructors/ 8/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

Like 13

Next

Solidity - While, Do-While, and For


Loop

Related Articles

1. Solidity - Types

2. Solidity - Functions

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-constructors/ 9/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

3. What are Events in Solidity?

4. Solidity - Inheritance

5. Solidity - Polymorphism

6. Solidity - View and Pure Functions

7. Solidity - Encapsulation

8. How to Install Solidity in Windows?

9. Solidity - While, Do-While, and For Loop

10. Solidity - Break and Continue Statements

Ar ticle Contributed By :

jeeteshgavande30
@jeeteshgavande30

Vote for difficulty

Current difficulty : Medium

Easy Normal Medium Hard Expert

Improved By : rkbhola5

Article Tags : Blockchain, Solidity

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-constructors/ 10/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Advertise with us Video Tutorials
Courses

News Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Start Your
WebCoding Journey Now!
Development Contribute
https://www.geeksforgeeks.org/solidity-constructors/ 11/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks

Web Tutorials Write an Article


Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-constructors/ 12/12
2/12/23, 5:38 PM UNDERSTANDING VALUE TYPES IN SOLIDITY | by Sayrarh | Coinmonks | Medium

Published in Coinmonks

Sayrarh Follow

Mar 17, 2022 · 5 min read · Listen

Save

UNDERSTANDING VALUE TYPES IN SOLIDITY


Before I go further to talk about the various value types in solidity, let’s recap what
solidity is for better understanding.

What is Solidity?

Solidity is an object-oriented programming language that helps to implement smart


contracts on various blockchain platforms, Ethereum in particular. Solidity is a
https://medium.com/coinmonks/understanding-value-types-in-solidity-5caa1af846ef 1/10
2/12/23, 5:38 PM UNDERSTANDING VALUE TYPES IN SOLIDITY | by Sayrarh | Coinmonks | Medium

statically typed language, which means that you have to specify every variable(state
&local) at compile time.

What are Smart Contracts?

Smart contracts are programs that run on the Ethereum blockchain. They are
computer programs stored on the blockchain that allows us to convert traditional
contracts into digital parallels. Smart contracts are very logical, following an if this
then that structure.

Smart contracts are a type of Ethereum account. This means they have a balance and
they can send transactions over the network. However they’re not controlled by a user,
instead, they are deployed to the network and run as programmed. User accounts can
then interact with a smart contract by submitting transactions that execute a function
defined on the smart contract. Smart contracts can define rules, as a regular contracts,
and automatically enforce them via the code. Smart contracts cannot be deleted by
default, and interactions with them are irreversible.

Solidity provides several elementary types which when combined, form complex
types. Solidity has different data types. These data types are grouped into two
categories which are the reference types and value types. In this article, we will focus
on value types. So, let us see what the value types are.

Value Types
The following types are called value types because variables of these types will always
be passed by value, i.e. they are always copied when they are used as function
arguments or in assignments.

Boolean
Boolean values are represented by bool. This data type accepts only two values True or
False.

The operators applicable on bool type are;

! (logical negation)

l && (logical conjunction i.e. and)


https://medium.com/coinmonks/understanding-value-types-in-solidity-5caa1af846ef 2/10
2/12/23, 5:38 PM UNDERSTANDING VALUE TYPES IN SOLIDITY | by Sayrarh | Coinmonks | Medium

l || (logical disjunction i.e. or)

l == (equality)

l != (inequality)

The boolean operators take up 1 byte of storage. The logical “and” and logical “or”
operator follow the same short-circuiting rules as in other programming languages.
For example, In the expression var(x) || var(y), if var(x) evaluates to true, var(y) will not
be evaluated.

Integer
There are two main Solidity types of integers of differing sizes:

int— signed integers.

uint — unsigned integers.

uint8 to uint256 (Unsigned integers from 8 bits to 256 bits)

int8 to int256(Signed integers from 8 bits to 256 bits) and both take up 32 bytes by
default.

Keywords such as uint8 and uint256 can be used to allocate a storage size of 8 bits to
256 bits respectively. By default, the allocation is 256 bits. That is, uint and int can be
used in place of uint256 and int256. uint and int are aliases(a false or assumed identity)
for uint256 and int256, respectively. There are two modes in which arithmetic is
performed on these types.

Unchecked and Checked Mode

By default arithmetic is always checked, which means that if the result of an operation falls
outside the value range of the type, the call is reverted through a failing assertion. Switching
to the unchecked mode using ‘unchecked {…}’

The operations which we can perform on integers are ;

Comparison operators (evaluates to bool)

https://medium.com/coinmonks/understanding-value-types-in-solidity-5caa1af846ef 3/10
2/12/23, 5:38 PM UNDERSTANDING VALUE TYPES IN SOLIDITY | by Sayrarh | Coinmonks | Medium

· <= (less than or equal)

· < (less than)

· == (equal to)

· != (not equal to)

· >= (greater than or equal)

· > (greater than)

Bit operators

· & (bitwise AND)

· | (bitwise inclusive OR)

· ^ (bitwise XOR (exclusive OR))

· ~ (bitwise NOT)

Arithmetic operators

· + (addition)

· — (subtraction)

· unary — (subtract on a single operand)

· unary + (add on a single operand)

· * (multiply a single operand)

· / (division)

· % (remainder (of division))

· ** (exponentiation)

https://medium.com/coinmonks/understanding-value-types-in-solidity-5caa1af846ef 4/10
2/12/23, 5:38 PM UNDERSTANDING VALUE TYPES IN SOLIDITY | by Sayrarh | Coinmonks | Medium

· << (left shift)

· >> (right shift)

Fixed Point Numbers


These are used to store floating numbers with decimal values. There are two types of
fixed point numbers namely:

fixed — signed fixed point number.

ufixed — unsigned fixed point number.

Keywords: “ufixedMxN” and “fixedMxN”, where;

M represents the number of bits taken by the type and;

N represents the number of decimal points available.

M must be divisible by 8 and goes from 8 to 256 bits. N must be between 0 and 80,
inclusive. ufixed and fixed are aliases for ufixed128x18 and fixed128x18, respectively.

Note: fixed point numbers can be declared in Solidity, but they are not completely
supported by this language.

Address
Every account and smart contract has an address that is stored as 20 bytes. The address
is used to send and receive ethers across accounts. This can be considered as a public
identity or account number on Blockchain. The address type comes in two types
namely;

· address- holds a 20-byte value (size of an Ethereum address).

· address payable- is the same as address, but have transfer and send members.

Note: The idea behind the distinctions between smart contract addresses is that the
address payable can receive Ether, while a simple address cannot.

Fixed-size Byte Arrays

https://medium.com/coinmonks/understanding-value-types-in-solidity-5caa1af846ef 5/10
2/12/23, 5:38 PM UNDERSTANDING VALUE TYPES IN SOLIDITY | by Sayrarh | Coinmonks | Medium

The value types bytes1, bytes2, bytes3, …, bytes32 contain a sequence of bytes (from 1
to 32).

Operators that can be applied to this Solidity value type:

· Comparisons: <=, <, ==, !=, >=, > (evaluate to bool)

· Bit operators: &, |, ^ (bitwise exclusive or), ~ (bitwise negation)

· Shift operators: << (left shift), >> (right shift)

· Index access: If x is of type bytesI, then x[k] for 0 <= k < I returns the k th byte (read-
only).

Enums
Enums in solidity is one way to create a user-defined type. They are explicitly
convertible to and from all integer types but implicitly. Enums values are numbered in
the order they are defined, starting from 0.

Example:
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;


contract EnumType {
enum Months { Jan, Feb, Mar, April, May, June, July, Aug, Sept, Oct,
Nov, Dec }
function getFirstEnum() public pure returns(Months) {
return Months.Jan;
}
}
//result 0: uint8: 0 ( Enums are numbered in the way they are defined
i.e Jan-0, Feb-1, Mar-2 and so on )

The explicit conversion from integer checks at runtime that the value lies inside the
range of the enum and causes a panic error otherwise. Enums require at least one

https://medium.com/coinmonks/understanding-value-types-in-solidity-5caa1af846ef 6/10
2/12/23, 5:38 PM UNDERSTANDING VALUE TYPES IN SOLIDITY | by Sayrarh | Coinmonks | Medium

member, and its default value when declared is the first member. Enums cannot have
more than 256 members.

https://medium.com/coinmonks/understanding-value-types-in-solidity-5caa1af846ef 7/10
2/12/23, 5:38 PM UNDERSTANDING VALUE TYPES IN SOLIDITY | by Sayrarh | Coinmonks | Medium

1 // SPDX-License-Identifier: MIT
2 pragma solidity ^0.8.7;
3
4 contract ValueType{
5
6 // boolean
7 // uint
8 // int
9 // address
10 // bytes
11 // enums
12
13 bool testBool = true;
14 bool testBool1 = false;
15
16 // unsigned integer
17 uint age = 15;
18 uint8 score1 = 255;
19 // (2 ** 8) - 1 = 256 - 1 = 255
20 uint16 score2 = 40;
21 uint24 score3 = 56;
22 uint256 score4 = 45;
23 // uint is an alias for uint256
24 // 11111111 = 255
25
26
27 // integer
28 int temp = -37;
29 int8 temp1 = -2;
30 int256 temp2 = -55;
31
32 int public min256 = type(int).min;
33 int public max256 = type(int).max;
34
35 int8 public min8 = type(int8).min;
36 int8 public max8 = type(int8).max;
37
38
39 // address and address payable
40 // a 20-byte hexadecimal number
41 // Hex: 123456789ABCDEF
42 address testAddr = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;
43
44 address payable testAddr2 = payable(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);
45
https://medium.com/coinmonks/understanding-value-types-in-solidity-5caa1af846ef 8/10
2/12/23, 5:38 PM UNDERSTANDING VALUE TYPES IN SOLIDITY | by Sayrarh | Coinmonks | Medium
45
I hope
46
this article made you understand the value types in solidity better. Watch out for
// bytes1, bytes2, bytes3 => bytes32
my
47 next article on reference types.
48 bytes1 public testBytes = "W";

Thank
49 you for public
bytes2 reading to the end!
testBytes1 = "er";
50 bytes32 public testBytes32 = "FGGGSS";
51
52 JoinenumCoinmonks
UserType { Telegram Channel and Youtube
54 Channel learn about crypto trading and investing
53 ADMIN,
SUBADMIN,
55 NORMALUSER

Also,
56 Read
}
57
Best Free Crypto Signals | YoBit Review | Bitbns Review
58 // function testEnums() external pure returns(UserType, UserType, UserType){
59 // UserType admin = UserType.ADMIN;
OKEx Review | Kucoin Trading Bot| Futures Trading Bots
60 // UserType subadmin = UserType.SUBADMIN;
61 // UserType normaluser = UserType.NORMALUSER;
AscendEx Staking | Bot Ocean Review | Best Bitcoin Wallets
62 // return (admin, subadmin, normaluser);
63 // }
Huobi Review | OKEx Margin Trading | Futures Trading
64 // function seeAttributes(address addr) external view returns(uint){
65 // uint balance = addr.balance;
Coinbase Staking | Hotbit Review | KuCoin Review
66 // return balance;
67 // }
68
69 // function seeContractAddressAndBalance() external view returns(address, uint){
70 // address contractAddress = address(this);
71 // uint balance = contractAddress.balance;
72 // return (contractAddress, balance);
73 // }
74
75 // let stringNum = "12"
76
Solidity // let toInt = parseInt(stringNum)
Ethereum Value Type Blockchain Technology Solidity Language
77
78 // 1 ether = 1,000,000,000,000,000,000 wei
79 // 1 ether = 1,000,000,000 gwei
80 }

Value Types.sol hosted with ❤ by GitHub view raw

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

https://medium.com/coinmonks/understanding-value-types-in-solidity-5caa1af846ef 9/10
2/12/23, 5:38 PM UNDERSTANDING VALUE TYPES IN SOLIDITY | by Sayrarh | Coinmonks | Medium

Open
Emails in
willapp
be sent to [email protected]. Not you? Get unlimited access

Get this newsletter


Search Medium

https://medium.com/coinmonks/understanding-value-types-in-solidity-5caa1af846ef 10/10
2/12/23, 5:40 PM Learn Solidity lesson 5. Uint, types and visibility. | by João Paulo Morais | Coinmonks | Medium

Published in Coinmonks

João Paulo Morais Follow

Jul 19, 2022 · 5 min read · Listen

Save

Learn Solidity lesson 5. Uint, types and visibility.

In the last lessons, we created a contract with only one state variable, of type string.
Let’s now create a new contract, with new state variables, of type (unsigned) integer.

In Remix, write the following code.

https://medium.com/coinmonks/learn-solidity-lesson-5-uint-types-and-visibility-fbebb221c311 1/9
2/12/23, 5:40 PM Learn Solidity lesson 5. Uint, types and visibility. | by João Paulo Morais | Coinmonks | Medium

pragma solidity ^0.8.7;


contract Sum {
uint x;
uint public y;
}

When saving the file, the contract will be compiled, but with a warning: once again,
the license has not been defined. Why does it happen? Every contract, when published
on the blockchain, is made public, so its source code can be audited (and possibly
copied). Therefore, it is recommended that the author include information about the
license to use the code.

Let’s add a license. The following sentence is included in the first line:

//SPDX-License-Identifier: MIT

Upon doing so, and compiling again, the warning will disappear. We defined the
license as MIT, but we could have also used undefined, or some other type of public or
private license. The difference between license types will not be studied in this course.

Visibility
Variables in Solidity have three types of visibility: public, private and internal. When
visibility is not explicitly declared, it is considered internal by the compiler. This is the
case for the variable x of the contract Sum.

As we have already seen, variables of type public make the compiler automatically
create a method to retrieve it, through a call. The same does not occur for private or
internal variables, as we can see in the image bellow, where only the variable y has an
associated method.

https://medium.com/coinmonks/learn-solidity-lesson-5-uint-types-and-visibility-fbebb221c311 2/9
2/12/23, 5:40 PM Learn Solidity lesson 5. Uint, types and visibility. | by João Paulo Morais | Coinmonks | Medium

The compiler creates getter methods only for public variables.

The difference between private and internal is a little more subtle, but important.
Internal variables are inherited by child contracts, while private variables are not.

Inheritance between contracts is a more advanced topic, but let me give you an
example. In the same contract file Sum.sol, let’s define a second contract, named Son,
as follows.

contract Son is Sum {


function setX(uint _x) public {
x = _x;
}
function getX() public view returns(uint) {
return x;
}
}

It has two functions, setX and getX, the first being responsible for changing the variable
x, while the second is responsible for returning the variable x. However, note that we
did not define, at any time, the variable x! It was defined by the contract Sum, of which
the contract Son is a child, through the statement ‘contract Son is Sum’.

Changing the variable x to private, the compiler will throw an error, as shown in the
figure bellow. Private variables are not inherited by the child contract.

https://medium.com/coinmonks/learn-solidity-lesson-5-uint-types-and-visibility-fbebb221c311 3/9
2/12/23, 5:40 PM Learn Solidity lesson 5. Uint, types and visibility. | by João Paulo Morais | Coinmonks | Medium

Private variables are not inherited by the child contract.

Constant and immutable


State variables can be declared as constant and immutable. Both cannot be changed
after initialization.

Constant variables must be initialized at the time of their declaration, while immutable
variables can be initialized in the constructor of the contract. The constructor is a
function that runs only at deploy time.

Let’s add a new variable to our contract, z, which will be constant. Among the state
variables, include the following line of code.

uint private constant z = 10;

Once declared, the variable z can no longer be changed. Technically speaking, we


cannot even say that z is a state variable, as the blockchain does not reserve a

https://medium.com/coinmonks/learn-solidity-lesson-5-uint-types-and-visibility-fbebb221c311 4/9
2/12/23, 5:40 PM Learn Solidity lesson 5. Uint, types and visibility. | by João Paulo Morais | Coinmonks | Medium

dedicated space for it in the database. Its value is written directly into the bytecode.

Declaring a constant variable without initializing it is prohibited and the compiler will
point out an error, as seen in the image bellow.

Constant variables must be initialized at declaration.

Immutable variables can be declared without being initialized, but they must be
initialized in the constructor. Lets do this. We start by declaring a new variable, w, to
be immutable.

uint private immutable w;

After that, we declare a constructor for the contract, using the function constructor, as
follows.

constructor() {
w = 20;
}

The contract so far, with no compiler error or warning, can be seen in the image
bellow.

https://medium.com/coinmonks/learn-solidity-lesson-5-uint-types-and-visibility-fbebb221c311 5/9
2/12/23, 5:40 PM Learn Solidity lesson 5. Uint, types and visibility. | by João Paulo Morais | Coinmonks | Medium

Constant and immutable variables cannot be changed after initialization.

Integer and unsigned integer


In Solidity, it is necessary to indicate the type of variable at the moment of its
declaration. In the contract Sum, we use the type uint, short for unsigned integer,
which represent positive integers. To represent both positive and negative integers,
there is also the type int.

Solidity has several types to represent integers and unsigned integers. For integers,
there are the following types: int8, int16, int24… up to int256, which is the same as int.
For unsigned integers, we have: uint8, uint16, uint24… up to uint256, which is the
same as uint. Note that the count occurs every 8, which is the size of the variable in
bits.

The type uint8, for instance, has 8 bits, or 1 Byte. This means that it accepts numbers
between 0 and 255. The type uint256, 32 Bytes, accepts numbers between 0 and 2²⁵⁶ —
1. If we try to assign an out-of-bounds value to a variable, the compiler will throw an
error.

For instance, if we try to assign the value 256 to a variable of type uint8, the compiler
will point out an error, as seen in the figure bellow.

https://medium.com/coinmonks/learn-solidity-lesson-5-uint-types-and-visibility-fbebb221c311 6/9
2/12/23, 5:40 PM Learn Solidity lesson 5. Uint, types and visibility. | by João Paulo Morais | Coinmonks | Medium

Variable of type uint8 accepts numbers between 0 and 255.

In addition to strings and integers, Solidity has other types. We can divide these types
into two classes: value type and reference type. The value type is the one whose
variable directly stores its value, while the reference type stores a reference to where
the assigned value is located.

Integers and unsigned integers are variables of type value. Strings are reference-type
variables. This is why the memory keyword is used when function arguments are
strings. This topic will be further explained in another lesson.

Let’s include a function that changes the value of the variable y in the contract. Include
the following code in the contract:

function setY(uint _y) public {


y = _y;
}

Note that it was not necessary to indicate that the argument _y of the function is in
memory (or elsewhere), as it is passed to the function by value, not by reference.

New to trading? Try crypto trading bots or copy trading

The contract so far, without compiler error or warning, can be seen in the image
bellow. In the next lesson, we will continue with it.

https://medium.com/coinmonks/learn-solidity-lesson-5-uint-types-and-visibility-fbebb221c311 7/9
2/12/23, 5:40 PM Learn Solidity lesson 5. Uint, types and visibility. | by João Paulo Morais | Coinmonks | Medium

The contract Sum, so far.

Thanks for reading!

Solidity Ethereum Blockchain

Enjoy the read? Reward the writer.Beta


Your tip will go to João Paulo Morais through a third-party platform of their choice, letting them know you appreciate
their story.

Give a tip

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.
Open in app Get unlimited access

https://medium.com/coinmonks/learn-solidity-lesson-5-uint-types-and-visibility-fbebb221c311 8/9
2/12/23, 5:40 PM Learn Solidity lesson 5. Uint, types and visibility. | by João Paulo Morais | Coinmonks | Medium

Emails will be sent to [email protected]. Not you?


Search Medium

Get this newsletter

https://medium.com/coinmonks/learn-solidity-lesson-5-uint-types-and-visibility-fbebb221c311 9/9
2/12/23, 5:42 PM Unit underflows and overflows — Ethereum solidity vulnerability | by HaloBlock Official | HaloBlock | Medium

Published in HaloBlock

HaloBlock Official Follow

Jul 9, 2018 · 4 min read · Listen

Save

Unit underflows and overflows — Ethereum


solidity vulnerability

Once smart contracts are deployed to the public network, they had better stay
immutable. Any update, such as bug fixes, needs to be adopted by all nodes. Also, the
https://medium.com/haloblock/unit-underflows-and-overflows-ethereum-solidity-vulnerability-39a39355c422 1/7
2/12/23, 5:42 PM Unit underflows and overflows — Ethereum solidity vulnerability | by HaloBlock Official | HaloBlock | Medium

older version of smart contracts needs to be rendered as invalid. This is known as a


“hard fork”. It requires all related nodes to update their protocols to the latest version.
Otherwise, the continual usage of old versions will cause protocol and data differences
than nodes that have been updated to the latest version. This can lead to significant
confusion and possible errors.

Therefore, smart contracts’ codes should be as clean as possible before they get
deployed to the public network, to avoid future hard forks. One of the most common
security pitfalls in smart contracts is the uint underflow/overflow, which could only be
fixed with a hard fork. The underflow/overflow issue could cause a catastrophic loss
for the crypto holder’s account, and make the crypto hacker rich effortlessly. In this
article, we will explain how unit overflows and underflows work in detail.

The uint overflow/underflow, also known as uint wrapping around, is an arithmetic


operation that produces a result that is larger than the maximum above for an N-bit
integer, or produces a result that is smaller than the minimum below for an N-bit
integer.

For instance, for a 2-bit unsigned integer, the maximum value it could express is “11”,
and the minimum is “00”. With “11 + 1”, for computers the outcome would be:

11
+ 1
— — — —
00

For any human calculation, the sum of the max 2-bit integer (99) and the minimal one
(01) should be 100. But, for the computer, the 3-bit outcome cascades the 2-bit uint, so
the left-most “1” is truncated to have only “00” as the final result (shown above).

How about the subtraction? The computer will calculate “00” minus “1” as below:

00

https://medium.com/haloblock/unit-underflows-and-overflows-ethereum-solidity-vulnerability-39a39355c422 2/7
2/12/23, 5:42 PM Unit underflows and overflows — Ethereum solidity vulnerability | by HaloBlock Official | HaloBlock | Medium

- 1
— — — —
11

Again, the negative sign is truncated, hence only “11” is left, making the MINIMUM
number to be MAXIMUM with only one subtraction.

Above examples are called the uint overflow and underflow, also named as integer
wrapping. They perform pretty much similar to the odometer:

“All digits are set to the maximum 9 and the next increment of the white digit causes a
cascade of carry-over additions setting all digits to 0, but there is no higher digit to
change to a 1, so the counter resets to zero. ”

https://medium.com/haloblock/unit-underflows-and-overflows-ethereum-solidity-vulnerability-39a39355c422 3/7
2/12/23, 5:42 PM Unit underflows and overflows — Ethereum solidity vulnerability | by HaloBlock Official | HaloBlock | Medium

- Wikipedia

In Solidity, crypto accounts have their balances defined as uint256 type, meaning that
any crypto hackers could flip their empty wallet to MAX value without any effort, and
any rich man could overflow their wallet with a simple transaction.

Try to subtract 0 to 2²⁵⁶-1, and 2²⁵⁶ — 1 to 0 in this Solidity script:

pragma solidity 0.4.24;

// Testing Uint256 underflow and overflow in Solidity

contract UintWrapping {
uint public zero = 0;
uint public max = 2**256-1;

// zero will end up at 2**256-1


function zeroMinus1() public {
zero -= 1;
}
// max will end up at 0
function maxPlus1() public {
max += 1;
}
}

https://medium.com/haloblock/unit-underflows-and-overflows-ethereum-solidity-vulnerability-39a39355c422 4/7
2/12/23, 5:42 PM Unit underflows and overflows — Ethereum solidity vulnerability | by HaloBlock Official | HaloBlock | Medium

Press “Compile” on the right -> “Deploy” -> Choose a random address “from Address” -
> “Deploy”, Call zero & max to check their initial values before calling any other
functions, then call zeroMinus1() and maxPlus1() sequentially. Then test zero & max to
see what happens.

In June 2017, OpenZepplin created the “SafeMath” library aiming to tackle the
underflow and overflow issues. They implemented safe addiction, subtraction,
division, and multiplication, by carefully comparing the operators and operands
before the operation. For instance, before running a.sub(b) as a — b, the function
would firstly assert to ensure b is smaller than a, then perform the subtraction.

https://medium.com/haloblock/unit-underflows-and-overflows-ethereum-solidity-vulnerability-39a39355c422 5/7
2/12/23, 5:42 PM Unit underflows and overflows — Ethereum solidity vulnerability | by HaloBlock Official | HaloBlock | Medium

pragma solidity 0.4.24;

// Testing safeMath library in Solidity

/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {

/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}

c = a * b;
assert(c / a == b);
return c;
}

/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}

/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {

Again, press “Compile” on the right -> “Deploy” the TestSafeMath column -> Choose a
random address “from Address” -> “Deploy”, Call zero & max to check their initial
values before calling any other functions, then call zeroMinus1Safe() and
maxPlus1Safe() sequentially. Then test zero & max to see what happens.

Pretty cool, right? However there are still uint wrapping cases that have not been taken
cared by developers, for instance, VenusADLAB published CVE-2018–13087, which is
about integer wrapping issue in MyAdvancedToken’s smart contract. In its mintToken()

https://medium.com/haloblock/unit-underflows-and-overflows-ethereum-solidity-vulnerability-39a39355c422 6/7
2/12/23, 5:42 PM Unit underflows and overflows — Ethereum solidity vulnerability | by HaloBlock Official | HaloBlock | Medium

function, anyone could deceive by minting negative amount of tokens in a zero-


balanced account, or minting a large number of tokens to overflow a rich account.

To fix this, assert(), SafeMath library, or require() functions should be adopted to pre-
check the operators and maybe rollback an illegal transaction.

Open in app Get unlimited access

Search Medium
Some of the auto-audit tools, like Mythril or Oyente, can also help accurately nail down
the Integer wrapping problems. We talked about how to install, deploy and install two
of the most popular security auditing tool, Mythril and Oyente in our previous blogs.
Please don’t forget to check them out before you publish your smart contracts.

By Yuan He, Security Researcher from HaloBlock.io

Ethereum Solidity Bugs Security Blog

https://medium.com/haloblock/unit-underflows-and-overflows-ethereum-solidity-vulnerability-39a39355c422 7/7
2/12/23, 5:44 PM Preventing Arithmetic Overflow and Underflow in Solidity: Best Practices and Solutions | by Hari Pandey | Coinmonks | Feb, 2023 …

Published in Coinmonks

Hari Pandey Follow

Feb 10 · 3 min read · Listen

Save

Preventing Arithmetic Overflow and Underflow


in Solidity: Best Practices and Solutions
Solidity is a high-level programming language that is used for developing smart
contracts on the Ethereum blockchain. It is a statically typed language, which means
that the type of a variable is known at compile-time. One of the most common errors
that developers encounter when working with Solidity is arithmetic overflow and
underflow.

https://medium.com/coinmonks/preventing-arithmetic-overflow-and-underflow-in-solidity-best-practices-and-solutions-bc06ea6da9fd 1/6
2/12/23, 5:44 PM Preventing Arithmetic Overflow and Underflow in Solidity: Best Practices and Solutions | by Hari Pandey | Coinmonks | Feb, 2023 …

Photo by Towfiqu barbhuiya on Unsplash

Arithmetic overflow occurs when the result of a mathematical operation exceeds the
maximum value that can be stored in a variable. For example, consider a uint256
variable that can store values between 0 and 2²⁵⁶ — 1. If we add 1 to the maximum
value that can be stored in a uint256, the result will be 0, which is called an overflow.

Arithmetic underflow, on the other hand, occurs when the result of a mathematical
operation is below the minimum value that can be stored in a variable. For example, if
we subtract 1 from 0, the result will be the maximum value that can be stored in a
uint256, which is called an underflow.

Both overflow and underflow can have serious consequences for smart contracts. For
instance, if a smart contract is programmed to transfer tokens from one account to
another and an overflow or underflow occurs, the tokens may be transferred to an
unintended recipient. This can result in security vulnerabilities and financial losses.

https://medium.com/coinmonks/preventing-arithmetic-overflow-and-underflow-in-solidity-best-practices-and-solutions-bc06ea6da9fd 2/6
2/12/23, 5:44 PM Preventing Arithmetic Overflow and Underflow in Solidity: Best Practices and Solutions | by Hari Pandey | Coinmonks | Feb, 2023 …

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.6;

contract Stake{

mapping(address =>uint256) public balances;


mapping (address =>uint256) public lockTime;

//user will not be able to transfer his fund for 15 days...


function deposit(uint256 _depositAmount) external payable{
balances[msg.sender]+=_depositAmount;
lockTime[msg.sender]=block.timestamp +15 days;
}
function increaseLockTime(uint256 _timeinsecond) external {

lockTime[msg.sender]=lockTime[msg.sender] + _timeinsecond;
}

function transferFund(address _to,uint256 _amount) external {


require(balances[msg.sender]>_amount,"insufficient funds !!");
require(block.timestamp >lockTime[msg.sender],"lock time not expired");
balances[_to]+=_amount;
balances[msg.sender]-=_amount;
}

Here, in the above code we can manipulate the locktime to make it Zero by calling
increaseLockTime function with a such value which can overflow that Arithmetic
value and make it zero.

You can deploy AttackStake Contract so that user will be able to transfer his fund
before his locking period ends.Here is the code :-

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.6;
import "./Stake.sol";

contract AttackStake {
Stake public stake;

constructor(Stake _stakeAddress) {
https://medium.com/coinmonks/preventing-arithmetic-overflow-and-underflow-in-solidity-best-practices-and-solutions-bc06ea6da9fd 3/6
2/12/23, 5:44 PM Preventing Arithmetic Overflow and Underflow in Solidity: Best Practices and Solutions | by Hari Pandey | Coinmonks | Feb, 2023 …

stake = Stake(_stakeAddress);
}
function attack(uint256 _depositAmount,address _to,uint256 _withdrawAwamount) pu
stake.deposit(_depositAmount);
stake.increaseLockTime(
type(uint).max + 1 - stake.lockTime(address(this))
);
stake.transferFund(_to,_withdrawAwamount);
}

Solution :
To avoid arithmetic overflow and underflow in Solidity, it is important to use the
appropriate data types and to write code that checks for overflow and underflow
before performing any arithmetic operations.

We can use SafeMath library, which is a collection of functions that perform arithmetic
operations and check for overflow and underflow. The SafeMath library is widely used
by Solidity developers and is considered to be a best practice for avoiding arithmetic
errors in smart contracts.

It does this by providing a set of functions that perform arithmetic operations, such as
addition, subtraction, multiplication, and division, and automatically check for
overflow and underflow before the operation is performed.

For example, when using the SafeMath library, if an addition operation would result in
an overflow, the function will throw an exception and stop the transaction from
executing. This helps to ensure that the intended arithmetic operation is performed
correctly and that the results are within the expected range.

To use SafeMath,you can import it in your contract, like this :

import "github.com/OpenZeppelin/zeppelin-solidity/contracts/math/SafeMath.sol";

https://medium.com/coinmonks/preventing-arithmetic-overflow-and-underflow-in-solidity-best-practices-and-solutions-bc06ea6da9fd 4/6
2/12/23, 5:44 PM Preventing Arithmetic Overflow and Underflow in Solidity: Best Practices and Solutions | by Hari Pandey | Coinmonks | Feb, 2023 …

and use this for your datatype, like this :

using SafeMath for uint256

Solidity 0.8 defaults to throwing an error for overflow / underflow but if you are
working with old solidity version, consider Using SafeMath library .

In conclusion,arithmetic overflow and underflow can have serious consequences for


smart contracts and it is important to take steps to prevent them. Developers should
use appropriate data types and perform checks for overflow and underflow before
performing any arithmetic operations. Additionally, the use of libraries such as
SafeMath can help to ensure that arithmetic errors are avoided. By following these best
practices, developers can help to ensure that their smart contracts are secure and
operate as intended.

New to trading? Try crypto trading bots or copy


trading on best crypto exchanges

Solidity Blockchain Blockchain Technology Solidity Tutorial Web 3


Open in app Get unlimited access

Search Medium

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

https://medium.com/coinmonks/preventing-arithmetic-overflow-and-underflow-in-solidity-best-practices-and-solutions-bc06ea6da9fd 5/6
2/12/23, 5:44 PM Preventing Arithmetic Overflow and Underflow in Solidity: Best Practices and Solutions | by Hari Pandey | Coinmonks | Feb, 2023 …

Get this newsletter

https://medium.com/coinmonks/preventing-arithmetic-overflow-and-underflow-in-solidity-best-practices-and-solutions-bc06ea6da9fd 6/6
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

Published in Coinmonks

Agoi Abel Follow

Apr 1, 2020 · 6 min read · Listen

Save

Arrays and Maps in Solidity

An array allows us to represent a collection of data, but


it is often more useful to think of an array as a
https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 1/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

collection of variables of the same type with keys


having sequential order based off the order they were
added.

Instead of declaring individual variables, such as number1, number2, number3, …..,


and number99, you can declare one array variable such as numbers and use
numbers[0], numbers[1], …, numbers[99] to represent individual variables.

Having understood how the array works in JAVASCRIPT and PHP, I was going to rush
through it in solidity but to my greatest surprise, it is quite different here in the solidity
blockchain world :). I decided to write about the array and map since both of them
seem similar to me and can be used together.

Unlike in javascript where we could have an array of integer together with strings or
any other data type, our array must have the variable of the same data type and this
can be enforced when declaring it like below:

uint[] myArray; //declaring an array of integer variables

Before I dive fully into the array in solidity, I want to clarify that there are two types of
arrays in solidity, which are the storage array and the memory array.

Wanna get published on Coinmonks, check here.

Storage Array:
These are arrays that are stored inside the blockchain after you execute your function,
you can declare them like normal variables without our contract like below:

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 2/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

1 pragma solidity ^0.5.3;


2
3 contract Array {
4 uint[] intergerArray; //sample showing initialization of an array of integers
5
6 bool[] boolArray; //sample showing initialization of an array of booleans
7
8 address[] addressArray; //sample showing initialization of an array of address etc.
9 }

array_map.sol hosted with ❤ by GitHub view raw

where unit/bool/address is the variable type, followed by [] and then the name of the
array which can be any name.

Manipulation of the storage array:

To add a new element to the array, we need to reference the array and use the
.push(value), we can also update an array position by referencing the element key like
myArray[0] = ‘new value’; , we also can also get a particular array element position by
simple using myArray[0] where 0 is the index or key of the array element

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 3/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

1 pragma solidity ^0.5.3;


2
3 contract{
4 uint[] myArray;
5
6 function manipulateArray() external {
7 myArray.push(1); // add an element to the array
8 myArray.push(3); // add another element to the array
9
10 myArray[0]; // get the element at key 0 or first element in the array
11 myArray[0] = 20; // update the first element in the array
12
13
14 //we can also get the element in the array using the for loop
15 for (uint j = 0; j < myArray.length; j++) {
16 myArray[j];
17 }
18 }
19
20 }
21
22
23

array_map_01.sol hosted with ❤ by GitHub view raw

We can also use the for loop to access the element of the array as we would array in
javascript (also in the snippet above). To delete an element in the array, we will use
delete myArray[1] where 1 is the array key, please note that this will not affect the
array length but will only reset the array value at the index of one or second element in
the array to the default value of the data type. i.e 0 if it’s a uint type and false if bool.
When we try to access an array key that does not exist, we will have an error.

Memory Array:
These arrays are not stored into the blockchain after calling the function, you can only
declare them within a function like below:

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 4/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

1 pragma solidity ^0.5.3;


2
3 contract MemoryArray {
4 /**
5 * These are temporary arrays and only exists when you are executing a function
6 * Must have a fixed size and must be declared inside a function
7 * You cannot run a for loop in a memory array
8 */
9 function memoryArray() public {
10 uint[] memory newArray = new uint[](10);
11 }
12 }

array_map_02.sol hosted with ❤ by GitHub view raw

where unit[] is the type of the variables, memory keyword declares it has a memory
array followed by the name which can be an acceptable name, it must be equated to
new unit[](10) type where the unit[] must be the variable type again and the number
of elements that will be in the array in the bracket () .

Manipulation of the memory array:

To add value to the memory array, we cannot use the .push() method, as we need to
use the index notation instead like newArray[0] = 1 , newArray[1] = 1 etc. We can read
a value, update a value, delete a value from the memory array just like the storage
array.

Passing an array as a function argument:

We can pass an array as a function argument in solidity, the function visibility


determines if the keyword before the array name should be calldata or memory . We

use calldata if the function visibility is external and memory if the function visibility is
public and internal. See example below:

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 5/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

1 pragma solidity ^0.5.3;


2
3 contract ArraySolidity {
4
5 /** Visible external */
6 function functionExternal(uint[] calldata myArg) external returns(uint[] memory) {
7 uint[] memory newArray = new uint[](10);
8
9 newArray[0] = 1;
10
11 return newArray;
12 }
13
14
15 /** Visible public */
16 function functionPublic(uint[] memory myArg) public returns(uint[] memory) {
17 uint[] memory newArray = new uint[](10);
18
19 newArray[0] = 1;
20
21 return newArray;
22 }
23
24 }

array_map_03.sol hosted with ❤ by GitHub view raw

Seems we have covered all we need to do in an array, how about mapping .

A Map is something like an array with a collection of


similar variables that uses key look-ups meaning
you’re referencing values with an object instead of an
integer in short.

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 6/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

Basically, mapping is equivalent to a dictionary or a map in other programming


languages. It’s key-to-value storage. A standard array is an index look-up e.g. if there
are 10 elements in the array the indexes are 0–9 and it would look like below as an
array of integers:

[0] 555
[1] 123
...
[8] 22
[9] 5

The map works slightly different and the easiest way to describe it is that it uses key
lookups. So if this was a map of addresses to integers then it would look something
like:

[0x000000000000000A] 555
[0x0000000000000004] 123
....
[0x0000000000000006] 22
[0x0000000000000003] 6

So basically, you’re referencing values with an object instead of an integer. The keys
also don’t have to be in sequence. It consists of two main parts: a _KeyType and a
_ValueType ; they appear in the following syntax below:

mapping (_KeyType => _ValueType) mapName .

Think of the _KeyType as the key you'll pass through a function to return the desired
value, or _ValueType . By default, a mapping is initially empty, so a new _KeyType will
first need to be mapped to a _ValueType .

It could be

mapping(string => string) mapName;

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 7/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

Or

mapping(int => bool) mapName;

Manipulation of a map:

We can manipulate a map within a function like below:

1 pragma solidity ^0.5.3;


2
3 contract Mapping {
4
5 mapping(address => uint) balances;
6
7 function manipulateMap() external {
8 balances[msg.sender] = 100; //assign a value;
9
10 balances[msg.sender] //read a value;
11
12 balances[unknown_key] //will return the default value of the type, i.e 0
13 }
14
15 }

gistfile1.txt hosted with ❤ by GitHub view raw

We assigned a value to the map here balances[msg.sender] = 100 by equating it to a


value. We read the value also by balances[msg.sender] without assigning any value.
When we use a non-existence key to read a value from a map, it will return the default
data value used to initialize the value type when declaring it unlike undefined in
javascript.

Assign an array as a map value:

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 8/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

We can assign an array as a value type to a map and can access them as we would an
array like below:

1 pragma solidity ^0.5.3;


2
3 contract Mapping {
4
5 mapping(address => uint[]) scores;
6
7 function manipulateArrayMap() external {
8 scores[msg.sender].push(1); //assign a value;
9 scores[msg.sender].push(2); //assign another element
10
11 scores[msg.sender][0]; //access the element in the map array
12
13 scores[msg.sender][1] = 5; //update an element in the map array in index 1
14
15 delete scores[msg.sender][0]; //delete the element in the index 0 of the map arr
16 }
17
18 }
19

array_map_04.sol hosted with ❤ by GitHub view raw

Assign another map as a map value:

We can also assign another map as a map value and can access them as we would
access a map like below:

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 9/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

1 pragma solidity ^0.5.3;


2
3 contract Mapping {
4
5 mapping(address => uint) balances;
6 mapping(address => mapping(address => bool)) approved;
7
8 function manipulateMapOfMap(spender) external {
9 approved[msg.sender][spender] = true //assign a value to the approved
10 approved[msg.sender][spender]; //get the value of the map
11
12 delete approved[msg.sender][spender] //delete the reference
13 }
14
15 }

array_map_05.sol hosted with ❤ by GitHub view raw

We can assign a Struct as a map value type too, there are occasions when you want to
iterate over a map and do other things on a map, I would advise you check out the
resources below when the need arises:

How to loop through mapping in solidity?


Thanks for contributing an answer to Ethereum Stack Exchange! Please
be sure to answer the question. Provide details…
ethereum.stackexchange.com

Soldity: Iterate through address mapping


If you want something more general, you can use a library. I've included
one I'm using below. It could probably use…
stackoverflow.com

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 10/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

how mapping works in solidity, and is mapping analogous to another


concept in other popular…
Thanks for contributing an answer to Stack Overflow! Please be sure to
answer the question. Provide details and share…
stackoverflow.com

If you got this far, you are cute, thank you for reading.

Join Coinmonks Telegram Channel and Youtube


Channel get daily Crypto News
Also, Read
Copy Trading | Crypto Tax Software

Grid Trading | Crypto Hardware Wallet

Best Crypto Exchange | Best Crypto Exchange in India

Best Crypto APIs for Developers

Crypto Telegram Signals | Crypto Trading Bot

Best Crypto Lending Platform

An ultimate guide to Leveraged Token

Best VPNs for Crypto Trading

Crypto Trading Signals for Huobi | HitBTC Review

TraderWagon Review | Kraken vs Gemini vs BitYard

How to trade Futures on FTX Exchange

OKEx vs KuCoin | Celsius Alternatives | How to Buy VeChain

3Commas vs. Pionex vs. Cryptohopper

How to use Cornix Trading Bot


Open in app Get unlimited access

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 11/12
2/12/23, 5:46 PM Arrays and Maps in Solidity. An array allows us to represent a… | by Agoi Abel | Coinmonks | Medium

Bitget Review | Gemini vs BlockFi cmd| OKEx Futures Trading


Search Medium
10 Best Places to Buy Crypto with Credit Card

Ethereum Solidity Beginner Blockchain Blockchain Development

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/coinmonks/array-and-map-in-solidity-a579b311d74b 12/12
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Jean Cvllr Follow

Dec 25, 2019 · 10 min read · · Listen

Save

Solidity Tutorial: all about Array

In Solidity, an array is an ordered list of items that is indexed numerically, starting at


0.
https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 1/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

Array types
In this section, we provide two types of categorisation for arrays:

Fixed-size vs dynamic size arrays

One-dimensional vs Multi-Dimensional arrays.

Fixed-size vs Dynamic-Size array


The Solidity documentation make the distinction between fixed-size and dynamic size
arrays. In the examples below, T is the element type and k is the array length / size. If
k = 5 , the array can hold a maximum of 5 values.

Fixed Size: T[k]

// array that can hold 5 unsigned integers maximum


uint[5] my_array;

Dynamic Size: T[]

// array containing an undefined number of strings


string[] my_array;

One Dimensional vs Multi-Dimensional arrays


One Dimensional and Multi-Dimensional arrays can be both of Fixed-Size or Dynamic-
Size. The One Dimensional arrays are essentially the examples cited above. Here are
the definitions

T[k] : One Dimensional, Fixed-size

T[] : One Dimensional, Dynamic-size

Multi-dimensional arrays are essentially nested arrays (An array that contain other
arrays). These however, come in three forms in Solidity. We use two-dimensional array
in this first example…
https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 2/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

T[k][k] : Two-Dimensional, Fixed-size

T[][] : Two-Dimensional, Dynamic-size

T[][k] or T[k][] : Two-Dimensional, Mixed-size

… but you will see that multi-dimensional arrays can have any level of nesting ! Here
are some examples.

T[2][2][2] : Three-Dimensional, Fixed-Size (all k are the same)

T[2][8][4][12] : Four-Dimensional, Fixed-Sizes ( k ‘s are of different values)

T[][][][][] : Five-Dimensional, Dynamic-Size

T[][3][2][][9][] : Six-Dimensional, Mixed-Size

The idea here is to demonstrate that arrays can be nested and become really complex.
As you can see, dynamic-size and fixed-size can be mixed in a nested array. However,
two important notes about nested array must be mentioned.

You cannot have different types within nested arrays

The maximum level of nesting for nested arrays is 15. If you try to create a variable with
16 nested arrays, you will get a ‘stack too deep’ error. This is because the stack pointer in
the EVM cannot access a slot in the stack that is deeper than is 16th element (counting from
the top downwards). Try pasting these codes snippets below on Remix and you will see the
error:

// 15 level of nesting : OK works


uint[][][][][][][][][][][][][][][] public nesting_limit;
// 'Stack too deep' error
uint[][][][][][][][][][][][][][][][] public over_limit;

How to define arrays ?

https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 3/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

Defining One-Dimensional arrays


You define a one-dimensional array in Solidity by specifying the variable T followed
by square brackets [] . If it’s a fixed size array, you must specify the maximum
number of elements between the [] .

// (One-Dimensional array, fixed size)


// Name of players in a 4 players online game room
string[4] players_room;

//(One-Dimensional array, Dynamic Size)


// Names of people who have voted
string[] have_voted;

Defining Two-Dimensional arrays

In Solidity, the notation of multidimensional array is reversed ONLY WHEN DEFINING


compared to other programming languages.

For this case, we are going to compare 2 arrays

string[2][] crypto_names;
string[][6] names_A_to_F;

In the first example crypto_names , we have a dynamic array outright, but its elements
are arrays of fixed size (2). In the second case, names_A_to_F is a fixed-size array which
has 6 elements, each of which is a dynamic array

Let’s see with the a first example:

string[2][] crypto_names;

In the example above, the fixed-size 2 refers to the second level of nesting, not the
first.
https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 4/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

pragma solidity ^0.5.0;


contract CryptoNames {
string[2][] public crypto_names;

constructor() public {
crypto_names.push([“Alice”, “Bob”]); // generic characters
crypto_names.push([“Carol”, “Dave”]); // 3rd and 4th party
crypto_names.push([“Eve”, “Frank”]); // Bad guys
crypto_names.push([“Grace”, “Heidi”]); // others
}
}

The variable crypto_names can hold an unlimited number of arrays, but each of these
arrays can hold a maximum of 2 values. If we try to push an array with 3 names (see
function below), we will get an error in Remix.

function invalidPush() public {


crypto_names.push(["Ivan", "Judy", "Mallory"]);
}
// Error in Remix :
/*
Invalid type for argument in function call. Invalid implicit
conversion from string memory[3] memory to string storage ref[2]
storage ref requested.
crypto_names.push(["Ivan", "Judy", "Mallory"]);
^-------------------------^
*/

To get an abstract overview, the array crypto_names would like this in PHP :

// In PHP code
$crypto_names = array(
0 => array(
0 => "Alice",
1 => "Bob",
// No more values allowed !
https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 5/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

),
1 => array(
0 => "Carol",
1 => "Dave",
// No more values allowed !
),
2 => array(
0 => "Eve",
1 => "Frank",
// No more values allowed !
),
3 => array(
0 => "Grace",
1 => "Heidi",
// No more values allowed !
),
// ... etc (can add more values)
);

Let’s now look at the opposite example, where the fixed size is given on the other way
around.

string[][6] names_A_to_F;

In this example, let’s consider that we want to hold a list of names, listed by
alphabetical order, from the letter A to the letter F. So the index 0 contains names
starting in A , index 1 contains names starting in B , up to names_alphabet[5] , which
will contain an array of names starting in F ( F is the 7th letter of the alphabet, but
since array’s indexes start at zero, the index will be 7 — 1 = 6 ).

Let’s look at the implementation.

pragma solidity ^0.5.0;


contract NamesAlphabet {

https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 6/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

string[][6] public names_A_to_F;

constructor() public {
names_A_to_F[0] = ["Alice"];
names_A_to_F[1] = ["Bob"];
names_A_to_F[2] = ["Carol", "Carlos", "Charlie", "Chuck",
"Craig"];
names_A_to_F[3] = ["Dan", "Dave", "David"];
names_A_to_F[4] = ["Erin", "Eve"];
}
}

There are two things to note:

1. Each indexes contain various number of values.

Index 0 and 1 (letters A and B) contain only one name each.

Index 2 (letter C) contain five names.

Index 3 (letter D) contain three names.

Index 4 (letter E) contain two names each.

2. Names are added by index access ( names_A_to_F[index] = ["value1", "value2", ...]

) rather than using the .push(value1, value2, ...) ) used previously.

You cannot use the .push method in an array that has a fixed length. You must specify
the index.

function addNamesF() public {


names_A_to_F[5] = ["Faythe", "Frank"];
}

function notWorking() public {


names_A_to_F.push(["Faythe", "Frank"]);
}

// Solidity error:
/*

https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 7/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

TypeError: Member "push" not found or not visible after argument-


dependent lookup in string storage ref[] storage ref[26] storage ref.
names_A_to_F.push(["Faythe", "Frank"]);
^---------------^
*/

3. Finally, you cannot add names starting in G ( So a 7th array at the 6th index), since
your variable is defined to hold no more than 6 arrays ( string[][6] names_A_to_F ).
Copy and paste the code snippet below on Remix and you will see the following error:

function addNamesG() public {


names_A_to_F[6] = ["Grace"];
}
// Error in Remix:
/*
TypeError: Out of bounds array access.
names_A_to_F[6] = ["Grace"];
^-------------^
*/

To get an abstract overview, the array names_A_to_F would like this in PHP :

// In PHP code
$names_A_to_F = array(
0 => array(
0 => "Alice"
// etc... (can add more values)
),
1 => array(
0 => "Bob"
// etc... (can add more values)
),
2 => array(
0 => "Carol",
0 => "Carlos",
0 => "Charlie",
0 => "Chuck",
0 => "Craig",
https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 8/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

// etc... (can add more values)


),
3 => array(
0 => "Dan",
0 => "Dave",
0 => "David",
// etc... (can add more values)
),
4 => array(
0 => "Erin",
0 => "Eve",
// etc... (can add more values)
),
5 => array(
0 => "Faythe",
0 => "Frank",
// etc... (can add more values)
),
// No more values allowed !
);

Access elements within Fixed and Dynamic size arrays.


Like many other programming languages, you must specify the index between the
square brackets.

Access elements within multi-dimensional arrays.


As opposed to the array definition where the notation is reversed, array access is in the
right to left order. Indices are always zero base.

To go back to our names_A_to_F example:

pragma solidity ^0.5.0;


contract NamesAlphabet {

string[][6] public names_A_to_F;

constructor() public {
names_A_to_F[0] = ["Alice"];
names_A_to_F[1] = ["Bob"];
names_A_to_F[2] = ["Carol", "Carlos", "Charlie", "Chuck",
"Craig"];
names_A_to_F[3] = ["Dan", "Dave", "David"];
https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 9/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

names_A_to_F[4] = ["Erin", "Eve"];


}

function getAliceName() public view returns (string memory) {


return names_A_to_F[0][0];
}

function getBobName() public view returns (string memory) {


return names_A_to_F[1][0];
}

function getEveName() public view returns (string memory) {


return names_A_to_F[4][1];
}

function getChuckName() public view returns(string memory) {


return names_A_to_F[2][3];
}

Arrays literals (inline arrays)


Arrays literals are arrays written like an expression. They do not get assigned to a
variable right away.

Array literals can only be of fixed-size. You declare them with the syntax below. Note
that the first value in the array declaration has to be type casted ( type(value_1 ).

// Here if k = 5, the array will contain 5 values.


T[k] memory array_literal = [type(value_1), value_2, ... , value_k];
// example
string[3] memory rgb_colours = [string("red"), "green", "blue"];

Here is another example of inline arrays.

// Base type (common types of the given elements)


// Here the type would be uint8[3]

https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 10/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

function func1() {

// Conversion of the 1st element to uint256 is necessary because


// the type of every constant memory is uint8 by default.
func2([uint(1), 2, 3]);
}
// memory type array that has a fixed size (uint3)
function func2(uint[3] _data) {

// Some code here


}

Memory Arrays inside functions


A memory array is an array created within a function. Because it is part of the
memory, it is not persistent, so the array is erased after the function has executed. To
create a a memory array, use the new keyword.

function memoryArray(uint len) {

// memory array of length 7, containing uint


// x.length == 7
uint[] memory x = new uint[](7);

// memory array of length `len`, containing bytes


// y.length == len
bytes[] memory y = new bytes(len);
}

An example of a memory array would be an array that contains x prime numbers that
you want to reduce (cumulate).

function reduceArray(uint _length) public pure returns (uint) {

uint[] memory _array = new uint[](_length);


uint cumul;
uint value = 2;

for (uint i = 0; i < _array.length; i++ ) {


https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 11/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

_array[i] = value;
cumul += _array[i];
value += 2;
}
return cumul;
}

Note that you can’t assign a fixed-size memory array to a dynamic size memory array.
To illustrate, here is an example that would not compile.

function dontCompile() public {


uint[] memory x = [uint(1), 3, 4];
}
// Remix Error:
/*
TypeError: Type uint256[3] memory is not implicitly convertible to
expected type uint256[] memory.
uint[] memory x = [uint(1), 3, 4];
^-------------------------------^
*/

Note that you can’t change the size of memory arrays by assigning values to the member
.length . You can only change the .length of an array if it is refered as storage .

Reference type members of Arrays


There are two built-in functions that you can use on arrays in Solidity. These methods
are also common to other programming languages that use arrays.

.length can be used to:

return the number of elements contained in an array.

resize a dynamic size array ( T[] ) in storage only.

As mentioned before, only dynamic sized arrays that are referenced in the contract’s
storage can be resized.
https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 12/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

Memory arrays cannot be resized by modifying their length member, because their
length is fixed once created. The Solidity documentation provides the following
explanation:

This would not happen automatically when trying to


access elements external to the current length. The
memory array size is fixed (but dynamic, as it can
depend on the runtime parameter) once they are
created.
.push(new_element) , when executed:

append a new element at the end of the array

returns the new length of the array.

This member function is only available for dynamic sized arrays and bytes.

Note: you can’t use push to append a new element to a string

Array as return values in functions


Solidity enables you to create functions that return arrays (both fixed and dynamic
size). Since we make the distinction between three types of arrays (one-dimensional,
two-dimensional and multi-dimensional), we will present how Solidity can return
these three different types of arrays via functions.

If an array is returned by a function, the data location specified always have to be


memory .

NB: you cannot return an array of mappings in Solidity.

https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 13/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

Return one-dimensional arrays


Here is a simple example that return a fixed-size array of all the one digit numbers
(The array here is an array literal, as described previously).

function returnOneDigitNumbers() public pure returns (uint[9] memory)


{
return [uint(1), 2, 3, 4, 5, 6, 7, 8, 9];
}

To continue in our example of crypto_names , let’s imagine a dynamic-size array


(growable) that contains the addresses of some famous cryptographers. You can simply
return a dynamic array by specifying returns (type[] memory) in your function
definition. A picture is worth thousand words.

address[] cryptographer_addresses;

function addCryptographerAddress(address _address) public {


cryptographer_addresses.push(_address);
}

function getAllCryptographersAddresses() public view returns


(address[] memory) {
return cryptographer_addresses;
}

To see it in action, copy / paste the code below in Remix, deploy the contract, add few
addresses to the list via the function addCryptographerAddress() and then click on
getAllCryptographerAddresses (in blue on the left sidebar). You should see the
following.

https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 14/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

After adding several address to the array list. Addresses are separated in the decoded output by commas.

The table below summarizes the different value types for one-dimensional arrays that
can be returned.

What you can’t do in Arrays with Solidity ?


It is not possible to use arrays of arrays within external functions.

https://ethereum.stackexchange.com/questions/11870/create-a-two-dimensional-
array-in-solidity

Programming

About Help Terms Privacy

Open in app
Get the Medium app Sign up Sign In

Search Medium

https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 15/16
2/12/23, 5:49 PM Solidity Tutorial: all about Array | by Jean Cvllr | Medium

https://jeancvllr.medium.com/solidity-tutorial-all-about-array-efdff4613694 16/16
2/12/23, 5:52 PM Solidity : How to use arrays?. An array can have a fixed size at… | by Bruno Delb | Crypto DevOps Academy | Medium

Published in Crypto DevOps Academy

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Bruno Delb Follow

Jul 5, 2022 · 5 min read · · Listen

Save

Solidity : How to use arrays?


An array can have a fixed size at compile time or a dynamic size.

An array can contain different types of elements.

The bytes and string arrays


Variables of type bytes and string are special arrays:

bytes is similar to bytes1[] but in calldata and memory ;

string is similar to bytes but does not provide length and index.

bytes is cheaper than bytes1[] .

bytes1 , …, bytes32 is recommended if the array size is known.

To concatenate an array, use .concat :

bytes.concat
string.concat

https://medium.com/cryptodevopsacademy/solidity-the-arrays-3bed66eeee4b 1/9
2/12/23, 5:52 PM Solidity : How to use arrays?. An array can have a fixed size at… | by Bruno Delb | Crypto DevOps Academy | Medium

The fixed-size arrays


To declare a fixed-size array, specify the type of elements and the number of elements
required: <type> <array-name> [ <array-size> ]; . This is a one-dimensional array.

Example:

uint balance[10];

To declare an array of dynamic size, specify the type of elements: <type>[] <array-

name>; .

To initialize arrays :

uint balance[3] = [1, 2, 3];

[3] specifies the number of values.

If the size of the array is not specified, an array of the right size is created to hold the
initialization:

uint balance[] = [1, 2, 3];

To assign a specific element of an array :

balance[2] = 5;

The dynamic size arrays


To create a memory array of dynamic size, use new :

https://medium.com/cryptodevopsacademy/solidity-the-arrays-3bed66eeee4b 2/9
2/12/23, 5:52 PM Solidity : How to use arrays?. An array can have a fixed size at… | by Bruno Delb | Crypto DevOps Academy | Medium

uint size = 3;
uint[] memory a = new uint[](size);
bytes memory b = new bytes(size);

This type of array cannot be resized with .push or .pop as with storage arrays.

Arrays literals
You can define an array using what is called an array literal:

uint[3] data = [uint(1), 2, 3];

The type of the array is the type of the first element: the conversion must be explicit.
But for the other elements, the conversion can be implicit. By default, the type of 1 is
uint8 . So a conversion must be done.

To access an element of an array, index the name of the array:

uint salary = balance[2];

Members of the arrays


.length is used to obtain the size of an array.

uint[6] data;
data = [uint(10), 20, 30, 40, 50, 60];
uint x = data.length;

.push() allows to add an element initialized to zero at the end of an array of dynamic
size and bytes. It returns a reference to the element. The latter can then be
manipulated.

https://medium.com/cryptodevopsacademy/solidity-the-arrays-3bed66eeee4b 3/9
2/12/23, 5:52 PM Solidity : How to use arrays?. An array can have a fixed size at… | by Bruno Delb | Crypto DevOps Academy | Medium

data.push(60);

.push(x) adds an element initialized to zero at the end of an array of dynamic size and
bytes .

.pop() allows to remove an element from the end of an array of dynamic size and
bytes . It implicitly calls .delete on the removed element.

uint[] data = [10, 20, 30, 40, 50];


data.pop();

It is also possible to access a portion of a calldata array with the syntax


myArray[<start>:<end>] :

bytes4 sig = bytes4(payload[:4]);

Examples of arrays

Example of an array stored in storage


Here is an example of a contract that manipulates a fixed length array of type storage :

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract MyContract {
uint[] data;
function fixedStorage() public returns (uint) {
data.push(10);
data.push(20);
data.push(30);
data.pop();
uint value2 = data[0];
data[0] = 30;
delete data[1];
uint total = 0;
https://medium.com/cryptodevopsacademy/solidity-the-arrays-3bed66eeee4b 4/9
2/12/23, 5:52 PM Solidity : How to use arrays?. An array can have a fixed size at… | by Bruno Delb | Crypto DevOps Academy | Medium

for(uint i = 0; i < data.length; i++) {


total += data[i];
}
return total;
}
}

The fixedArrayStorage() function performs the following operations:

Adds elements 10, 20 and 30;

Delete the last element, 30;

Change the value of the first element to 30;

Delete the second element of the array;

Calculate the total, which is 30, since there is only the first element, which is 30,
left.

Let’s check all this by compiling and redeploying the contract :

Let’s display the content of the data array:

The result of the function is 30.

Example of an array stored in memory


Here is an example of a function that manipulates a fixed length array of type memory :
https://medium.com/cryptodevopsacademy/solidity-the-arrays-3bed66eeee4b 5/9
2/12/23, 5:52 PM Solidity : How to use arrays?. An array can have a fixed size at… | by Bruno Delb | Crypto DevOps Academy | Medium

function fixedMemory() public pure {


int[3] memory data2;
data2 = [int(10), 20, 30];
uint[] memory data3 = new uint[](3);
data3[3] = 10;
data3[4] = 20;
data3[5] = 30;
}

Let’s compile and deploy this contract. Then execute the fixedArrayMemory() function:

This function performs the following operations:

Creation of an array data2 of three elements containing the values 10, 20 and 30;

Creation of an array data3 of three elements containing the same values but with
another syntax.

Example of a fixed size byte array


Solidity provides arrays of bytes from 1 to 32 bytes: bytes1 , bytes2 , …, bytes32 .

To create an array of three elements for example :

uint[3] memory data2 = [uint(10), 20, 30];

To modify an element of the array:

data2[0] = 10;

The .length member is used to obtain the size of this array:

https://medium.com/cryptodevopsacademy/solidity-the-arrays-3bed66eeee4b 6/9
2/12/23, 5:52 PM Solidity : How to use arrays?. An array can have a fixed size at… | by Bruno Delb | Crypto DevOps Academy | Medium

uint len = data2.length;

Example:

function bytesFixed() public pure returns (uint) {


uint[3] memory data2 = [uint(10), 20, 30];
data2[0] = 15;
uint len = data2.length;
return len;
}

Here is the result of the execution of this function:

Example of a dynamic size array of bytes


Solidity also provides dynamic arrays of bytes.

To create an array of size specified by a variable :

uint len = 3;
uint[] memory data2 = new uint[](_len);

To get the size of an array of dynamic size, use .length :

uint len = data2.length;

Here is an example:

https://medium.com/cryptodevopsacademy/solidity-the-arrays-3bed66eeee4b 7/9
2/12/23, 5:52 PM Solidity : How to use arrays?. An array can have a fixed size at… | by Bruno Delb | Crypto DevOps Academy | Medium

function bytesDynamic(uint _len) public pure returns (uint) {


uint[] memory data2 = new uint[](_len);
data2[0] = 10;
data2[1] = 20;
data2[2] = 30;
delete data2[2];
uint len = data2.length;
return len;
}

The result of calling the bytesDynamic(2) function is :

Solidity Blockchain Development Ethereum

Get an email whenever Bruno Delb publishes.

Your email

Subscribe

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

https://medium.com/cryptodevopsacademy/solidity-the-arrays-3bed66eeee4b 8/9
2/12/23, 5:52 PM Solidity : How to use arrays?. An array can have a fixed size at… | by Bruno Delb | Crypto DevOps Academy | Medium

About Help Terms Privacy

Get the Medium app

Open in app Sign up Sign In

Search Medium

https://medium.com/cryptodevopsacademy/solidity-the-arrays-3bed66eeee4b 9/9
2/12/23, 5:53 PM Dynamic Arrays and its Operations in Solidity - GeeksforGeeks

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+

Dynamic Arrays and its Operations in Solidity


Last Updated : 17 Nov, 2020

Read Discuss Courses Practice Video

The Dynamic arrays are the arrays that are allocated memor y at the runtime and the

memor y is allocated from the heap. 

Syntax :

// declaration of dynamic array

 int[] private arr;   

How They Are Different From Fixed Size Arrays?

Start Your Coding Journey Now!


The fixed-size array has a fixed memor y size whereas, in dynamic arrays, the size can be

Login Register
randomly updated during the run time which may be considered efficient with respect to

https://www.geeksforgeeks.org/dynamic-arrays-and-its-operations-in-solidity/ 1/9
2/12/23, 5:53 PM Dynamic Arrays and its Operations in Solidity - GeeksforGeeks

the memor y complexity of the code. 

Problem: How to create a dynamic array in solidity and per form its associated

operations?

Solution: In this ar ticle, we will create dynamic arrays in solidity language and will

per form the following operations on it:

1. Add data in an array

2. Get data of an array

3. Get length of an array

4. Get sum of elements of an array

5. Search a par ticular element in an array

What is Solidity?

Solidity is a high-level language. The structure of smar t contracts in solidity is ver y

similar to the structure of classes in object-oriented languages. The solidity file has an

extension .sol.

What are Smar t Contracts?

Solidity ’s code is encapsulated in contracts which means a contract in Solidity is a

collection of code (its functions) and data (its state) that resides at a specific address on

the Ethereum blockchain. A contract is a fundamental block of building an application on

Ethereum.

Start Your Coding Journey Now!


Step 1: Open Remix-IDE.

https://www.geeksforgeeks.org/dynamic-arrays-and-its-operations-in-solidity/ 2/9
2/12/23, 5:53 PM Dynamic Arrays and its Operations in Solidity - GeeksforGeeks

Step 2: Select File Explorer from the lef t side icons and select Solidity in the

environment. Click on the New option below the Solidity environment. Enter the file

name as dynamicArray.sol and Click on the OK button.

Step 3: Enter the following Solidity Code. Select the same solidity version as in your

code.

Solidity

// Solidity program to demonstrate


// the above approach
pragma solidity ^0.6.8;
contract DynamicArray{
    
// Declaring state variable  
int[] private arr; 
      
// Function to add data 
// in dynamic array
function addData(int num) public
{
  arr.push(num);
}
      
// Function to get data of
// dynamic array
function getData() public view returns(int[] memory)
{

Start Your Coding Journey Now!


  return arr;
}
https://www.geeksforgeeks.org/dynamic-arrays-and-its-operations-in-solidity/ 3/9
2/12/23, 5:53 PM Dynamic Arrays and its Operations in Solidity - GeeksforGeeks

      
// Function to return length 
// of dynamic array
function getLength() public view returns (uint)
{
  return arr.length;
}
  
// Function to return sum of 
// elements of dynamic array
function getSum() public view returns(int)
{
  uint i;
  int sum = 0;
    
  for(i = 0; i < arr.length; i++)
    sum = sum + arr[i];
  return sum;
}
      
// Function to search an 
// element in dynamic array
function search(int num) public view returns(bool)
{
  uint i;
    
  for(i = 0; i < arr.length; i++)
  {
    if(arr[i] == num)
    {
      return true;
    }
  }
    
  if(i >= arr.length)
    return false;
}
}

Step 4: Compile the file dynamicArray.sol from the Solidity Compiler tab.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/dynamic-arrays-and-its-operations-in-solidity/ 4/9
2/12/23, 5:53 PM Dynamic Arrays and its Operations in Solidity - GeeksforGeeks

Step 5: Deploy the smar t contract from the Deploy and Run Transaction tab.

Step 6: Per form various operations on the array under the deployed contracts section.

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/dynamic-arrays-and-its-operations-in-solidity/ 5/9
2/12/23, 5:53 PM Dynamic Arrays and its Operations in Solidity - GeeksforGeeks

Like 3

Previous Next

Related Articles

1. Mathematical Operations in Solidity

2. Solidity - Arrays

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/dynamic-arrays-and-its-operations-in-solidity/ 6/9
2/12/23, 5:53 PM Dynamic Arrays and its Operations in Solidity - GeeksforGeeks

3. Solidity - View and Pure Functions

4. Solidity - While, Do-While, and For Loop

5. Solidity - Break and Continue Statements

6. Solidity - Enums and Structs

7. Creating a Smart Contract that Returns Address and Balance of Owner using
Solidity

8. Introduction to Bytecode and Opcode in Solidity

9. Difference Between this and address(this) in Solidity

10. Solidity - Types

Ar ticle Contributed By :

muskan02
@muskan02

Vote for difficulty

Easy Normal Medium Hard Expert

Article Tags : Solidity-Arrays, Technical Scripter 2020, Solidity, Technical Scripter

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/dynamic-arrays-and-its-operations-in-solidity/ 7/9
2/12/23, 5:53 PM Dynamic Arrays and its Operations in Solidity - GeeksforGeeks

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Advertise with us Video Tutorials
Courses

News Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Start Your
WebCoding Journey Now!
Development Contribute
https://www.geeksforgeeks.org/dynamic-arrays-and-its-operations-in-solidity/ 8/9
2/12/23, 5:53 PM Dynamic Arrays and its Operations in Solidity - GeeksforGeeks

Web Tutorials Write an Article


Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/dynamic-arrays-and-its-operations-in-solidity/ 9/9
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+

Solidity – Arrays
Difficulty Level : Easy ● Last Updated : 11 May, 2022

Read Discuss Courses Practice Video

Arrays are data structures that store the fixed collection of elements of the same data

types in which each and ever y element has a specific location called index. Instead of

creating numerous individual variables of the same type, we just declare one array of the

required size and store the elements in the array and can be accessed using the index. In

Solidity, an array can be of fixed size or dynamic size. Arrays have a continuous memor y

location, where the lowest index corresponds to the first element while the highest

represents the last

Creating an Array

To declare an array in Solidity, the data type of the elements and the number of elements

should be specified. The size of the array must be a positive integer and data type should

be a valid Solidity type

Syntax :

<data type> <array name>[size] = <initialization>

Fixed-size Arrays

The size of the array should be predefined. The total number of elements should not

exceed the size of the array. If the size of the array is not specified then the array of

Start Your Coding Journey Now!


enough size is created which is enough to hold the initialization.

Login Register
https://www.geeksforgeeks.org/solidity-arrays/ 1/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

Example : In the below example, the contract Types are created to demonstrate how to

declare and initialize fixed-size arrays.

Solidity

// Solidity program to demonstrate 


// creating a fixed-size array 
pragma solidity ^0.5.0;  
  
// Creating a contract 
contract Types {  
  
    // Declaring state variables
    // of type array
    uint[6] data1;    
      
    // Defining function to add 
    // values to an array 
    function array_example() public returns (
    int[5] memory, uint[6] memory){  
            
        int[5] memory data 
        = [int(50), -63, 77, -28, 90];  
        data1 
        = [uint(10), 20, 30, 40, 50, 60];
            
        return (data, data1);  
  }  
}

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-arrays/ 2/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

Output : 

Dynamic Array: 

The size of the array is not predefined when it is declared. A s the elements are added the

size of array changes and at the runtime, the size of the array will be determined.

Example : In the below example, the contract Types are created to demonstrate how to

create and initialize dynamic arrays.

Solidity

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-arrays/ 3/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

// Solidity program to demonstrate 


// creating a dynamic array
pragma solidity ^0.5.0;  
  
// Creating a contract  
contract Types {  
    
    // Declaring state variable 
    // of type array. One is fixed-size
    // and the other is dynamic array
    uint[] data 
      = [10, 20, 30, 40, 50]; 
    int[] data1;  
    
    // Defining function to 
    // assign values to dynamic array
    function dynamic_array() public returns(
      uint[] memory, int[] memory){  
    
        data1 
          = [int(-60), 70, -80, 90, -100, -120, 140]; 
        return (data, data1);  
    }  
}

Output : 

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-arrays/ 4/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

Array Operations

1. Accessing Array Elements : The elements of the array are accessed by using the

index. If you want to access ith element then you have to access (i-1)th index.

Example: In the below example, the contract Types first initializes an array[data] and

then retrieves the value at specific index 2.

Solidity

// Solidity program to demonstrate


// accessing elements of an array
pragma solidity ^0.5.0;  
   
// Creating a contract 
contract Types {  
  
    // Declaring an array
    uint[6] data;    
       
    // Defining function to 
    // assign values to array
    function array_example(
    ) public payable returns (uint[6] memory){  
            
        data 
          = [uint(10), 20, 30, 40, 50, 60];
        return data;  
  } 
    
Start Your Coding Journey Now!
  // Defining function to access

https://www.geeksforgeeks.org/solidity-arrays/ 5/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

  // values from the array


  // from a specific index  
  function array_element(
  ) public payable returns (uint){  
        uint x = data[2];
        return x;  
  }  
}

Output : 

2. Length of Array: Length of the array is used to check the number of elements present

in an array. The size of the memor y array is fixed when they are declared, while in case

the dynamic array is defined at runtime so for manipulation length is required.

Example: In the below example, the contract Types first initializes an array[data] and

then the length of the array is calculated.

Solidity

// Solidity program to demonstrate 


// how to find length of an array
pragma solidity ^0.5.0;  
  
// Creating a contract
contract Types {  
  
    // Declaring an array
Start Your Coding Journey Now!
    uint[6] data;    
        
https://www.geeksforgeeks.org/solidity-arrays/ 6/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

    // Defining a function to 


    // assign values to an array
    function array_example(
    ) public payable returns (uint[6] memory){  
        data = [uint(10), 20, 30, 40, 50, 60];
        return data;  
  }  
  
  // Defining a function to 
  // find the length of the array
  function array_length(
  ) public returns(uint) {  
        uint x = data.length;
        return x; 
    } 
  }

Output : 

3. Push: Push is used when a new element is to be added in a dynamic array. The new

element is always added at the last position of the array.

Example: In the below example, the contract Types first initializes an array[data], and

then more values are pushed into the array.

Solidity

// Solidity program to demonstrate 


Start Your Coding Journey Now!
// Push operation
pragma solidity ^0.5.0;  
https://www.geeksforgeeks.org/solidity-arrays/ 7/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

   
// Creating a contract 
contract Types {  
  
    // Defining the array
    uint[] data = [10, 20, 30, 40, 50]; 
    
    // Defining the function to push 
    // values to the array
    function array_push(
    ) public returns(uint[] memory){  
    
        data.push(60);  
        data.push(70);  
        data.push(80);
    
        return data;  
    }  
}

Output : 

4. Pop: Pop is used when the last element of the array is to be removed in any dynamic

array.

Example: In the below example, the contract Types first initializes an array[data], and

then values are removed from the array using the pop function.

Start Your Coding Journey Now!


Solidity

https://www.geeksforgeeks.org/solidity-arrays/ 8/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

// Solidity program to demonstrate


// Pop operation
pragma solidity ^0.5.0;  
    
// Creating a contract
contract Types {  
  
    // Defining an array
    uint[] data 
      = [10, 20, 30, 40, 50];
    
    // Defining a function to 
    // pop values from the array
    function array_pop(
    ) public returns(uint[] memory){  
        data.pop(); 
        return data;  
    }  
}

Output : 

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-arrays/ 9/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

Like 6

Previous Next

Related Articles

1. Dynamic Arrays and its Operations in Solidity

2. Solidity - Types

3. Solidity - Functions

4. What are Events in Solidity?

5. Solidity - Inheritance

6. Solidity - Polymorphism

7. Solidity - View and Pure Functions

8. Solidity - Encapsulation

9. How to Install Solidity in Windows?

10. Solidity - While, Do-While, and For Loop

Start Your Coding Journey Now!


Ar ticle Contributed By :

https://www.geeksforgeeks.org/solidity-arrays/ 10/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

jeeteshgavande30
@jeeteshgavande30

Vote for difficulty

Current difficulty : Easy

Easy Normal Medium Hard Expert

Article Tags : Solidity-Arrays, Blockchain, Solidity

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305
[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Advertise with us Video Tutorials
Start Your Coding Journey Now! Courses

https://www.geeksforgeeks.org/solidity-arrays/ 11/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks

News Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Web Development Contribute


Web Tutorials Write an Article
Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-arrays/ 12/12
2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Jean Cvllr Follow

Aug 1, 2019 · 11 min read · · Listen

Save

Solidity Tutorial : all about Bytes

Bytes are a large aspect of Solidity, whether when using fixed size bytesN or dynamic
size bytes array. We will see in this article their difference, bitwise operations related
to fixed-sized array bytesN and we can use them to perform some generic methods
like concatenating.
https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 1/17
2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

Table of Content :
1. Endianness & bytes data layout in Solidity

2. Fixed-size byte arrays

3. Dynamically-size byte arrays

4. Bitwise operations in Solidity

5. An array of bytes = a little difference

6. Bytes as function arguments

7. Conversion between addresses and bytes20

8. Advanced operations with Bytes

9. A word of warning with Solidity bytes

1. Endianness & bytes data layout in Solidity

Introduction to Endianness
In computing, the term endianness corresponds to how the low level bytes of any data
are stored and ordered. Therefore, it defines the internal ordering of the computer or
machine memory.

We refer to multi-byte data types data that its t(uint, float, string, etc…). There are two
ways for ordering multi-byte data types in computer: in little-endian or big-endian
format (where format = order).

With Big-Endian, the first byte of binary representation of the multibyte data-type
is stored first.

With Little-Endian, the last byte of binary representation of the multibyte data-
type is stored first. (Intel x86 machines)

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 2/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

This is how a variable y with a value of 0x01234567 (hexa-decimal representation) would be stored in both
formats

Bytes data layout in Solidity


Ethereum and the EVM is a Virtual Machine that uses the Big Endian format. In the
EVM, all data (regardless of its Solidity type) is stored big-endian at the low level inside
the virtual machine. Most importantly, the EVM uses 32 bytes words to manipulate
data.

However, depending on its type ( bytesN , uintN , address , etc…), the data is laid out
differently. The sentence “how data is layout” refers to where the high order bits are
placed.

In the Ethereum and community of Solidity developers, this is more know as the
padding rules: left padded vs right padded.

The following padding rules are used in Solidity:

right-padded: string , bytes and bytesN .

left-padded: intN / uintN (signed/unsigned integers), address and other types.

Note: you will also find the term “left aligned” or “right aligned”. To better clarify and avoid
confusion:

left-padded = right aligned

right-padded = left aligned

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 3/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

As an example, this is how the string value = “abcd” in Solidity would be padded by
the EVM to a full 32 bytes word. It would be padded on the right.

0x6162636400000000000000000000000000000000000000000000000000000000

In the contrary, this how the number uint256 value = 1_633_837_924 (= 0x61626364 in
hex) in Solidity would be padded by the EVM to a full 32 bytes word. It would be
padded on the left:

0x0000000000000000000000000000000000000000000000000000000061626364

Learning the rules of data layout and padding is important to know how to deal with
different data types in Solidity. Especially when dealing with bytesN and their uintN

“relatives”. For instance for a bytes1 and uint8 value, even if they have the same bit-
size, their internal representation is different. See the code snippet below.

// 0x00000000…01
Uint8 a = 1;
// 0x01000000….
byte b = 1;
bytes1 c =

This article focus mainly on the bytesN and bytes type. Solidity presents two bytes
types :

fixed-sized byte arrays: bytesN

Dynamically-sized byte arrays: bytes that represent a sequence of bytes.

2. Fixed-size byte arrays


You can define a variables by using the keyword bytesX where X represents the
sequence of bytes. X can be from 1 up to 32

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 4/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

byte is an alias for bytes1 and therefore stores a single byte.

If you can limit the length to a certain number of bytes,


always use one of bytes1 to bytes32 because they are
much cheaper.
Bytes with a fixed-size variable can be passed between contracts.

3. Dynamically-size byte arrays


These are a really specific types. Basically, bytes and string are special array (see
Solidity doc)

Bytes

use bytes for arbitrary-length raw byte data

The term bytes in Solidity represents a dynamic array of bytes. It’s a shorthand for
byte[] .

Because bytes are treated as array is Solidity code, it can have a length of zero and you
can do things like append a byte to the end.

However, bytes is not a value type !

You can push, pop and length

String

use string for arbitrary-length string (UTF-8) data

bytes32 samevar = "stringliteral";

This string literal is interpreted in its raw byte form when assigned to a bytes32 type.

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 5/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

However, strings can’t be passed between contracts because they are not fixed size
variables.

Solidity does not have string manipulation functions, but there are third-party string
libraries.

4. Bitwise operations in Solidity

Most of this section is based on articles written by Maksym, which also provides great articles
on zk-SNARKS. Thanks Chronicled Staff !!

Solidity supports basic bitwise operations (though some of them are missing, like left
of right shift). Luckily there’s arithmetic equivalents. The following section will give
you some basic primitives for bit manipulations.

Comparison operators
The following comparison operators applied to bytes evaluate to a bool value true or
false .

<= , < , == , != , >= , >

Bit operators
The following Bit operators are available in Solidity : & (AND), | (OR), ^ (XOR) and ~

(NEGATION).

For simplicity, we are going to use bytes1 data type ( equal to byte ) for two variables :
a and b . We will initialize them in Solidity by using their hex representation.

bytes1 a = 0xb5; // [10110101]


bytes1 b = 0x56; // [01010110]

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 6/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

The following table display their representation in binary format.

NB: inputs have white background, results will be highlighted in yellow

Let’s have a look :

———————————————————————————————

& (AND) : both bits must be 1s (white rows) to result in true (1 => yellow rows).

a & b; // Result: 0x14 [00010100]

———————————————————————————————

| (OR) : at least one of the bits have to be 1 (white rows), to result in true (1 => yellow
rows)

a | b; // Result: 0xf7 [11110111]

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 7/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

———————————————————————————————

^ (XOR) : bitwise exclusive OR

XOR operation are often used in to build cryptographic algorithms that are privacy
preserving. An example are DC-nets, based on the Dining Cryptographer problem.

This is the difference between two inputs. One of the inputs have to be 1 and the other
one must be 0 to result in true. Simply a[i] != b[i].

If both inputs have the same value (1 and 1, or 0 and 0), this results in false (0).

If both inputs have different value (1 and 0, or 0 and 1), this results in true (1)

a ^ b; // Result: 0xe3 [11100011]

An interesting property is that if you want to know what was the value of original b,
just XOR result with a. In one sense a is the key to unlock b.

0xe3 ^ a; // Result: 0x56 == b [01010110]

———————————————————————————————

~ (Negation) : bitwise negation

NB: Negation is the same as to XOR input with all 1s.

This is also called an inversion operation. With this operation, 0 becomes and 1 and 1
becomes 0.
https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 8/17
2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

a ^ 0xff; // Result: 0x4a [01001010]

Here is the Solidity implementation.

function negate(bytes1 a) returns (bytes1) {


return a ^ allOnes();
}
// Sets all bits to 1
function allOnes() returns (bytes1) {

// 0 - 1, since data type is unsigned, this results in all 1s.

return bytes1(-1);
}

Shift Operators

From the Solidity Doc : The shifting operator works with any integer type as right operand
(but returns the type of the left operand), which denotes the number of bits to shift by.
Shifting by a negative amount causes a runtime exception.

Let’s have a look :

———————————————————————————————

<< x (left shift of x bits) : shift a number 3 bits left.

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 9/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

function leftShiftBinary(
bytes32 a,
uint n
) public pure returns (bytes32) {
return bytes32(uint(a) * 2 ** n);
}
// This function does the same than above using the << operators
function leftShiftBinary2(
bytes32 a,
uint n
) public pure returns (bytes32) {
return a << n;
}
// Normally, we should do the following according to the article,
// but explicit conversion is not allowed for bytes to uint
var n = 3;
var aInt = uint8(a); // Converting bytes1 into 8 bit integer
var shifted = aInt * 2 ** n;
bytes1(shifted); // Back to bytes. Result: 0xa8 [10101000]

>> x (right shift of x bits) : shift a number 3 bits left.

function rightShiftBinary(
bytes32 a,
uint n
) public pure returns (bytes32) {
return bytes32(uint(a) / 2 ** n);
}

// This function does the same than above using the >> operators
function rightShiftBinary2(
https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 10/17
2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

bytes32 a,
uint n
) public pure returns (bytes32) {
return a >> n;
}
// Normally, we should do the following according to the article,
// but explicit conversion is not allowed for bytes to uint
var n = 2;
var aInt = uint8(a); // Converting bytes1 into 8 bit integer
var shifted = aInt / 2 ** n;
bytes1(shifted); // Back to bytes. Result: 0x2d [00101101]

Index Access (read-only)

if x is of type bytesI (where I represents an integer), then x[k] for 0 <= k < I returns the
k th byte.

Accessing individual bytes by index is possible for all bytesN types. The highest order
byte is found at index 0. Let’s see with an example.

function accessByte(
bytes32 _number_in_hex,
uint8 _index
) public pure returns (byte) {
byte value = _arg[_index];
return value;
}

This is the result you should obtain in Remix

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 11/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

If we pass the arguments _number_in_hex = 0x61626364 and _index = 2 , the function


will return 0x63 as you can see from the screenshot.

Members of Bytes
.length (read-only). : yields the fixed length of the byte array

5. An array of bytes = a little difference.


According to the Solidity documentation,

The type byte[] is an array of bytes, but due to padding rules, it wastes 31 bytes of space for
each element (except in storage). It is better to use the bytes type instead.

6. Bytes as function arguments


The fixed length bytes32 can be used in function arguments to pass data in or return
data out of a contract.

The variable length bytes can be used in function arguments also, but only for
internal use (inside the same contract), because the interface (ABI) does not support
variable length type.

7. Conversion between addresses and bytes20


As we know, an address in Ethereum is a 20 bytes value (eg:
0xa59b89aee4f944a04d8fc075967d616b937dd4a7 ). Because of this, it is possible to do
conversions in both ways.

bytes20 to address

You can easily convert a value of bytes20 type into an address via explicit conversion.
That means you simply wrap your bytes20 value between parentheses () and prefix it
https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 12/17
2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

with the type address , as shown below :

address public my_address;


// This function is really expensive the 1st time
// it's called (21 000 gas). Why ?
function bytesToAddress(bytes20 input) public returns (address) {
my_address = address(input);
return my_address;
}

If we look at the result in Remix after running this function, we can see that the
explicit conversion from bytes20 to address ran successfully. Even more, the Solidity
compiler converted it into an address with a valid checksum ! Note the different
uppercase and lowercase letters in the input.

For more infos on checksum, read our article “All about addresses” or see EIP55 proposed by
Vitalik Buterin.

address to bytes20

You can also do the other way around, if you would like to convert an address into the
bytes20 type and maybe do some computation.

8. Advanced Operations with Bytes

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 13/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

Get First N Bits


In this scenario, we need a 2 step process :

1. Create a mask of needed number N of 1s in order to filter the part in a that we are
looking to retrieve.

2. Apply an AND operation between a and the mask, so : a & mask .

function getFirstNBytes(
bytes1 _x,
uint8 _n
) public pure returns (bytes1) {
require(2 ** _n < 255, “Overflow encountered ! “);
bytes1 nOnes = bytes1(2 ** _n — 1);
bytes1 mask = nOnes >> (8 — _n); // Total 8 bits
return _x & mask;
}

Gest Last N Bits


There’s arithmetic way to get last N bits. We can achieve that using modulo. For
example if want to get last 2 digits from 10345, we can easily do it by dividing by 100
(1⁰²) and getting remainder.

10345 % 10 ** 2 = 45

Same with binary, though this time we’re getting modulo of multiples of 2. For example
to get last 5 bits:

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 14/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

var n = 5;
var lastBits = uint8(a) % 2 ** n;
bytes1(lastBits); // Result: 0x15 [00010101]

Here is the implementation in Solidity.

function getLastNBytes(
byte _A,
uint8 _N
) public pure returns (bytes1) {
require(2 ** _N < 255, “Overflow encountered ! ”);
uint8 lastN = uint8(_A) % (2 ** _N);
return byte(lastN);
}

Bytes Packing
Imagine that you have 2 x 4-bits (= 2 bytes) values c and d.

You want to pack these two value into one 8-bit (= 4 bytes) value.

c takes first 4 bits, and d takes the remaining 4 bits (can be the other way around)

Note : the function below works in Remix, but is restrictive.

It is based on the example above and works only to concatenate two value of both 2 bytes into
a final value of 4 bytes. For more modularity, you might need something else, like an array of
bytes that you shrink and specify the number of bytes only (difficult)

/// @dev 798 gas cost :)


function concatBytes(
bytes2 _c,

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 15/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

bytes2 _d
) public pure returns (bytes4) {
return (_c << 4) | _d;
}

9. A word of warning with Solidity bytes


Some possibly disorienting situations are possible if bytes is used as a function
argument and the contract successfully compiles. Always use fixed length types for
any function that will called from outside.

References

Little Endian vs Big Endian


A question very frequently asked in interviews.
thebittheories.com

Endianness - Wikipedia
Historically, various methods of endianness have been used in
computing, including exotic forms such as…
en.wikipedia.org

Bitwise Operations and Bit Manipulation in Solidity, Ethereum


Yes, Ethereum is the world’s computer, though probably the most
expensive one. Since storage is the largest…
medium.com

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 16/17


2/12/23, 5:59 PM Solidity Tutorial : all about Bytes | by Jean Cvllr | Medium

Programming

About Help Terms Privacy

Open in app Sign up Sign In

Get the Medium app


Search Medium

https://jeancvllr.medium.com/solidity-tutorial-all-about-bytes-9d88fdb22676#:~:text=The term bytes in Solidity,is not a value type ! 17/17


2/12/23, 6:01 PM bytes and strings in Solidity. In this post we are going to explain… | by Cryptopusco | Medium

Cryptopusco Follow

Jan 10, 2018 · 3 min read · Listen

Save

bytes and strings in Solidity

In this post we are going to explain why cryptopus smart contracts love bytes & bytes
arrays more than strings, which are evil for now.

So, what actually is the difference between bytes and string? Solidity documentation
says:

As a rule of thumb, use bytes for arbitrary-length raw byte data and string for arbitrary-
length string (UTF-8) data. If you can limit the length to a certain number of bytes, always
https://medium.com/@cryptopusco/bytes-and-strings-in-solidity-f2cd4e53f388 1/5
2/12/23, 6:01 PM bytes and strings in Solidity. In this post we are going to explain… | by Cryptopusco | Medium

use one of bytes1 to bytes32 because they are much cheaper.

So is there any situation, when string is necessary? The answer is yes, because not all
the strings, that are passed as parameters to smart contracts are one-liners.

String literals are written with either double or single-quotes (“foo” or ‘bar’)…

String literals support escape characters, such as \n, \xNN and \uNNNN. \xNN takes a hex
value and inserts the appropriate byte, while \uNNNN takes a Unicode codepoint and inserts
an UTF-8 sequence.

Dealing with escape characters is always difficult, but Solidity let’s people work with
both types of strings.

Never the less would be to mention, that bytes1 to bytes32 use less gas, so they are
better for the situations, when there is known for sure, that strings passed to the
function are limited to the size of bytes type.

pragma solidity ^0.4.19;

contract BytesOrStrings {
string constant _string = "cryptopus.co Medium";
bytes32 constant _bytes = "cryptopus.co Medium";
function getAsString() public returns(string) {
return _string;
}

function getAsBytes() public returns(bytes32) {


return _bytes;
}
}

https://medium.com/@cryptopusco/bytes-and-strings-in-solidity-f2cd4e53f388 2/5
2/12/23, 6:01 PM bytes and strings in Solidity. In this post we are going to explain… | by Cryptopusco | Medium

Simple smart-contract above is dedicated to demonstrate the difference between both


types and Gas Conversion of them. As for bytes32 type, the gas amount used is:

{
"transactionHash":
"0xa50b4f040acb653735a0d496c34c1b6b5a635e1b21de334fb2427f3e866fbc47",
"transactionIndex": 0,
"blockHash":
"0xbfd158d140cec5015baa989dc32f075599ed7186dcc026e86690521ac6b8fb5f",
"blockNumber": 7,
"cumulativeGasUsed": 21484,
"gasUsed": 21484,
"contractAddress": null
}

The string type is not that cheap and comes with:

{
"transactionHash":
"0x7dc6e89537ff0992a12db432210b5dd7653f9f7bbd16fe56f14c73053134849f",
"transactionIndex": 0,
"blockHash":
"0x8cac42f6fddf98cb17e3fcb7c5f94a6db5ca57739407caf68659c12a62ce81a1",
"blockNumber": 8,
"cumulativeGasUsed": 21916,

"gasUsed": 21916,
"contractAddress": null
}

As you can see, the difference between calls is small, but still is. In a bigger examples,
where amount of functions and commands is higher that in a sample, it is always

https://medium.com/@cryptopusco/bytes-and-strings-in-solidity-f2cd4e53f388 3/5
2/12/23, 6:01 PM bytes and strings in Solidity. In this post we are going to explain… | by Cryptopusco | Medium

important to keep an eye on it.

Second reason to use bytes over string is smart-contract to smart-contract relations.


Solidity ver. 0.4.19 is still unable to return string as function’s result for other contracts.
It may look like really unnecessary stuff to know, but smart contracts are getting
complex with each day and the further it goes, the more contract2contract realtions
are going to appear on Blockchain.

Talking about cryptopus API, we use bytes32 as the only format of string storage. Our
structures inside Library are all bytes32 oriented:

struct brokerWallet {
bytes32 APIKey;
bytes32 APISecret;
bytes32 historyHash;
bytes32 balanceHash;
uint256 nonce;
}
struct cryptoBroker {
uint8 flag;
bytes32 username;
uint256 registerDate;
}

We also return bytes32 as function results of Storage contract, because this contract is
only about to face User Interface contract:

function balanceOf(address _owner, uint256 _position) onlyOLevel


external constant returns (bytes32) {
return brokersWallets[_owner][_position].balanceHash;
}
function historyOf(address _owner, uint256 _position) onlyOLevel
external constant returns (bytes32) {
return brokersWallets[_owner][_position].balanceHash;
}

https://medium.com/@cryptopusco/bytes-and-strings-in-solidity-f2cd4e53f388 4/5
2/12/23, 6:01 PM bytes and strings in Solidity. In this post we are going to explain… | by Cryptopusco | Medium

In conclusion to this post we want to add, that there is also a workaround for those,
who don’t want to use strings in any case. Try to use bytes32[] (arrays). There is an
assembly way to get string’s length, so it is possible to allocate as many bytes32
elements as needed.

Thank you for your interest and, please, stay tuned!

We also do love answering questions in our Telegram Chat!

Ethereum Smart Contracts Solidity Development Blockchain

Open in app Get unlimited access

Search Medium

https://medium.com/@cryptopusco/bytes-and-strings-in-solidity-f2cd4e53f388 5/5
2/12/23, 7:19 PM Learning Solidity — Loops, Libraries and Imports | by theblockchainchick | Medium

theblockchainchick Follow

Mar 16, 2019 · 3 min read · Listen

Save

Learning Solidity — Loops, Libraries and Imports

Learning Solidity — Loops, Libraries and Imports

(Part V)
This is the fifth blog in my Solidity Learning series which will talk about looping, how
to write your own libraries and import them to use them in your contracts.

https://gyanlakshmi.medium.com/learning-solidity-loops-libraries-and-imports-9e473c56275d 1/5
2/12/23, 7:19 PM Learning Solidity — Loops, Libraries and Imports | by theblockchainchick | Medium

What is looping?

Looping, in any programming language, is a technique which combines repetitions


into one entity. Loops makes sure that your business logic, which is to be repeated n
number of times, can be written in an efficient and compact manner.

Looping in Solidity
If you have already worked with programming languages, looping is pretty much the
same in Solidity as well.

for loop: Example loop that runs from 0 to 9

for (uint i =0; i < 10; i++){

//Do Something

while loop: Example loop that runs from 0 to 9

uint i =0;

while(i<10){

i++;

Using break and continue statements while looping:

Break and continue statements are used to break out of the loop based on certain
condition or skip doing something on a certain condition respectively.

for(uint i =1; i < 10; i++){

if(i %5 == 0)

break;
https://gyanlakshmi.medium.com/learning-solidity-loops-libraries-and-imports-9e473c56275d 2/5
2/12/23, 7:19 PM Learning Solidity — Loops, Libraries and Imports | by theblockchainchick | Medium

else

continue;

The above is just an example loop which will exit when i = 5.

Libraries and Imports


Libraries in Solidity can be written by the user and imported in your Solidity code to
reuse them in multiple contracts. Libraries provide you a way to re-use one set of
functions in multiple places without re-writing them over and over again.

Here is an example of a Mathematics library that we have created and imported in our
code in order to use some of those functions in our contract.

Step 1: Use the keyword library to write your library definition.

library Mathematics

Step 2: Define the functions that you would like to write in your library.

You can define the common functions that you would like to import/use in the other
contracts.

function factorial(uint num) pure public returns(uint){


uint fact = 1;
for(uint i=1; i<=num; i++){
fact *= i;
}
return fact;
}

function fivedivisible(uint num) pure public returns(uint) {


uint answer = num/5;

https://gyanlakshmi.medium.com/learning-solidity-loops-libraries-and-imports-9e473c56275d 3/5
2/12/23, 7:19 PM Learning Solidity — Loops, Libraries and Imports | by theblockchainchick | Medium

return answer;
}

I have defined two functions -factorial and fivedivisible. The factorial function returns
the factorial of a particular number and the fivedivisible function returns the quotient
after dividing by 5.

Step 3: Write a test contract to import the defined library.

Import the library(mention the full path) in your test contract. My test contract is
named TestLibrary.

import “browser/library.sol”; // In this case, since I am using the remix editor

You can use the keyword using to link a particular data type to the library so that you
can invoke the functions defined in the library on those data types.

using Mathematics for uint;

Step 4: Write your own contract functions in order to invoke the library functions.

In order to invoke the function defined in the library, write you own contract functions
and use the uint parameter to invoke the factorial and fividivisible functions.

function calcfact(uint _val) pure public returns (uint) {


return _val.factorial();
}

function calcfive(uint _val) pure public returns (uint) {


return _val.fivedivisible();
}

https://gyanlakshmi.medium.com/learning-solidity-loops-libraries-and-imports-9e473c56275d 4/5
2/12/23, 7:19 PM Learning Solidity — Loops, Libraries and Imports | by theblockchainchick | Medium

Remix Editor — Library and Imports

Libraries are useful tools to wrap a set of functions which are used repetitively in
several contracts that you write. They are a great way to use existing functionality
without writing additional logic for the same functionality multiple times.

Open in app Get unlimited access

Ethereum Solidity Solidity Tutorial Programming Smart Contracts


Search Medium

https://gyanlakshmi.medium.com/learning-solidity-loops-libraries-and-imports-9e473c56275d 5/5
2/12/23, 7:21 PM Solidity - While, Do-While, and For Loop - GeeksforGeeks

Read Discuss Courses Practice Video

Solidity – While, Do-While, and For Loop


Last Updated : 11 May, 2022

Loops are used when we have to per form an action over and over again. While

writing a contract there may be a situation when we have to do some action repeatedly,

In this situation, loops are implemented to reduce the number of lines of the statements.

Solidity suppor ts following loops too ease down the programming pressure.

While Loop

This is the most basic loop in solidity, Its purpose is to execute a statement or block of

statements repeatedly as far as the condition is true and once the condition becomes

false the loop terminates. 

Syntax :

while (condition) {
statement or block of code to be executed if the condition is True
}

Example : In the below example, the contract Types demonstrate the execution of a while

loop and how an array can be initialized using the while loop.

Start Your Coding Journey Now!▲ Login Register


HIDE AD

https://www.geeksforgeeks.org/solidity-while-do-while-and-for-loop/ 1/10
2/12/23, 7:21 PM Solidity - While, Do-While, and For Loop - GeeksforGeeks

Read Discuss Courses Practice Video

Solidity

// Solidity program to 


// demonstrate the use
// of 'While loop'
pragma solidity ^0.5.0; 
  
// Creating a contract 
contract Types { 
      
    // Declaring a dynamic array
    uint[] data; 
    
    // Declaring state variable
    uint8 j = 0;
     
    // Defining a function to 
    // demonstrate While loop'
    function loop(
    ) public returns(uint[] memory){
    while(j < 5) {
        j++;
        data.push(j);
     }
      return data;
    }
}

Output : 

 
Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-while-do-while-and-for-loop/ 2/10
2/12/23, 7:21 PM Solidity - While, Do-While, and For Loop - GeeksforGeeks

Read Discuss Courses Practice Video

Do-While Loop

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+
This loop is ver y similar to while loop except that there is a condition check which

happens at the end of loop i.e. the loop will always execute at least one time even if the

condition is false. 

Syntax :

do
{
Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-while-do-while-and-for-loop/ 3/10
2/12/23, 7:21 PM Solidity - While, Do-While, and For Loop - GeeksforGeeks

block of statements to be executed


} while (condition);
Read Discuss Courses Practice Video
Example : In the below example, the contract Types demonstrate the execution of a do-

while loop and how an array can be initialized using the do-while loop.

Solidity

// Solidity program to 


// demonstrate the use of
// 'Do-While loop'
pragma solidity ^0.5.0; 
  
// Creating a contract 
contract Types { 
      
    // Declaring a dynamic array
    uint[] data; 
    
    // Declaring state variable
    uint8 j = 0;
  
    // Defining function to demonstrate 
    // 'Do-While loop'
    function loop(
    ) public returns(uint[] memory){
    do{
        j++;
        data.push(j);
     }while(j < 5) ;
      return data;
    }
}

Output : 

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-while-do-while-and-for-loop/ 4/10
2/12/23, 7:21 PM Solidity - While, Do-While, and For Loop - GeeksforGeeks

Read Discuss Courses Practice Video

For Loop

This is the most compact way of looping. It takes three arguments separated by a semi-

colon to run. The first one is ‘loop initialization’ where the iterator is initialized with

star ting value, this statement is executed before the loop star ts. Second is ‘test

statement ’ which checks whether the condition is true or not, if the condition is true the

loop executes else terminates. The third one is the ‘iteration statement ’ where the

iterator is increased or decreased. Below is the syntax of for loop :

Syntax :

for (initialization; test condition; iteration statement) {


statement or block of code to be executed if the condition is True
Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-while-do-while-and-for-loop/ 5/10
2/12/23, 7:21 PM Solidity - While, Do-While, and For Loop - GeeksforGeeks

Read Discuss Courses Practice Video


Example : In the below example, the contract Types demonstrate the execution of a while

loop and how an array can be initialized using the while loop.

Solidity

// Solidity program to 


// demonstrate the use
// of 'For loop'
pragma solidity ^0.5.0; 
   
// Creating a contract
contract Types { 
     
    // Declaring a dynamic array 
    uint[] data; 
  
    // Defining a function 
    // to demonstrate 'For loop'
    function loop(
    ) public returns(uint[] memory){
    for(uint i=0; i<5; i++){
        data.push(i);
     }
      return data;
    }
}

Output :  

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-while-do-while-and-for-loop/ 6/10
2/12/23, 7:21 PM Solidity - While, Do-While, and For Loop - GeeksforGeeks

Read Discuss Courses Practice Video

Like 8

Previous Next

Related Articles

1. Solidity - View and Pure Functions

2. Solidity - Break and Continue Statements

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-while-do-while-and-for-loop/ 7/10
2/12/23, 7:21 PM Solidity - While, Do-While, and For Loop - GeeksforGeeks

3. Solidity - Enums and Structs

Read Discuss Courses


4. Creating a Smart ContractPractice
that ReturnsVideo
Address and Balance of Owner using
Solidity

5. Dynamic Arrays and its Operations in Solidity

6. Introduction to Bytecode and Opcode in Solidity

7. Difference Between this and address(this) in Solidity

8. Solidity - Types

9. Solidity - Functions

10. What are Events in Solidity?

Ar ticle Contributed By :

jeeteshgavande30
@jeeteshgavande30

Vote for difficulty

Easy Normal Medium Hard Expert

Article Tags : Solidity Control-Flow, Blockchain, Solidity

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-while-do-while-and-for-loop/ 8/10
2/12/23, 7:21 PM Solidity - While, Do-While, and For Loop - GeeksforGeeks

Read Article
Improve Discuss Report IssuePractice
Courses Video

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Advertise with us Video Tutorials
Courses

News Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Start Your
WebCoding Journey Now!
Development Contribute
HIDE AD

https://www.geeksforgeeks.org/solidity-while-do-while-and-for-loop/ 9/10
2/12/23, 7:21 PM Solidity - While, Do-While, and For Loop - GeeksforGeeks

Web Tutorials Write an Article


Django Tutorial Improve an Article
Read Discuss HTML
Courses Practice Video Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-while-do-while-and-for-loop/ 10/10
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

Published in Coinmonks

Ferdi Kurt Follow

Dec 9, 2020 · 2 min read · Listen

Save

ETHEREUM SMART CONTRACTS DEVELOPMENT

Solidity Fundamentals
Operators: Arithmetic, Logical, Comparison, Assignment, Bitwise,
Conditional

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 1/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

In this section, we will learn operators which are play vital role in any programming
language. At the same time, operators that are used in Solidity are very similar to
Javascript. We can group them in 6 prominent categories;

1. Arithmetic Operators

2. Logical Operators

3. Comparison Operators

4. Assignment Operators

5. Bitwise Operators

6. Conditional Operators

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 2/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

Arithmetic Operators

These operators are used to perform arithmetic-mathematical operations.

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 3/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

1 // SPDX-License-Identifier: UNLICENSED
2 pragma solidity >=0.7.0 <0.8.0;
3
4 contract ArithmeticOperators {
5 // initializing variables
6 uint public x = 20;
7 uint public y = 10;
8
9 // addition, subtraction, multiplication, division
10 uint public addition = x + y; // 30
11 uint public subtraction = x - y; // 10
12 uint public multiplication = x * y; // 200
13 uint public division = x / y; // 2
14
15 /**
16 * @dev x++ executes the statement and then increments the value,
17 * however ++x increments the value and then executes the statement
18 *
19 * see examples!
20 */
21 uint public inc = x++; // equivalent to x = x + 1
22 uint public dec = x--; // equivalent to x = x - 1
23
24 // post - pre increment, decrement
25 uint public postInc = y++; // postInc = 10, y = 11
26 uint public preInc = ++y; // preInc = 12, y = 12
27
28 /**
29 * @dev the modulo (%) opererator produces the remainder
30 * of an integer division
31 *
32 * i.e. 17 % 5 = 2
33 */
34 uint public mod = x % y; // 20 % 10 = 0
35 }

ArithmeticOperators.sol hosted with ❤ by GitHub view raw

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 4/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

Logical Operators

Combining two or more conditions requires the usage of logical operators.

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 5/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

1 // SPDX-License-Identifier: UNLICENSED
2 pragma solidity >=0.7.0 <0.8.0;
3
4 contract LogicalOperators {
5 /**
6 * @dev In programming, AND(&&) returns true if both operands are truthy
7 * and false otherwise
8 *
9 * ( true && true ); // true
10 * ( true && false ); // false
11 * ( false && true ); // false
12 * ( false && false ); // false
13 */
14 function andOperator(uint hour) public pure returns (bool) {
15 if (hour >= 10 && hour <= 18) {
16 return true;
17 }
18
19 return false;
20 }
21
22 /**
23 * @dev In programming, OR(||) returns true if any of given arguments is true,
24 * otherwise it returns false.
25 *
26 * ( true || true ); // true
27 * ( true || false ); // true
28 * ( false || true ); // true
29 * ( false || false ); // false
30 */
31 bool public isWeekend = true;
32 function orOperator(uint hour) public view returns (bool) {
33 if (hour < 10 || hour > 18 || isWeekend) {
34 return true;
35 }
36
37 return false;
38 }
39
40 /**
41 * @dev NOT(!) operator converts the operand to its inverse value
42 *
43 * (!true); // false
44 * (!false); // true
45 */
https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 6/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks
45 */
46 function setWeekendValue() public {
47 isWeekend = false;
48 }
49 }
Comparison Operators
LogicalOperators.sol hosted with ❤ by GitHub view raw

These operators are used to compare two values.

1 // SPDX-License-Identifier: UNLICENSED
2 pragma solidity >=0.7.0 <0.8.0;
3
4 contract ComparisonOperators {
5 // initializing variables
6 uint16 public x = 20;
7 uint16 public y = 10;
8
9 // equal (==) operator checks if two values are equal or not
10 bool public isEqual = x == y; // false
11
12 // not equal (!=)
13 bool public notequal = x != y; // x is not equal to y, true
14
15 // greater (>) than
16 bool public greater = x > y; // true
17
18 // greater than or equal to (>=)
19 bool public greaterOrEqual = x >= y; // true
20
21 // less (<) than
22 bool public less = x < y; // false
23
24 // less than or equal to (<=)
25 bool public lessOrEqual = x <= y; // false
26 }

ComparisonOperators.sol hosted with ❤ by GitHub view raw

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 7/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

Assignment Operators

For assigning value to a variable, solidity supports assignment operators below.

1 // SPDX-License-Identifier: UNLICENSED
2 pragma solidity >=0.7.0 <0.8.0;
3
4 contract AssignmentOperators {
5 /**
6 * @dev number1 += number2 is equivalent to number1 = number1 + number2
7 *
8 * The operators -=, *=, /=, %= are defined accordingly.
9 */
10 uint public number = 2;
11
12 uint public add = 5;
13 uint public sub = 5;
14 uint public mul = 5;
15 uint public div = 6;
16 uint public mod = 5;
17
18 // Defining function to
19 // demonstrate Assignment Operator
20 function getResult() public returns(string memory) {
21 add += number; // 5 + 2
22 sub -= number; // 5 - 2
23 mul *= number; // 5 * 2
24 div /= number; // 6 / 2
25 mod %= number; // 5 % 2
26
27 return "Calculation finished!";
28 }
29 }

AssignmentOperators.sol hosted with ❤ by GitHub view raw

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 8/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

Bitwise Operators

These operators used to perform bit-level operations like AND , OR , XOR , NOT etc.

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 9/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

1 // SPDX-License-Identifier: UNLICENSED
2 pragma solidity >=0.7.0 <0.8.0;
3
4 contract BitwiseOperators {
5 /**
6 * @dev bitwise AND(&), performs boolean AND operation on each bit
7 *
8 * bytes1 a = 0x15; // [00010101]
9 * bytes1 b = 0xf6; // [11110110]
10 *
11 * i.e. (00010101) & (11110110) = (00010100)
12 */
13 function and(bytes1 b1, bytes1 b2) public pure returns(bytes1) {
14 return b1 & b2;
15 }
16
17 /**
18 * @dev bitwise OR(|), performs boolean OR operation on each bit
19 *
20 * bytes1 a = 0x15; // [00010101]
21 * bytes1 b = 0xf6; // [11110110]
22 *
23 * i.e. (00010101) | (11110110) = (11110111)
24 */
25 function or(bytes1 b1, bytes1 b2) public pure returns(bytes1) {
26 return b1 | b2;
27 }
28
29 /**
30 * @dev bitwise XOR(^), performs boolean XOR operation on each bit
31 *
32 * XOR Table
33 * 1 ^ 1 = 0
34 * 0 ^ 0 = 0
35 * 1 ^ 0 = 1
36 * 0 ^ 1 = 1
37 *
38 * bytes1 a = 0x15; // [00010101]
39 * bytes1 b = 0xf6; // [11110110]
40 *
41 * i.e. (00010101) ^ (11110110) = (11100011)
42 */
43 function xor(bytes1 b1, bytes1 b2) public pure returns(bytes1) {
Open
44 in app return b1 ^ b2; Get unlimited access
45 }
https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 10/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks
45 }
46 Search Medium
47 /**
48 * @dev bitwise NOT(~), performs boolean NOT operation on each bit
49 *
Conditional
50 Operators
* bytes1 a = 0x15; // [00010101]
51 *
52 conditional
The * i.e. ~00010101 = 11101010
(ternary) operators is operator that takes three operands: a condition
53 */
followed by a question mark ( ? ), then an expression to execute if the condition is
54 function not(bytes1 b1) public pure returns(bytes1) {
truthy
55 followed by~b1;
return a colon ( : ), and finally the expression to execute if the condition is
falsy.
56 This
} operator is frequently used as a shortcut for the if statement.
57
58 /**
1
59 // SPDX-License-Identifier: UNLICENSED
* @dev bitwise left SHIFT(<<), shifts bits to the left according to given value
2
60 pragma
* solidity >=0.7.0 <0.8.0;
3
61 * bytes1 a = 0x15; // [00010101]
4
62 contract
* ConditionalOperators {
5
63 /**
* i.e. 00010101 << 2 = 01010100
6
64 *
*/@dev if condition true ? then x: else y
7
65 *
function leftShift(bytes1 a, uint n) public pure returns (bytes1) {
8
66 */ return a << n;
9
67 function
} getMax(uint x, uint y) public pure returns(uint) {
10
68 return x >= y ? x: y;
11
69 }
/**
12
70 * @dev bitwise right SHIFT(>>), shifts bits to the right according to given value
13
71 //
* same functionality with the above
14
72 function
* bytes1 _getMax(uint x, uint y) internal pure returns(uint) {
a = 0x15; // [00010101]
15
73 * if (x >= y) {
16
74 return x;
* i.e. 00010101 >> 2 = 00000101
17
75 */ }
18
76 function rightShift(bytes1 a, uint n) public pure returns (bytes1) {
19
77 return y;
return a >> n;
20
78 }
}
21
79 }
}

ConditionalOperators.sol hosted
BitwiseOperators.sol hosted with with
❤ by ❤GitHub
by GitHub view
view raw
raw

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 11/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

126
Unsigned math operations should be carefully examined. There are some scenarios
that need to be watched for as they can cause havoc in production, for instance,
multiplication of two unsigned integers can cause overflow, or subtraction of two
unsigned integers can result in underflow.

Later in the contract security section, we will handle these type of scenarios using open
source libraries like Open Zeppelin’s SafeMath.

In the next part, we will be working on reference types such as arrays, structs and
mapping. Thanks for reading.

References

Solidity - Solidity 0.7.5 documentation

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 12/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

Solidity is an object-oriented, high-level language for implementing smart contracts. Smart


contracts are programs…
docs.soliditylang.org

Ethereum Smart Contract Best Practices


 This document provides a baseline knowledge of security considerations for intermediate
Solidity programmers. It is…
consensys.github.io

All Parts in Order


Layout of a Contract

Value Types: Part One

Value Types: Part Two

Operators

Reference Types

Data Location and Assignment Behaviors

Control Structures

Error Handling: Assert, Require, Revert and Exceptions

Functions: Part One

Functions: Part Two

Feel free to ask any question.

Stay safe, do good work, and keep in touch!

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 13/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks

Ferdi Kurt

Blockchain Ethereum Smart Contracts Cryptocurrency Programming

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 14/14
2/12/23, 7:26 PM Learn Solidity lesson 23. Loops and conditionals. | by João Paulo Morais | Coinmonks | Medium

Published in Coinmonks

João Paulo Morais Follow

Aug 13, 2022 · 5 min read · Listen

Save

Learn Solidity lesson 23. Loops and conditionals.

Solidity has loops and conditionals similar to other programming languages. Its syntax
is pretty much the same as C, Java, and JavaScript, so this chapter should be
straightforward for anyone who is used to programming in languages like the ones
above.

if/else/else if
https://medium.com/coinmonks/learn-solidity-lesson-23-loops-and-conditionals-2e90489cd865 1/7
2/12/23, 7:26 PM Learn Solidity lesson 23. Loops and conditionals. | by João Paulo Morais | Coinmonks | Medium

When the program finds some kind of fork in its flow, where it must follow a certain
path if a condition is satisfied, we have a conditional. For this type of situation we use
the keywords if/else.

if (condition) {
...
code to be executed if the condition is satisfied.
...
} else {
...
code to be executed if the condition is not satisfied.
...
}

The condition must be an expression that returns true or false, such as x > 3 or (y < 1
&& z == 4). Note that Solidity does not convert the value 1 to true and neither convert
an empty string to false.

Often, instead of using if/else, it is better to use require to check a condition. They don’t
have the same effect and should be used according to the code’s purpose.

Let’s suppose that we want a function to be correctly executed only if the sender of the
transaction is an address previously registered in the variable owner . We could have
the following.

function onlyOwner() public {


if (msg.sender === owner) {
... some code
}
}

If the sender is not the address of owner , the above function will have no effect, but the
transaction will be valid and will not throw an error. This is usually not what we want.
We could improve this function to throw an error, as below.

function onlyOwner() public {


if (msg.sender == owner) {
https://medium.com/coinmonks/learn-solidity-lesson-23-loops-and-conditionals-2e90489cd865 2/7
2/12/23, 7:26 PM Learn Solidity lesson 23. Loops and conditionals. | by João Paulo Morais | Coinmonks | Medium

... some code


} else
revert("Sender not owner");
}
}

The transaction will be rolled back if the owner is not the sender of the transaction, via
the revert method. The above conditional is common in other programming languages,
but in Solidity it is better to use the require method in such cases.

function onlyOwner() public {


require(msg.sender == owner, "Sender not owner");
... some code
}

If the condition inside require is false, the transaction will roll back. As a second
parameter, we can send an error message to the sender of the transaction.

Solidity also accepts the else if expression, which allows you to chain conditionals, as
below.

if (condition) {... code ...}


else if (condition) {... code ...}
...
else {... code ...}

In other programming languages, the above chained conditional can be replaced by


using switch, but this keyword does not exist in Solidity. In the above scenario, we must
use multiple if’s.

while, do while and for loops


When we want a block of code to run multiple times, we use some form of loop. Let’s
start by looking at the use of while, which executes a block of code while a certain
condition is true.

https://medium.com/coinmonks/learn-solidity-lesson-23-loops-and-conditionals-2e90489cd865 3/7
2/12/23, 7:26 PM Learn Solidity lesson 23. Loops and conditionals. | by João Paulo Morais | Coinmonks | Medium

while (condition) {
// code to be executed
}

Inside a loop we can use two keywords: break and continue. If the EVM encounters a
break inside a loop, it will exit the loop and continue the flow of code after the loop. If it
finds a continue it will skip the rest of the code block and go back to the conditional, for
one more iteration of the loop. Let’s see examples.

uint8 last;
uint8 i;
while(i < 10) {
last = i;
i++;
if (i==5) break;
} // last => 4

First we define a variable i that will act as a counter. The variable last will store the
last value of the counter inside the conditional. For each iteration, we increment the
counter.

When the variable i reaches the value of 4, in the loop block it is incremented to 5
(through the expression i++, which is equivalent to i=i+1). The conditional (i==5) will
then be true, break will be executed and the loop is terminated.

An example using the continue keyword is shown below.

uint8 total;
uint8 i;
while(i < 10) {
i++;
if (i==5) continue;
total++;
} // total => 9

https://medium.com/coinmonks/learn-solidity-lesson-23-loops-and-conditionals-2e90489cd865 4/7
2/12/23, 7:26 PM Learn Solidity lesson 23. Loops and conditionals. | by João Paulo Morais | Coinmonks | Medium

The above loop will be executed 10 times, as the variable i will run from 0 to 9.
However, the variable total will end up with a value of 9, not 10. This happens
because when i is 5, the condition (i==5) will be true and continue will be executed.
This way the loop will go back to the beginning and the increment of the variable
total will not be executed for that particular iteration.

The do while loop is similar to the while loop, the difference is that the condition is
checked after the code block is executed, not at the beginning.

In the example below, at least the first iteration is executed, even though the condition
is explicitly false.

uint8 value;
do {
value = 10;
} while(false); // value => 10

In the examples above, three essential ingredients were needed: a counter, a


conditional, and a way to increment the counter. These three ingredients are easily
implemented using the for loop.

for (initialize the counter; conditional; increment) {


// code to be executed
}

Let’s write an example to iterate over an array and change all of its entries.

uint[] memory array = new uint[](5);


for(uint i=0; i < array.length; i++) {
array[i] = i;
} // array => [0,1,2,3,4]

You have to be a little careful when using loops in Solidity, especially for
adding/changing state variables. Managing state variables is one of the most gas-
https://medium.com/coinmonks/learn-solidity-lesson-23-loops-and-conditionals-2e90489cd865 5/7
2/12/23, 7:26 PM Learn Solidity lesson 23. Loops and conditionals. | by João Paulo Morais | Coinmonks | Medium

intensive operations on Ethereum, so a loop that makes multiple changes to state


variables can consume a lot of gas.

Thanks for reading!

Comments and suggestions about this article are welcome.

Any contribution is welcome. www.buymeacoffee.com/jpmorais

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also, Read
The Best Crypto Tax Software | CoinTracking Review

Stackedinvest Review | Kraken Review | bitFlyer Review

Best Crypto Lending Platforms | Leveraged Token

Best Crypto Charting Tool | Best Crypto Exchange

Bitsler Review |WazirX vs CoinSwitch vs CoinDCX

Solidity Ethereum

Enjoy the read? Reward the writer.Beta


Your tip will go to João Paulo Morais through a third-party platform of their choice, letting them know you appreciate
their story.

https://medium.com/coinmonks/learn-solidity-lesson-23-loops-and-conditionals-2e90489cd865 6/7
2/12/23, 7:26 PM Learn Solidity lesson 23. Loops and conditionals. | by João Paulo Morais | Coinmonks | Medium

Give a tip

Open in app Get unlimited access


Sign up for Coinmonks
By Coinmonks
Search Medium
A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/coinmonks/learn-solidity-lesson-23-loops-and-conditionals-2e90489cd865 7/7
2/12/23, 7:32 PM Solidity: Variables and Value Data Types | by Mary Mazi | Medium

Mary Mazi Follow

Feb 19, 2022 · 4 min read · Listen

Save

Solidity: Variables and Value Data Types

Photo by environmatic on iStock

In programming languages, data types are a means of specifying the type of value that
a variable possesses. If variables are containers that hold data, then data type is the
type of container which tells that what kind of stuff can be put in it.

https://medium.com/@mazma/solidity-variables-and-value-data-types-e2b29bddcaf7#:~:text=bool %3A The possible values are constants true and fal… 1/5
2/12/23, 7:32 PM Solidity: Variables and Value Data Types | by Mary Mazi | Medium

Data types also determine what operations and actions can be performed on a given
data. A solid understanding of data types is highly useful in ensuring that data is
collected in the preferred format and the value of each property is as expected.

Types of Variables
There are three types of variables in Solidity:

1. State Variables: These are variables whose values are stored permanently on the
blockchain. They are declared inside of a contract but outside a function.

2. Local Variables: These are variables defined within a function to temporarily hold
values during a program execution. They cannot be accessed outside the function
in which they are defined and they exist only while the function is executing.

3. Global Variables: These are special variables that exist in the global namespace
and are used to retrieve information about the blockchain.

Defining Variables
When declaring a variable in Solidity, you have to specify the data type first, followed
with an access modifier, and the variable name.

Access Modifiers are the keywords used to specify the accessibility or scope. of a
variable or function. The scope of local variables is limited to function in which they
are defined but state variables and functions can have the following scope:

Public
Both state variables and functions can be marked as public. Public state variables and
https://medium.com/@mazma/solidity-variables-and-value-data-types-e2b29bddcaf7#:~:text=bool %3A The possible values are constants true and fal… 2/5
2/12/23, 7:32 PM Solidity: Variables and Value Data Types | by Mary Mazi | Medium

functions can both be accessed from the outside and the inside. The Solidity compiler
automatically creates a getter function for them.

Private
This is the most restrictive visibility. State variables and functions marked as private
are only visible and accessible in the same contract.

Private is only a code-level visibility modifier. A


contract marked as private is still visible to observers
of the blockchain, it is just not accessible for other
contracts.
Internal
This is the default visibility for state variables. Internal functions and state variables
can both be accessed from within the same contract and in deriving contracts. They
aren’t accessible from the outside.

External
Only functions can be marked external. External functions are meant to be called by
other contracts. They cannot be called internally.

If you do not specify any access modifier when declaring a variable, it will be
considered as a private.

//STRUCTURE
<type> <access modifier> <variable name>;`

Data Types
Solidity is a statically typed language. As a result, the data type of each variable (state
and local) needs to be specified. Data types in Solidity can be classified into two types:

1. Value type: This is a type that holds the data directly in the memory owned by it.
Variables of this type are always passed by value. This means that their values are
https://medium.com/@mazma/solidity-variables-and-value-data-types-e2b29bddcaf7#:~:text=bool %3A The possible values are constants true and fal… 3/5
2/12/23, 7:32 PM Solidity: Variables and Value Data Types | by Mary Mazi | Medium

always copied when they are used in assignments or as function arguments.

2. Reference type: These are variables whose values are references to where the
actual data is stored in memory.

A Closer Look at Value Types


The value types supported in Solidity are:

1. Boolean
bool : The possible values are constants true and false .

2. Integer
int / uint : Signed integers are declared with the int keyword, unsigned integers
with the uint and both take up 32 bytes by default. You can specify the exact
number of bits your variable can hold if the default size of 32 bytes is too much.
You do this in steps of 8 starting from 8 up till 256. For example int128 / uint128 .

3. Fixed Point Number


fixed / ufixed : Used to represent numbers with a fixed number of decimal places.
No matter how large or small the fractional part is, it will always use the same
number of bits. This is however an upcoming type and cannot be used yet.

4. Address
address : Holds a 20 byte value (size of an Ethereum address).
address payable : Holds same size as address , but with the additional members
transfer and send .

The difference between both address types is that address payable is an address
you can send Ether to, while a plain address cannot be sent Ether.

5. Fixed-size Byte Array


This contains a sequence of bytes from one to up to 32. The length of the array
must always be specified in the type declaration. They are declared in the following
way bytes1 , bytes2 , bytes3 all the way up to bytes32 . byte is an alias for bytes1 .

6. Literals
Literals refer to fixed values that the program may not alter during its execution.

https://medium.com/@mazma/solidity-variables-and-value-data-types-e2b29bddcaf7#:~:text=bool %3A The possible values are constants true and fal… 4/5
2/12/23, 7:32 PM Solidity: Variables and Value Data Types | by Mary Mazi | Medium

These fixed values are also called constants. These include address literals, rational
and integer literals, string literals, hexadecimal literals.

7. Enums
Enums are one way to create a user-defined type in Solidity. They restrict a variable
to have one of only a few predefined values.
Open in app Get unlimited access

Search Medium

https://medium.com/@mazma/solidity-variables-and-value-data-types-e2b29bddcaf7#:~:text=bool %3A The possible values are constants true and fal… 5/5
2/12/23, 7:33 PM Lesson 2: Value Types in Solidity | by Lajos Deme | Solidify | Medium

Published in Solidify

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Lajos Deme Follow

Sep 18, 2021 · 5 min read · · Listen

Save

Lesson 2: Value Types in Solidity


Introduction to value types

https://medium.com/solidify/lesson-2-value-types-in-solidity-a594f152da64 1/8
2/12/23, 7:33 PM Lesson 2: Value Types in Solidity | by Lajos Deme | Solidify | Medium

Photo by Michael Dziedzic on Unsplash

In Solidity, like in many other languages, data types can be broadly classified into two
groups: reference types and value types. In this article, we will examine the various
value types that are present in the language.

Let’s begin by defining what a value type is. A value type is a type that holds the data
directly in the memory owned by it. Variables of these types are always passed by
value, meaning that they are always copied when assigned to another variable or
passed into a function.

The following types are value types in Solidity:

booleans

integers

https://medium.com/solidify/lesson-2-value-types-in-solidity-a594f152da64 2/8
2/12/23, 7:33 PM Lesson 2: Value Types in Solidity | by Lajos Deme | Solidify | Medium

unsigned integers

addresses

fixed-size byte arrays ( bytes1 to bytes32 )

enums

fixed point numbers (they are not fully supported yet)

Booleans
Booleans, of course, can hold two values true or false . Solidity supports all your
regular boolean operators, such as ! , && , == etc. They only take up 1 byte of storage.

bool public a_boolean;

Signed and unsigned integers


Signed integers are declared with the int keyword, unsigned integers with the uint

and both take up 32 bytes by default. If you know your variable will never hold that
many bytes you can always make it smaller by explicitly specifying the number of bits.
For example int128 / uint128 . You can specify this in steps of 8 starting from 8 up till
256. You can use regular comparison, arithmetic, and bitwise operators on both int

and uint .

When it comes to addresses, things start to get a bit more interesting. We will go into
greater detail on addresses in another lesson, but for now, you should know that there
are two types of addresses, Externally Owned Addresses (EOA) and contract addresses.
An EOA is an address to an Ethereum account, just like an inbox has an email address.
You can use this to send/receive funds. The contract address is the address associated
with a smart contract, and it is used to send/receive money to and from that contract.
In both cases, the address is in the format of a 42 character hexadecimal address. The
address is derived from the first 20 bytes of the public key controlling the account (if
it’s an EOA), or deploying the contract (if it’s a smart contract). So every address takes
up 20 bytes of storage. You declare an address like this:

https://medium.com/solidify/lesson-2-value-types-in-solidity-a594f152da64 3/8
2/12/23, 7:33 PM Lesson 2: Value Types in Solidity | by Lajos Deme | Solidify | Medium

address public an_address;

Fixed-size byte arrays


Fixed-size byte arrays contain a sequence of bytes. The length of the array must always
be specified in the type declaration. They are declared in the following way bytes1 ,

bytes2 , bytes3 all the way up to bytes32 . byte is an alias for bytes1 . You can use your
regular boolean operators, comparison operators, and bitwise operators on this type
too.

It’s important to note that there is another type, called bytes which is different from
the above in that it is a dynamically sized array, and not a value type but a reference
type. It is basically shorthand for byte[] .

When you can limit the length of your data to a predefined amount of bytes, it is
always good practice to use some of bytes1 to bytes32 because it is much cheaper.

Enums
Enums in Solidity are a way to create user-defined types. Enums are explicitly
convertible to integer types, but not implicitly. Enum values are numbered in the order
they are defined, starting from 0.

Enums are not part of the ABI (Application Binary Interface — more on this in a later
lesson, but it’s basically how you encode Solidity code for the Ethereum Virtual
Machine, and how you get data back). This means that if your function returns an enum

for example, it will be automatically converted to a uint8 behind the scenes. The
integer returned is just large enough to hold all enum values. With more values, the
size gets increased too ( uint16 and up).

The below code, taken from the Solidity docs, defines an enum with four possible
values, creates a variable of that enum named choice and a constant called
defaultChoice that will hold a default value.

enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }


ActionChoices choice;

https://medium.com/solidify/lesson-2-value-types-in-solidity-a594f152da64 4/8
2/12/23, 7:33 PM Lesson 2: Value Types in Solidity | by Lajos Deme | Solidify | Medium

ActionChoices constant defaultChoice = ActionChoices.GoStraight;

Now we can define some functions to interact with our enum .

function setGoStraight() public {


choice = ActionChoices.GoStraight;
}

function setChoice(ActionChoices newChoice) public {


choice = newChoice;
}

The first one simply sets the choice to GoStraight while the second one sets it to the
choice that the caller passes into the function. As we can see after deployment, the
setChoice function expects a uint8 value, which corresponds to the enum value
declared at that number.

Testing enums in Remix

If we want to get the value of choice and defaultChoice , we can define the following
functions:

function getChoice() public view returns (ActionChoices) {


return choice;

https://medium.com/solidify/lesson-2-value-types-in-solidity-a594f152da64 5/8
2/12/23, 7:33 PM Lesson 2: Value Types in Solidity | by Lajos Deme | Solidify | Medium

}
function getDefaultChoice() public pure returns (uint) {
return uint(defaultChoice);
}

As we can see if we try this out in Remix, the first function returns a uint8 while the
second returns a uint256 .

Testing enums in Remix

Fixed point numbers


Fixed point numbers represent fractional numbers by storing a fixed number of digits
of their fractional part. No matter how large or small the fractional part is, it will
always use the same number of bits.

Fixed point numbers are not fully supported by Solidity


yet. They can be declared, but cannot be assigned to
or from.
We can differentiate between signed fixed point numbers, declared with the fixed

keyword, and unsigned fixed point numbers, declared with the ufixed keyword.

https://medium.com/solidify/lesson-2-value-types-in-solidity-a594f152da64 6/8
2/12/23, 7:33 PM Lesson 2: Value Types in Solidity | by Lajos Deme | Solidify | Medium

It can also be declared as fixedMxN or ufixedMxN where M represents the number of


bits the type takes, and N represents the number of decimal points. M has to be
divisible by 8 and a number between 8 and 256. N has to be a number between 0 and
80.

They function with the following operators:

Comparisons: <= , < , == , != , >= , > (evaluate to bool )

Arithmetic operators: +, -, unary -, unary +, *, /, % (remainder)

Conclusion
In this lesson, we looked at what value types are available in Solidity and how each one
works.

Thank you for staying with us till the end. If you enjoyed reading this piece please keep
in touch and follow Solidify to keep up with our lessons on Solidity. In the upcoming
articles, we will deep dive into the intricacies of the language, progressing from
beginner to advanced level.

If you are new to Solidity, check out the previous lessons about setting up a local
development environment and writing your first smart contract.

How to Setup Your Local Solidity Development Environment


Get started with smart contract development
medium.com

Lesson 1: Your First Solidity Smart Contract


In the previous lesson, we looked at how to set up your local Solidity
development environment. Here we will continue…
medium.com

https://medium.com/solidify/lesson-2-value-types-in-solidity-a594f152da64 7/8
2/12/23, 7:33 PM Lesson 2: Value Types in Solidity | by Lajos Deme | Solidify | Medium

Solidity Ethereum Programming Coding Cryptocurrency

About Help Terms Privacy

Open in app Sign up Sign In

Get the Medium app


Search Medium

https://medium.com/solidify/lesson-2-value-types-in-solidity-a594f152da64 8/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks

Read Discuss Courses Practice Video

Solidity – Types
Difficulty Level : Basic ● Last Updated : 18 Nov, 2022

Solidity is a statically typed language, which implies that the type of each of

the variables should be specified. Data types allow the compiler to check the correct

usage of the variables. The declared types have some default values called Zero-State,

for example for bool the default value is False. Likewise other statically typed languages

Solidity has Value types and Reference types which are defined below:

Value Types

Value-type variables store their own data. These are the basic data types provided by

solidity. These types of variables are always passed by value. The variables are copied

wherever they are used in function arguments or assignments. Value type data types in

solidity are listed below: 

Boolean: This data type accepts only two values True or False.

Integer: This data type is used to store integer values, int and uint are used to declare

signed and unsigned integers respectively.

Fixed Point Numbers : These data types are not fully suppor ted in solidity yet, as per

the Solidity documentation. They can be declared as fixed and unfixed for signed and

unsigned fixed-point numbers of var ying sizes respectively.

Address : Address hold a 20-byte value which represents the size of an   Ethereum

address. An address can be used to get balance or to transfer a balance by balance

and transfer method respectively.

Bytes : Although bytes are similar to strings, there are some differences between

them. bytes used to store a fixed-sized character set while the string is used to store

the character set equal to or more than a byte. The length of bytes is from 1 to 32,

Start Your Coding Journey Now!▲


while the string has a dynamic length. Byte has the advantage that it uses less gas, so

Login Register
better to use when we know the length of data. HIDE AD

https://www.geeksforgeeks.org/solidity-types/ 1/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks

Enums : It is used to create user-defined data types, used to assign a name to an

integral constant which makes the contract more readable, maintainable, and less

Read Discuss Courses Practice Video


prone to errors. Options of enums can be represented by unsigned integer values

star ting from 0.

Example : 

In the below example, the contract Types initializes the values of different types of

Values Types.

QuickNode -
Learn.Build.Scale
A Full Suite of Blockchain APIs. Build the
Future of Web3 with the Ease of Web2

Solidity

// Solidity program to demonstrate


// value types
pragma solidity ^ 0.5.0;   
   
// Creating a contract
contract Types {   
Data
  Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+
    // Initializing Bool variable
    bool public boolean = false;
    
    // Initializing Integer variable
    int32 public int_var = -60313;
 
    //  Initializing String variable
    string public str = "GeeksforGeeks";
 
    // Initializing Byte variable
Start Your Coding Journey Now!
    bytes1 public b = "a";
      HIDE AD

https://www.geeksforgeeks.org/solidity-types/ 2/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks

    // Defining an enumerator


    enum my_enum { geeks_, _for, _geeks } 
 
ReadDefining
    // Discuss Coursesto return
a function Practice Video
    // values stored in an enumerator
    function Enum() public pure returns(
      my_enum) {   
        return my_enum._geeks;   
    }   
}

Output :

Reference Types

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-types/ 3/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks

Reference type variables store the location of the data. They don’t share the data

directly. With the help of reference type, two different variables can refer to the same

Read Discuss Courses Practice Video


location where any change in one variable can affect the other one. Reference types in

solidity are listed below: 

Arrays : An array is a group of variables of the same data type in which the variable

has a par ticular location known as an index. By using the index location, the desired

variable can be accessed. The array size can be fixed or dynamic.

Strings : Strings are like arrays of characters. When we use them, we might occupy

bigger or shor ter storage space.

Struct : Solidity allows users to create and define their own type in the form of

structures. The structure is a group of different types even though it ’s not possible to

contain a member of its own type. The structure is a reference type variable that can

contain both value type and reference type

Mapping : Mapping is the most used reference type, that stores the data in a key-

value pair where a key can be any value type. It is like a hash table or dictionar y as in

any other programming language, where data can be retrieved by key.

Example : In the below example, the contract Types initializes the values of various

Reference Types.

Solidity

// Solidity program to demonstrate


// Reference Types
pragma solidity ^0.4.18;
  
// Creating a contract
contract mapping_example {
 
    // Defining an array   
    uint[5] public array
      = [uint(1), 2, 3, 4, 5] ;
     
    // Defining a Structure
    struct student {
        string name;
        string subject;
        uint8 marks;
    }
 
Start Your Coding Journey Now!
    // Creating a structure object HIDE AD

https://www.geeksforgeeks.org/solidity-types/ 4/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks

    student public std1;


 
    // Defining a function to return
Readvalues
    // Discuss
of the Courses
elements ofPractice Video
the structure
    function structure() public view returns(
      string memory, string memory, uint){
        std1.name = "John";
        std1.subject = "Chemistry";
        std1.marks = 88;
        return (
          std1.name, std1.subject, std1.marks);
    }
     
    // Creating a mapping
    mapping (address => student) result;
    address[] student_result;
}

 Output : 

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-types/ 5/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks

Like 7

Read Discuss Courses Practice Video

Next

How to Install Solidity in Windows?

Related Articles

1. Solidity - Functions

2. What are Events in Solidity?

3. Solidity - Inheritance

4. Solidity - Polymorphism

5. Solidity - View and Pure Functions

6. Solidity - Encapsulation

7. How to Install Solidity in Windows?

8. Solidity - While, Do-While, and For Loop

9. Solidity - Break and Continue Statements

10. Solidity - Variables

Ar ticle Contributed By :

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-types/ 6/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks

jeeteshgavande30
@jeeteshgavande30
Read Discuss Courses Practice Video

Vote for difficulty

Current difficulty : Basic

Easy Normal Medium Hard Expert

Improved By : sweetyty, bahadorgh

Article Tags : Solidity-Basics, Blockchain, Solidity

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Start YourAdvertise
Coding Journey Now!
with us Video Tutorials
HIDE AD

https://www.geeksforgeeks.org/solidity-types/ 7/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks

Courses

Read Discuss
News
Courses Practice Video
Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Web Development Contribute


Web Tutorials Write an Article
Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/solidity-types/ 8/8
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Jean Cvllr Follow

Aug 1, 2019 · 7 min read · · Listen

Save

Solidity Tutorial: all about Structs

Structs are a way to define new custom types in Solidity. The Solidity documentation
define them as “objects with no functionalities”, however, they are more than that.

Like in C, structs in Solidity are a collection of variables (that can be of different types)
under a single name.

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 1/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

This enable you to group many variables of multiple types into one user defined type.

Table of Contents
1. Basic of Structs

2. How to define a new Struct type?

3. How to declare a new variable of type Struct?

4. Struct members types

5. Structs + Mappings and Arrays = the good mix

6. Storage, Memory and Calldata with Structs

7. The ‘delete’ keyword

8. What you can’t do with Structs?

1. Basic of Structs

struct Account {
uint balance;
uint dailylimit;
}

We can treat a struct like a value type such that they can be used within arrays and
mappings.

Account my_account = Account(0, 10);


function setBalance(uint new_balance) public {
my_account.balance = new_balance;
}

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 2/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

2. How to define a new Struct type?


You define a struct in Solidity with the struct keyword, followed by the struct name
and a pair of curly braces.

Within the curly, you must define the struct members, which consists of variables
names along their types.

struct Instructor {
uint age;
uint first_name;
uint last_name;
}

3. How to declare a new variable of type Struct ?


I consider 3 different ways to define a variable of struct types:

1. the procedural way.

2. the readable way.

3. the shorter way.

// 1) The procedural way


function method_1(address _address, uint _age, string _first_name,
string _last_name) {

Instructor memory instructor = instructors[_address];


instructor.age = _age;
instructor.first_name = _first_name;
instructor.last_name = _last_name;
instructorAccounts.push(_address) — 1;
}
// 2) The readable way
function method_2(address _address, uint _age, string _first_name,
string _last_name) {
https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 3/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

instructors[_address] = Instructor(
{
age: _age,
first_name: _first_name,
last_name: _last_name
}
);

instructorAccounts.push(_address) — 1;
}

// 3) The shorter way


function method_3(address _address, uint _age, string _first_name,
string _last_name) {

instructors[_address] = Instructor(_age, _first_name, _last_name);


instructorAccounts.push(_address) — 1;
}

The readable and shorter way are similar to how you instantiate a struct in Rust.

4. Struct members types


The members of a struct can be of any type (except the struct itself, which will give a
recursive struct, see example at the end).

Simple Members Types


(uint / int, bool, address, string, etc…)

Complex Members types


Struct can also contain array and mapping (including an array of its own struct type).
The code snippet below extends our previous example, renaming the Instructor and
considering it is a researcher.

struct Researcher {

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 4/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

uint age;
string first_name;
string last_name;
address researcher_address;
// List of academic articles published by the Researcher
string[] academic_papers;
// List of researchers that can peer-review the Researcher's
// academic articles before publishing
Researcher[] peer_reviewers;
// If an address is mapped to `true`, the Researcher can review
// the academic papers of the Researcher
// associated with the address
mapping(address => bool) can_peer_review;

NB: a Struct can contain either a fixed or dynamic size array of its own type.

5. Structs + Mappings and Arrays = the good mix


Structs work really well with mappings and arrays, although it is a bit complex initially
to get used to it. Some good things to know about Structs when the two previously
cited:

Structs can be used inside mappings and arrays as ValueType.

Structs can contain themselves mappings and arrays.

A struct can contain a dynamic sized array of its own type.

Use Structs as ValueTypes in mappings.


The declaration below is a mapping that reference each Instructor by their ethereum
address.

mapping(address => Instructor) instructors;

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 5/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

You can use this mapping to lookup a specific instructor with their ethereum address
and retrieve their informations. The function below implements this functionality by
returning a tuple that contains the instructor’s age, first name and last name.

pragma solidity ^0.5.0;


contract Course {

struct Instructor {
uint age;
string first_name;
string last_name;
}

mapping(address => Instructor) instructors;

function getInstructorInfos(address _instructor_address) public


view returns (uint, string memory, string memory) {

uint _age = instructors[_instructor_address].age;


string memory _first_name =
instructors[_instructor_address].first_name;
string memory _last_name =
instructors[_instructor_address].last_name;

return (_age, _first_name, _last_name);


}

You could also write the the _age , _first_name and _last_name directly in the return

statement for brevity, as shown below.

function getInstructorInfos(address _instructor_address) public view


returns (uint, string memory, string memory) {

return (
instructors[_instructor_address].age,
instructors[_instructor_address].first_name,
instructors[_instructor_address].last_name
);
}

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 6/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

Going back to our previous example, you can’t return the mapping and iterate through
all the instructors (because a mapping contains all the possible values by default).

Instead, you would need the following protocol:

1. save all the Instructor ‘s addresses who registered in your contract in an array.

address[] public instructorAccounts;

2. Iterate through all the addresses stored he array

for (uint i = 0; i <= instructorAccounts.length; i++) {

// logic goes here


}

3. Retrieve the information in the mapping based on the instructor’s address that you
iterated in your mapping.

6. Storage, Memory and Calldata with Structs


If you assign the Struct type to a local variable, you always have to mention the data
location: storage, memory or calldata.

Storage
If storage is specified, this will only stores a reference (It will not copy the struct).
Assignments to the members of the local variable will write and modify the state. Here
is a simple example.

contract Course {
struct Professor {
uint age;
https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 7/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

string name;
}

string constant course_name = "Painting";


Professor public module_leader;

constructor() public {
module_leader.age = 138;
module_leader.name = "Pablo Picasso";
}
function modifyModuleLeader(uint _age, string memory _name) public {
Professor storage new_module_leader = module_leader;
new_module_leader.age = _age;
new_module_leader.name = _name;
}
}

Try deploying and running the following code on Remix. If you click on the
module_leader variable (in blue) after the contract is deployed, the values of Struct
member defined in the constructor will be returned.

Then 1) run the function modifyModuleLeader() (in orange on the left) by assign new
values to its parameters age and name and 2) click again on the module_leader
variable in blue.

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 8/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

The modifyModuleLeader() function writes to the state and overwrite the contract’s storage.

As you can see, using the storage keyword modify the contract’s storage value. The
members value of the module_leader struct have been modified because the storage

keyword is a direct pointer the state variable module_leader .

Professor storage new_module_leader = module_leader;

The function below would do exactly the same, but it is simply to explain the idea of
storage .

function modifyModuleLeader(uint _age, string memory _name) public {


module_leader.age = _age;
module_leader.name = _name;
}

Memory
You can try to reuse the previous example. Change the keyword storage by memory and
you will see that the local state variable module_leader is not overwritten.

Using the memory keyword simply copy the struct in memory. The example below is
self explanatory:

struct Student {
uint age;
string name;
https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 9/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

Student[] public students_enrolled;

function addStudentToCourse(uint _age, string memory _name) public {


Student memory new_student = Student(_age, _name);
students_enrolled.push(new_student);
}

When declaring a struct with 3 members of type uint each, it might be necessary
that their bytes length is uint128, uint128, uint256 (in this order) , to ensure that the
struct fills one 32bytes row in storage. Otherwise, padding applies.

7. The ‘delete’ keyword


You can use the Solidity built-in function delete on a variable of Struct type to reset all
its members (This will act like if the variable would be declared as a Struct without
assigning any value to its members).

// Do not set this function as `public` in a real smart contract !!


function resignModuleLeader() public {
delete module_leader;
}

delete has no effects on mappings. So if you delete a struct, it will reset all members that
are not mappings and also recurse into the members unless they are mappings.

8. What you can’t do with Structs?

Recursive Structs
A Struct is said recursive when it contains within its definition a member variable in
its own type.

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 10/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

We naturally understand why this is not possible: a struct can’t contain a member of its
own type because the size of the struct has to be finite.

The Remix compiler would throw an ErrorType as displayed below.

Let’s use the example above to better understand the problem.

Imagine we want to create a new player: Christiano Ronaldo ! We would then create a
new variable _Christiano_Ronaldo and assign to him some values.

Each FootballPlayer (the struct), has a name (a string), an age (an uint) and a mentor
(another FootballPlayer, so the struct itself).

The problem here is that since every football player has a mentor being a football
player itself, the definition of the variable would never end.

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 11/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

struct FootballPlayer {
string name;
uint age;
FootballPlayer mentor;
}

FootballPlayer _Christiano_Ronaldo = FootballPlayer(


{
name: "Christiano Ronaldo",
age: 34,
mentor: _Ronaldinho {
// The Struct would call itself recursively
// This would go over and over and would never end
}
}
);

recursive-struct-fun-example1.md hosted with ❤ by GitHub view raw

For a bit of fun, the in-depth look at our variable _Christiano_Ronaldo would look
something like this:

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 12/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

_Christiano_Ronaldo {

name: "Christiano Ronaldo",


age: 34
mentor: _Ronaldinho {

name: "Ronaldinho",
age: 38,
mentor: _Maradonna {

name: "Diego Maradonna",


age: 58,
mentor: _Pelé {

name: "Edson Arantes do Nascimento",


age: 78,
mentor: _God {

name: "unknown",
age: ∞,
mentor: _Unknown {

name: ...,
age: ...,
mentor: ... {

name: ...
age: ...
mentor: ... {

...
...
... {

...
...
... {

// Never ending, not enough data to go back so far in time...

} // <- Basically, we would never reach this final bracket

recursive-struct-fun-example2.md hosted with ❤ by GitHub view raw

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 13/14
2/12/23, 7:38 PM Solidity Tutorial: all about Structs | by Jean Cvllr | Medium

Struct as KeyType in mappings


A Struct can’t be used as a KeyType of a mapping. Otherwise, the compiler will throw
the following error: “Parser Error: Expected Elementary type name for mapping key type”

References
https://www.youtube.com/watch?v=t0DE5ytTcvs

Programming

Open in app Sign up Sign In

Search Medium

About Help Terms Privacy

Get the Medium app

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e 14/14
2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Jean Cvllr Follow

Aug 1, 2019 · 9 min read · · Listen

Save

Solidity Tutorial: all about Enums

The word Enum in Solidity stands for Enumerable. They are user defined type that
contain human readable names for a set of constants, called member. The data
representation for an enum is the same as the one in the C language.

Table of Contents
1. How and When to create Enums?

2. Enums explained with a card deck

3. Accessing an Enum value

4. Modifying an enum value


https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 1/14
2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

5. Transition through different Enums values

6. Using Enums with modifiers

7. Represent Enums as Strings

8. Using Hash Functions with Enums

9. Use Enums as a KeyType in Mappings

10. What you can’t do with Enums in Solidity?

1. How and When to create Enums?

A classical example of an Enum would be a deck of


card, to represent:

> The suits (Spades, Clubs, Diamonds, Hearts).

> The ranks / values (2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, King,


Queen, Ace).

enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,
Jack, King, Queen, Ace }
enum Suit { Spades, Clubs, Diamonds, Hearts }

Note 1 : you can’t use numbers (positive or negative) or boolean (true or false in
lowercase) as members for an enum . However, True and False (Capitalised) are
accepted.

Note 2 : you do not need to end the enum declaration with a semicolon. The compiler
uses the semicolon ; and curly brackets {} to determine the scope of the code it’s
applied to.
https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 2/14
2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

- The semicolon determines the end of single instructions or declarations.

- The curly brackets determine the the start and end of arbitrary numbers of
instructions or declarations, like functions, modifiers, structs, enums and the contract
itself.

An enum needs at least one member to be defined. However, they are useful for
defining a series of predefined values (or out of a small set of possible values).

Here are few other examples of possible enum in Solidity.

enum Direction { Left, Right, Straight, Back }


enum ContractType { permanent, temporary, apprentice }
enum State { Created, Locked, Inactive }
enum Status { ON, OFF }

Enums are especially useful when we need to specify the current state / flow of a smart
contract. For instance, if a smart contract needs to be turned on in order to be ready to accept
deposits from users.

Status constant defaultstatus = Status.OFF;

Using our previous example of the Status enum, you can modify its value as follow:

function turnOn() public { status = Status.ON; }


function turnOff() public { status = Status.OFF; }

However, this is not a good practice, as it makes our code really repetitive. If we have
an enum with a lot of value, we would need to create a function for each possible
member of the enum.

2. Enums explained with a card deck

https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 3/14


2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

A “standard” deck of playing cards consists of 52 cards in each of the 4 suits of Spades,
Hearts, Diamonds, and Clubs. Each suit contains 13 cards: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10,
Jack, Queen, King.

This would be a lot of functions !

Imagine now that we want to create a variable myCard , and a function that would store
the card Suit and Value that we would like to choose.

We would need to create 52 functions (one for each possible card) to achieve this
objective. Or we could create a function pick_a_card() that would accept two inputs :
the Suit and the Value we want to select. Let’s look at our code example below.

contract CardDeck {
enum Suit { Spades, Clubs, Diamonds, Hearts}
enum Value {
Two, Three, Four, Five, Six,
Seven, Eight, Nine, Ten,
Jack, King, Queen, Ace
}
struct Card {
Suit suit;
Value value;
}

https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 4/14


2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

Card public myCard;

function pick_a_card(Suit _suit, Value _value) public returns


(Suit, Value) {
myCard.suit = _suit;
myCard.value = _value;
return (myCard.suit, myCard.value);
}
}

Here we set up a Card struct, a custom type that include two properties with our two
previously created enum : Suit and Value .

Then we create our function pick_a_card() with two parameters : a Suit and a Value .

If we deploy our contract on Remix, we will see that the two inputs of our functions are
actually integers (see picture below). Why is that ?

https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 5/14


2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

Enum are explicitly convertible to and from all integer type. The options are represented by
subsequent unsigned integer values starting from 0, in the order they are defined.

Under the hood, enums are integers, not strings. Solidity will automatically handle
converting name to ints. In the case of our Suit enum, the index of our members are :
0= Spades, 1= Clubs, 2 = Diamonds, 3 = Hearts. Same for our Value enum : 0 = One, 1 =
Two, 2 = Three, etc…

If we would like to pick the Queen of Diamonds, we would use 1, 11 as an input in


Remix.

Therefore, we could create our function using integers instead of enums as function
parameters. Let’s create another function to change the suit of our card.

function changeSuit(uint _value) public {


myCard.suit = Suit(_value);
}
function changeSuit(Suit _suit) public {
myCard.suit = _suit;
https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 6/14
2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

3. Accessing an Enum value


There are two methods to access the value of a variable defined as an enum.

Method 1 : using public to create a getter

Status public status;

Using the public keyword in front of your variable name is probably the safer bet.
However, we can do it a bit more complicated to understand exactly the returned
value.

Method 2: return the enum index of a variable

Enum are explicitly convertible to and from all integer type. The options are represented by
subsequent unsigned integer values starting from 0. The integer type uint8 is large enough to
hold all enums values. If you have more than 256 values, uint16 will be used and so on.

Enums value are numbered in the order they are defined, starting at 0. To get the value
of an Enum type variable, simply write .

enum Status { ON, OFF }


Status status;
function getStatus() public view returns (Status) {
return choice;
}

https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 7/14


2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

Looking at the Remix Compiler, we would see this.

You could also return an enum value via a function by writing uint(status) .

function getStatus() public view returns (uint) {


return uint(status);
}

4. Modifying an enum value


To modify a variable enum type, you can create a setter function as follow:

enum Status { ON, OFF }


Status public status;

https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 8/14


2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

function turnOn() public pure {


status = Status.ON;
}
function turnOff() public pure {
status = Status.OFF;
}

However, we shouldn’t repeat ourselves and create a function that can modify the
status to set it either to ON or OFF. We could create this function by passing an
argument uint to the function that refers to the enum ‘s member.

function setStatus(uint new_status) public {


status = Status(new_status);
}

5. Transition through different Enums values


This is a good example of a how to move from different enums type

enum Stages {
AcceptingBlindedBids,
RevealBids,
AnotherStage,
AreWeDoneYet,
Finished
}
// This is the current stage.
Stages public stage = Stages.AcceptingBlindedBids;
function nextStage() internal {
stage = Stages(uint(stage) + 1);
}

https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 9/14


2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

6. Using Enums with modifiers


The next example (from the State Machine Example in the Solidity doc) shows how to
use an Enum as part of modifiers.

modifier atStage(Stages _stage) {


require(
stage == _stage,
"Function cannot be called at this time."
);
_;
}
// Go to the next stage after the function is done.
modifier transitionNext() {
_;
nextStage();
}
// Order of the modifiers matters here!
function bid() public payable atStage(Stages.AcceptingBlindedBids) {

// We will not implement that here


}

7. Represent Enums as Strings


So far, we have seen that enum can only be represented by their indices, which are
uint . However, it is a pain, and we could make it a bit more friendly.

We could create some getters to return the string representations of our enum. Let’s
take the example of the Suit enum. Fairly easy to represent, since there is only 4
possible value. We can write a custom function.

function getSuitKeyByValue(Suit _suit) internal pure returns (string


memory) {

// Error handling for input


require(uint8(_suit) <= 4);

// Loop through possible options


if (Suit.Spades == _suit) return "Spades";
https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 10/14
2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

if (Suit.Clubs == _suit) return "Clubs";


if (Suit.Diamonds == _suit) return "Diamonds";
if (Suit.Hearts == _suit) return "Hearts";
}
// Retrieve Suit of our card
function getSuit() public view returns (string memory) {
Suit _cardSuit = myCard.suit;
return getSuitKeyByValue(_cardSuit);
}

Let’s look at our function getSuitKeyByValue() . Our function accept an enum as an


argument, the Suit of our card. It returns the represent of our card Suit as a string.

First, we check that the value for our Suit enum we enter is not greater than 4 (among
the possibilities), otherwise, we throw an error, stop the function running and revert.

Then we loop through all the possible options using an if statement and returns a
string representation of each possible enum member .

We can use only an if statement to check via looping since there is no match loop (compared
to Javascript or Rust). See a similar concept for Rust in the following book p44 :

Blandy and Orendorff (2018) : Programming Rust: Fast, Safe system development, O’Reilly,
p44

8. Use Hash Functions with Enums


Blockchain programming is all about Hashing Functions, a key component of any
Blockchain Project.

function checkSuitValueByKey (string memory _mySuit) internal pure


returns (Suit) {

// keccak256() only accept bytes as arguments, so we need


explicit conversion
bytes memory mySuit = bytes(_mySuit);
bytes32 Hash = keccak256(mySuit);

https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 11/14


2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

// Loop to check
if (Hash == keccak256("Spades") || Hash ==
keccak256("spades")) return Suit.Spades;
if (Hash == keccak256("Clubs") || Hash == keccak256("clubs"))
return Suit.Clubs;
if (Hash == keccak256("Diamonds") || Hash ==
keccak256("diamonds")) return Suit.Diamonds;
if (Hash == keccak256("Hearts") || Hash ==
keccak256("hearts")) return Suit.Hearts;
revert();
}

function changeSuit(string memory _suit) public {


myCard.suit = checkSuitValueByKey(_suit);
}

In this example, we have modified our changeSuit() function by enabling to enter a


string instead of an uint . The function checkSuitValueByKey() simply enables this
feature.

checkSuitValueByKey() takes first our input string and convert it into bytes in order to
hash it with keccak256() . We then compare the obtained Hash with the Hash of each
possible options : Spades, Clubs, Diamonds and Hearts (We also made the case for
lowercase strings, so “spades”, “clubs”, “diamonds” and “hearts”.

If something is found, we return the string representation associated with enum


member. If nothing is found, we revert and stop the function execution. Try to enter
“Triangle” in Remix in the changeSuit() function and you will see the following error
message :

“ transact to CardDeck.changeSuit errored: VM error: revert. revert The transaction has been
reverted to the initial state. “

9. Use Enums as a KeyType in Mappings

Warning ! Experimental (see this answer on StackExchange)

https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 12/14


2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

Normally, enums are not allowed to be used as a KeyType inside mappings. However, a
workaround could be used.

Since enums members are represented by uint , we can use uint inside our mapping
to a mapping of Enum > Enum. Consider the following code example :

enum Suit { Spades, Clubs, Diamonds, Hearts}


enum Value {
Two, Three, Four, Five, Six,
Seven, Eight, Nine, Ten,
Jack, King, Queen, Ace
}
// Suit Value
// | |
// v v
mapping (uint8 => uint8) cardDeck;

10. What you can’t do with Enums in Solidity?


Implicit conversion is not allowed !

Enums can’t be used as KeyTypes in mappings !

You can’t return an Enum within a function. This is because Enums types are not
part of the ABI.

You can’t define Enums in an interface if your Solidity compiler version is less than
0.5.0.

Programming

https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 13/14


2/12/23, 7:42 PM Solidity Tutorial: all about Enums | by Jean Cvllr | Medium

About Help Terms Privacy

Open in app Sign up Sign In


Get the Medium app
Search Medium

https://jeancvllr.medium.com/solidity-tutorial-all-about-enums-684adcc0b38e#:~:text=The word Enum in Solidity,one in the C language. 14/14


2/12/23, 7:44 PM Enum in solidity from zero to hero | by Mahmoud Mourad Dev | Coinmonks | Medium

Published in Coinmonks

Mahmoud Mourad Dev Follow

Oct 14, 2022 · 4 min read · Listen

Save

Enum in solidity from zero to hero

Enum
Enums are one way to create user-defined type in solidity

https://medium.com/coinmonks/enum-in-solidity-from-zero-to-hero-f709796b1670 1/9
2/12/23, 7:44 PM Enum in solidity from zero to hero | by Mahmoud Mourad Dev | Coinmonks | Medium

Enums are value type comprising a pre-defined list of constant values

constant values with an enum can be explicity converted to integer

Each constant values gets an integer value start from zero

Enums require at least one number

Enums cannot have more than 256 members

You can’t use numbers (positive or negative) or boolean (true or false in lowercase)
as members for an enum. However, True and False (Capitalised) are accepted.

You do not need to end the enum declaration with a semicolon. The compiler uses
the semicolon ; and curly brackets {} to determine the scope of the code

Using type(name of enum).min get the smallest value

Using type(name of enum).max get the largest value

Example of enum

enum status {ON,OFF}


status lightOn=status.ON;
status lightOff=status.OFF

https://medium.com/coinmonks/enum-in-solidity-from-zero-to-hero-f709796b1670 2/9
2/12/23, 7:44 PM Enum in solidity from zero to hero | by Mahmoud Mourad Dev | Coinmonks | Medium

enum example in solidity

Shipment Example

https://medium.com/coinmonks/enum-in-solidity-from-zero-to-hero-f709796b1670 3/9
2/12/23, 7:44 PM Enum in solidity from zero to hero | by Mahmoud Mourad Dev | Coinmonks | Medium

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.16;
contract enumTest{
enum shipMent{notFound,approved,rejected}
shipMent status;
shipMent defaultStatus=shipMent.notFound;
function setToApproved() public{
status=shipMent.approved;
}
function setToRejected() public{
status=shipMent.rejected;
}
function getChoise() public view returns(shipMent){
return status;
}
function getDefaultStatus() public view returns(shipMent){
return defaultStatus;
}
function getSmallestValue() public pure returns(shipMent){
return type(shipMent).min;
}
function getLargestValue() public pure returns(shipMent){
return type(shipMent).max;
}
}

Solidity document Example

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.8;

contract test {
enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }
ActionChoices choice;
ActionChoices constant defaultChoice = ActionChoices.GoStraight;

function setGoStraight() public {


choice = ActionChoices.GoStraight;
}

function getChoice() public view returns (ActionChoices) {


https://medium.com/coinmonks/enum-in-solidity-from-zero-to-hero-f709796b1670 4/9
2/12/23, 7:44 PM Enum in solidity from zero to hero | by Mahmoud Mourad Dev | Coinmonks | Medium

return choice;
}

function getDefaultChoice() public pure returns (uint) {


return uint(defaultChoice);
}

function getLargestValue() public pure returns (ActionChoices) {


return type(ActionChoices).max;
}

function getSmallestValue() public pure returns (ActionChoices) {


return type(ActionChoices).min;
}
}

Example from geeks for geeks

// Solidity program to demonstrate


// how to use 'enumerator'
pragma solidity ^0.5.0;
// Creating a contract
contract Types {
// Creating an enumerator
enum week_days
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
// Declaring variables of
// type enumerator
week_days week;

week_days choice;
// Setting a default value
week_days constant default_value
= week_days.Sunday;

// Defining a function to
// set value of choice
https://medium.com/coinmonks/enum-in-solidity-from-zero-to-hero-f709796b1670 5/9
2/12/23, 7:44 PM Enum in solidity from zero to hero | by Mahmoud Mourad Dev | Coinmonks | Medium

function set_value() public {


choice = week_days.Thursday;
}
// Defining a function to
// return value of choice
function get_choice(
) public view returns (week_days) {
return choice;
}

// Defining function to
// return default value
function getdefaultvalue(
) public pure returns(week_days) {
return default_value;
}
}

Juice size example

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract test {

// predefined value enum EnumName


enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
//Enum variable
FreshJuiceSize choice;
// access default choice
FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;
function setLarge() public {
choice = FreshJuiceSize.LARGE;
}
function getChoice() public view returns (FreshJuiceSize) {
return choice;
}
function getDefaultChoice() public pure returns (uint) {
return uint(defaultChoice);
}
}

https://medium.com/coinmonks/enum-in-solidity-from-zero-to-hero-f709796b1670 6/9
2/12/23, 7:44 PM Enum in solidity from zero to hero | by Mahmoud Mourad Dev | Coinmonks | Medium

Shipped Status

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Enum {
//enum representing shipping status
enum Status {Pending,Shipped, Accepted, Rejected,Canceled}
//enum variable, Default value pending =0
Status public status;
function getChoice() public view returns (Status) {
return status;
}
// Update status by passing uint into input
function set(Status _status) public {
status = _status;
}
//You can update to a specific enum like this
function cancel() public {
status = Status.Canceled;
}
// delete resets the enum to it's first value, 0
function reset() public {
delete status;
}
}

Move between enum elements

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Enum {
enum Status {Pending,Shipped, Accepted, Rejected,Canceled}
Status public status;
function nextChoice() public {
status=Status(uint(status)+1);
}
}

https://medium.com/coinmonks/enum-in-solidity-from-zero-to-hero-f709796b1670 7/9
2/12/23, 7:44 PM Enum in solidity from zero to hero | by Mahmoud Mourad Dev | Coinmonks | Medium

Explicit Convertion allowed

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract EnumTest {
enum Status {Pending,Shipped, Accepted, Rejected,Canceled}
function explicitConvertion() public pure returns(uint){
return uint(Status.Accepted);
}
}

Example from stack exchange

// Lets see Enums which are often used for state machine like this
enum State { Created, Locked, Inactive };

// post this a variable can be Declared like this


State public state;

// Initializing the state can be done like this


state = State.Created;

// It is important to note that enums can be explicitly converted to


ints like this
uint createdState = uint(State.Locked);

Enum & mapping

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Enum {
enum Status {Pending,Shipped, Accepted, Rejected,Canceled}
mapping(uint=> Status) enumMappnig;
}

Enum & struct

https://medium.com/coinmonks/enum-in-solidity-from-zero-to-hero-f709796b1670 8/9
2/12/23, 7:44 PM Enum in solidity from zero to hero | by Mahmoud Mourad Dev | Coinmonks | Medium

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Enum {
Open in app Get unlimited access
enum Status {Pending,Shipped, Accepted, Rejected,Canceled}
struct enumStruct{
Search Medium
Status _status;
}
}

New to trading? Try crypto trading bots or copy


trading

Enumeration Enumerable Solidity

21

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/coinmonks/enum-in-solidity-from-zero-to-hero-f709796b1670 9/9
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

Published in Coinmonks

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Jean Cvllr Follow

Sep 1, 2020 · 8 min read · · Listen

Save

Solidity Tutorial: all about Mappings

The School Cloackroom by Malcolm Evans, a cartoon drawing used as an analogy to explain mappings in
Solidity (taken from https://www.cagle.com/tag/cloakroom/)

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 1/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

Table of Content
Introduction to mappings

What mappings are used for?

How mappings are represented in storage?

Key and Values types allowed

Operations on Mappings

Nested Mappings

Mappings as function parameters

Structs as value types of mappings

Mappings Limitations

Introduction to mappings
Mappings in Solidity are similar to the concept of hash map in Java or dictionary in C
and Python. They act like hash tables, although they are slightly different.

There is nothing better than an analogy with the real world to understand what are
mappings in Solidity and how they behave. The following example was taken from a
Reddit post.

A hashmap (= mapping) is like a cloakroom. You hand


your coat over and get a ticket. Whenever you give
that ticket back, you immediately get your coat. You
can have a lot of coats, but you still get your coat back
immediately. There is a lot of magic going on inside the

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 2/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

cloakroom, but you don’t really care as long as you get


your coat back immediately.

Therefore, mapping as a data structure enables to find the location corresponding to a


given key in an efficient way.

What mappings are used for?


Mappings are useful for associations, like associating a unique Ethereum address to a
specific balance. This is the case of the standard ERC20 contract. The smart contract
keeps track of how many tokens a user owns by using a mapping.

contract ERC20 is Context, IERC20 {


using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 3/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

...
}

Another example where a mapping could be used would be to manage and keep track
wich users / addresses are allowed to send ether to the contract.

mapping(address => bool) allowedToSend;

Here is another example of how to define a mapping in Solidity. The code sample
below would enable to associate a user level to an ethereum address for a simple game
written in Solidity.

mapping(address => uint) public userLevel;

How mappings are represented in Storage?


Mappings are represented differently in storage than other variable types.

As we said, mappings enable to find the location of a value in storage, given a specific
key. Hashing the key is a good start !

In Solidity, mappings values are represented by the hash of their keys. The 32 byte
hash is an hexadecimal value that can be converted to a decimal number. This number
represents the slot number where the value for a specific key is hold in storage.

Let’s look at a basic example with the code snippet below.

contract StorageTest {
uint256 a; // slot 0
uint256[2] b; // slots 1-2

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 4/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

struct Entry {
uint256 id;
uint256 value;
}
Entry c; // slots 3-4
Entry[] d; // slot 5 for length, keccak256(5)+ for data
mapping(uint256 => uint256) e;
mapping(uint256 => uint256) f;
}

In the above code:

the “location” for e is slot 6

the location for f is slot 7

but nothing is actually stored at those locations ! There’s no length to be stored, and
individual values need to be located elsewhere.

In fact when mapping is declared, space is reserved for it sequentially like any other
type, but the actual values are stored in a different slot.

Finding the location in storage of a mapping key

To find the location of a specific value within a mapping, the key (1st !) and the slot of
the mapping variable (2nd) are hashed together (after being concatenated).

The hash obtained correspond to the location in storage where the value associated to
this key in the mapping is stored. In fact, a 32 byte hash contains hexadecimal
characters, that can be converted to a decimal number (that represents the storage
slot for a specific key in the mapping). Here is an example.

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 5/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

mapping(address => uint) public balances; // slot 2

The variable balances is located in slot 2 in storage. As seen before, we concatenate


both the key with the slot number, as in the formula below:

So in conclusion:

the token balance associated with the address


0x123456…7890 can be found in the contract’s storage
slot nb 11233648340…332173
NB: Note the value of slot and keys are represented in hexadecimals., and left padded with
empty bytes.

Mapping do not have a length


As seen before, there is no concept of a key and a value “by itself”.

The data for a key is not stored in a mapping, but rather its keccak256 hash is used for
storing the value the key data references to.

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 6/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

Because of this, mappings do not have a length.

NB: the same principle applies to nested mappings. We will talk about it later.

Key and value types allowed


The table below lists all the possible variable types that can be used when declaring a
mapping.

mapping (KeyType => ValueType) mappingName;

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 7/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

Operations on Mappings

Getter - Reading value for a specific key


To obtain the value associated to a specific key as follow.

function currentLevel(address userAddress)


public
view
returns (uint)
{
return userLevel[userAddress];
}

However, there is a better for reading a value a mapping. Like for any other variable,
the keyword public creates automatically a getter function in Solidity.

The same applies to mapping . By adding the keyword public in the mapping definition,
this will create a getter function. You will only need to pass the key as a parameter to
the getter to return the _ValueType.

mapping(address => uint) public userLevel;

Setter — Writing value for a specific key


Following our example for the getter function, you can set the value for a specific key
as follow:

function setUserLevel(address _user, uint _level)


public
{
userLevel[_user] = _level;
}

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 8/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

The code above enables to set the level of an “imaginary” game for a specific user.

Finding the storage slot for a specific key


The code snippet below offer the functionality describe above. It enables to find in
which storage slot the value associated to a specific key is stored.

function findMapLocation(uint256 slot, uint256 key) public pure


returns (uint256) {
return uint256(keccak256(abi.encode(key, slot)));
}

Nested Mappings
If you have a look at the table above, for keys and value types allowed, you will notice
that:

in a mapping, a key can be associated to a value of


type mapping
So mappings can be nested !

A great practical example of a nested mapping can be found in the ERC20 smart
contract. An address can grant other addresses the right to spend a certain amount of
tokens.

mapping (address => mapping (address => uint256)) private _allowances;

In relational database architecture, this relationship is called one-to-many: an owner

can grant multiple spenders to spend some tokens on his behalf.

Getter function for nested mapping

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 9/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

If the _ValueType of a mapping turns up to be a mapping too, then the getter function
will have a single parameter for every _KeyType recursively.

Let’s go back to our previous allowances example from the ERC20 contract. The
function allowance(...) defined in line 125 takes two parameters: owner and spender .

Based on our explanation based, we can understand that these are our single
parameter defined for every key type recursively.

function allowance(address owner, address spender)


public
view
virtual override
returns (uint256)
{
return _allowances[owner][spender];
}

How nested mappings are represented in storage?


A nested mapping follows the same pattern as a regular mapping, but in a recursive
fashion.

Take the hash of the key + slot => we get our resulting result (=key 2)

Take the resulting hash and hash it with our key 2 result

Mappings as function parameters


This is a difficult topic, but we will attempt to discuss about it.

Mappings can be passed as parameters inside functions, but they must satisfy the
following two requirements.

Mapping can be used as parameter only for private and internal functions.

The data location for the function parameter (our mapping) can only be storage.

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 10/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

Iterating through a mapping

Why you cannot iterate through a mapping?


Because the 32 bytes hash obtained via keccak256(key, slot) is an hexadecimal value
that can be converted to decimals, this lead to an immense possible range. The
decimal number obtained can be somewhere in the range of 0 to 2²⁵⁶.

This is why you cannot iterate through a mapping. There would be too many possible
keys ( = also read slots) to iterate. As a result:

mappings are virtually initialised. In other words, all


possible variables are initialised by default.
So by default, when a mapping is declared, every possible key is mapped to a value
whose bytes representation are all zeros.

How to iterate through a mapping in Solidity?


We have already seen that because of their nature, it is impossible to iterate through a
mapping. The reason being that when a mapping is defined, all its key are virtually
initialised.

In other words, every possible key exist by default, and is mapped to a default zero /
null value.

However, it is possible to implement a data structure on top of a mapping, so that we


can iterate through it.

Let’s take an example that use an uint as a key. The solution is to have a counter that
tells you the length of the mapping where the last value is stored.

contract IterableMapping {
mapping(uint => address) someList;
uint public totalEntries = 0;
https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 11/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

function addToList() public returns(uint) {


someList[totalEntries] =
address(0xABaBaBaBABabABabAbAbABAbABabababaBaBABaB);
return ++totalEntries;
}
}

A note on Struct as a value type for mappings


An important side note worth mentioning relates to mappings that have a struct as a
value type.

If the struct contains an array, it will not be returned via the getter function created by
the “public” keyword. You have to create your own function for that, that will return an
array.

Mappings Limitations
Mappings do not come without pitfalls. Here are some of them.

You can’t not define variables as the _ValueType of a mapping. Remix will throw a
TypeError as shown below:

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 12/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

As seen before, you can’t iterate in a mapping directly

It is impossible to retrieve a list of values or keys, like you would do it in Java for
instance. The reason is still the same: all variables already initialised by default.
So it’s internally not possible.

Mappings can’t be passed as parameters inside public and external functions in


smart contracts.

Mappings can’t be used as return value for function

Join Coinmonks Telegram Channel and Youtube


Channel get daily Crypto News
Also, Read
Copy Trading | Crypto Tax Software

Grid Trading | Crypto Hardware Wallet

Best Crypto Exchange | Best Crypto Exchange in India

Best Crypto APIs for Developers

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 13/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium

Crypto Telegram Signals | Crypto Trading Bot

Best Crypto Lending Platform

An ultimate guide to Leveraged Token

Best VPNs for Crypto Trading

Crypto Trading Signals for Huobi | HitBTC Review

TraderWagon Review | Kraken vs Gemini vs BitYard

How to trade Futures on FTX Exchange

OKEx vs KuCoin | Celsius Alternatives | How to Buy VeChain

3Commas vs. Pionex vs. Cryptohopper

How to use Cornix Trading Bot

Bitget Review | Gemini vs BlockFi cmd| OKEx Futures Trading

10 Best Places to Buy Crypto with Credit Card

Solidity Solidity Tutorial Smart Contracts Ethereum Blockchain

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Your email

Get this newsletter

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 14/15
2/12/23, 7:46 PM Solidity Tutorial: all about Mappings | by Jean Cvllr | Coinmonks | Medium
By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

About Help Terms Privacy

Open in app Sign up Sign In

Get the Medium app


Search Medium

https://medium.com/coinmonks/solidity-tutorial-all-about-mappings-29a12269ee14 15/15
2/12/23, 7:48 PM Mappings in Solidity Explained in Under Two Minutes | by Doug Crescenzi | Upstate Interactive | Medium

Published in Upstate Interactive

Doug Crescenzi Follow

May 23, 2018 · 3 min read · Listen

Save

Mappings in Solidity Explained in Under Two


Minutes

https://medium.com/upstate-interactive/mappings-in-solidity-explained-in-under-two-minutes-ecba88aff96e 1/5
2/12/23, 7:48 PM Mappings in Solidity Explained in Under Two Minutes | by Doug Crescenzi | Upstate Interactive | Medium

Mappings act as hash tables which consist of key types and corresponding value type
pairs. They are defined like any other variable type in Solidity:

mapping(_KeyType => _ValueType) public mappingName

example of a hash table

Mappings are incredibly useful for associations and frequently used to associate
unique Ethereum addresses with associated value types. For instance in the
blockchain-based puzzle game we built it was necessary for us to map a user’s address
to their corresponding level in the game:

mapping(address => uint) public userLevel;

https://medium.com/upstate-interactive/mappings-in-solidity-explained-in-under-two-minutes-ecba88aff96e 2/5
2/12/23, 7:48 PM Mappings in Solidity Explained in Under Two Minutes | by Doug Crescenzi | Upstate Interactive | Medium

Accessing Value Types from a Mapping with Key Types


With this mapping in place we then built a function to identify a user’s current level in
the game. Here we pass the currentLevel function an argument — i.e., a particular
user’s address — and then we use the userLevel mapping to return that user’s
associated level in the game:

function currentLevel(address userAddress) public constant returns


(uint) {
return userLevel[userAddress];
}

Using a mapping here is helpful because it can store many _KeyTypes to _ValueTypes .

In this case there are many users playing the game all at once and they can each have
their own corresponding userLevel .

A mappings default value


According to the Solidity docs, “mappings can be seen as hash tables which are virtually
initialized such that every possible key exists and is mapped to a value whose byte-
representation are all zeros.”

Essentially this means that mappings do not have a length. They also do not have a
concept of a key or a value being set. We can only use mappings for state variables that
act as storage reference types. It’s then possible to create a getter function call (like
public ) in which the _KeyType is the parameter used by the getter function in order to
return the _ValueType .

https://medium.com/upstate-interactive/mappings-in-solidity-explained-in-under-two-minutes-ecba88aff96e 3/5
2/12/23, 7:48 PM Mappings in Solidity Explained in Under Two Minutes | by Doug Crescenzi | Upstate Interactive | Medium

Let’s reflect back on our userLevel mapping from our game:

mapping(address => uint) public userLevel;

When userLevel is initialized it’s done in such a way that every possible Ethereum
address exists in the mapping and is mapped to a corresponding level of 0. Whether it’s
a random Ethereum user’s MetaMask address who perhaps has never even heard of
our game before, or maybe an arbitrary smart contract on the Ethereum blockchain
doing something totally unrelated, it doesn’t matter. Our mapping still maps
Open in app
them to a
Get unlimited access
corresponding level of 0 in our game, or more appropriately, maps to a “value whose
byte-representation
Searchare all zeros.”
Medium

Take aways
Mappings act as hash tables which consist of key types and corresponding value
type pairs

Mappings are useful because they can store many _KeyTypes to _ValueTypes

Mappings do not have a length, nor do they have a concept of a key or a value being
set

Mappings can only be used for state variables that act as storage reference types

When mappings are initialized every possible key exists in the mappings and are
mapped to values whose byte-representations are all zeros

☞ We build decentralized applications (DApps) on the Ethereum blockchain

https://medium.com/upstate-interactive/mappings-in-solidity-explained-in-under-two-minutes-ecba88aff96e 4/5
2/12/23, 7:48 PM Mappings in Solidity Explained in Under Two Minutes | by Doug Crescenzi | Upstate Interactive | Medium

Sign Up for our Monthly Email!


405 1
Email

First Name

Sign up

I agree to leave medium.com and submit this information, which will be collected
and used according to Upscribe's privacy policy.

Ethereum Solidity Dapps Decentralized Apps Blockchain

https://medium.com/upstate-interactive/mappings-in-solidity-explained-in-under-two-minutes-ecba88aff96e 5/5
2/12/23, 7:53 PM Ethereum Solidity: Memory vs Storage & When to Use Them | by Forest Fang | Coinmonks | Medium

Published in Coinmonks

Forest Fang Follow

Mar 18, 2018 · 5 min read · Listen

Save

Ethereum Solidity: Memory vs Storage & When


to Use Them

Someone asked me on Github whether we should use storage or memory keyword in


the following simplified code snippet:

https://medium.com/coinmonks/ethereum-solidity-memory-vs-storage-which-to-use-in-local-functions-72b593c3703a 1/8
2/12/23, 7:53 PM Ethereum Solidity: Memory vs Storage & When to Use Them | by Forest Fang | Coinmonks | Medium

Item memory item = Item(_price, _units);


items.push(item);
}

function getUsingStorage(uint _itemIdx)


public
// set to non-view to estimate gas
// view
returns (uint)
{
Item storage item = items[_itemIdx];
return item.units;
}

function getUsingMemory(uint _itemIdx)


public
// set to non-view to estimate gas
// view
returns (uint)
{
Item memory item = items[_itemIdx];
return item.units;
}

function addItemUsingStorage(uint _itemIdx, uint _units)


public
{
Item storage item = items[_itemIdx];
item.units += _units;
}

function addItemUsingMemory(uint _itemIdx, uint _units)


public
// set to non-view to estimate gas
// view
{
Item memory item = items[_itemIdx];
item.units += _units;
}

For getUsingStorage and getUsingMemory , I tried both storage and memory and my unit
tests were able to pass in both cases. So what’s the difference between storage and
memory anyway and when should we use them?

Discover and review best Ethereum development


tools

https://medium.com/coinmonks/ethereum-solidity-memory-vs-storage-which-to-use-in-local-functions-72b593c3703a 2/8
2/12/23, 7:53 PM Ethereum Solidity: Memory vs Storage & When to Use Them | by Forest Fang | Coinmonks | Medium

According to Solidity documentation, these two keywords are used for Reference Types

where

Complex types, i.e. types which do not always fit into 256 bits have to be handled more
carefully than the value-types we have already seen. Since copying them can be quite
expensive, we have to think about whether we want them to be stored in memory (which is
not persisting) or storage(where the state variables are held).

Every complex type, i.e. arrays and structs, has an additional annotation, the “data
location”, about whether it is stored in memory or in storage.

It is now important to look at where EVM (Ethereum Virtual Machine) stores data:

The Ethereum Virtual Machine has three areas where it can store items.

The first is “storage”, where all the contract state variables reside. Every contract has its own
storage and it is persistent between function calls and quite expensive to use.

The second is “memory”, this is used to hold temporary values. It is erased between (external)
function calls and is cheaper to use.

The third one is the stack, which is used to hold small local variables. It is almost free to use,
but can only hold a limited amount of values.

Most importantly,

If you e.g. pass such variables in function calls, their data is not copied if it can stay in
memory or stay in storage.

This is where it gets confusing:

1. The storage and memory keywords are used to reference data in storage and
memory respectively.

https://medium.com/coinmonks/ethereum-solidity-memory-vs-storage-which-to-use-in-local-functions-72b593c3703a 3/8
2/12/23, 7:53 PM Ethereum Solidity: Memory vs Storage & When to Use Them | by Forest Fang | Coinmonks | Medium

2. Contract storage is pre-allocated during contract construction and cannot be


created in function call. After all, it makes little sense to create new variable in
storage in a function if it is to be persisted.

3. Memory cannot be allocated during contract construction but rather created in


function execution. Contract state variable is always declared in storage. Again, it
makes little sense to have state variable that cannot persist.

4. When assigning a memory referenced data to a storage referenced variable, we are


copying data from memory to storage. No new storage is created.

5. When assigning a storage reference data to a memory referenced variable, we are


copying data from storage to memory. New memory is allocated.

6. When a storage variable is created in function locally by look up, it simply


reference data already allocated on Storage. No new storage is created.

To recap, refer back to the documentation:

Forced data location:

* parameters (not return) of external functions: calldata

* state variables: storage

Default data location:

* parameters (also return) of functions: memory

* all other local variables: storage

We can change data location only for parameters of functions and local variables in
function. Whenever a storage reference is casted to memory , a copy is made, and
further modification on the object does not propagate back to contract state. memory

reference can only be “assigned” to storage reference if memory data can be copied to
a pre-allocated state variable.

https://medium.com/coinmonks/ethereum-solidity-memory-vs-storage-which-to-use-in-local-functions-72b593c3703a 4/8
2/12/23, 7:53 PM Ethereum Solidity: Memory vs Storage & When to Use Them | by Forest Fang | Coinmonks | Medium

Back to our illustrative contract above, for getters:

function getUsingStorage(uint _itemIdx)


public
// set to non-view to estimate gas
// view
returns (uint)
{
Item storage item = items[_itemIdx];
return item.units;
}
function getUsingMemory(uint _itemIdx)
public
// set to non-view to estimate gas
// view
returns (uint)
{
Item memory item = items[_itemIdx];
return item.units;
}

Both functions return the same result, except in the getUsingMemory a new variable is
created and resulting in more gas used:

// getUsingStorage
"gasUsed": 21849
// getUsingMemory
"gasUsed": 22149,

On the other hand, for setters:

function addItemUsingStorage(uint _itemIdx, uint _units)


public
{
Item storage item = items[_itemIdx];
item.units += _units;
}

https://medium.com/coinmonks/ethereum-solidity-memory-vs-storage-which-to-use-in-local-functions-72b593c3703a 5/8
2/12/23, 7:53 PM Ethereum Solidity: Memory vs Storage & When to Use Them | by Forest Fang | Coinmonks | Medium

function addItemUsingMemory(uint _itemIdx, uint _units)


public
// set to non-view to estimate gas
// view
{
Item memory item = items[_itemIdx];
item.units += _units;
}

Only addItemUsingStorage modified the state variable (consuming more gas):

// addItemUsingStorage
// `units` changes in `items`
"gasUsed": 27053,
// addItemUsingMemory
// `units` does not change in `items`
"gasUsed": 22287,

So to close, the takeaways are:

1. memory and storage specifies which data location the variable refers to

2. storage cannot be newly created in a function. Any storage referenced variable in


a function always refers a piece of data pre-allocated on the contract storage (state
variable). Any mutation persists after function call.

3. memory can only be newly created in a function. It can either be newly instantiated
complex types like array/struct (e.g. via new int[...] ) or copied from a storage

referenced variable.

4. As references are passed internally through function parameters, remember they


default to memory and if the variable was on storage it would create a copy and any
modification would not persist.

https://medium.com/coinmonks/ethereum-solidity-memory-vs-storage-which-to-use-in-local-functions-72b593c3703a 6/8
2/12/23, 7:53 PM Ethereum Solidity: Memory vs Storage & When to Use Them | by Forest Fang | Coinmonks | Medium

References:

In Ethereum Solidity, what is the purpose of the "memory" keyword?


Without the memory keyword, Solidity tries to declare variables in
storage. Lead Solidity dev chriseth: "You can think…
stackoverflow.com

What does the keyword "memory" do exactly?


The Solidity FAQ on "memory" is highly recommended reading in
entirety, and a snippet is provided below. The Ethereum…
ethereum.stackexchange.com

Ethereum Solidity: Memory vs Storage & How to initialize an array


inside a struct
In Loom Network’s Telegram (which has ~8,000 members!) people ask
questions on various topics such as Loom’s roadmap…
medium.com

Join Coinmonks Telegram Channel and Youtube


Channel get daily Crypto News
Also, Read
Crypto Telegram Signals | Crypto Trading Bot

Copy Trading | Crypto Tax Software

Grid Trading | Crypto Hardware Wallet

Best Crypto Exchange | Best Crypto Exchange in India

https://medium.com/coinmonks/ethereum-solidity-memory-vs-storage-which-to-use-in-local-functions-72b593c3703a 7/8
2/12/23, 7:53 PM Ethereum Solidity: Memory vs Storage & When to Use Them | by Forest Fang | Coinmonks | Medium

Best Crypto APIs for Developers

Best Crypto Lending Platform

An ultimate guide to Leveraged Token

Best VPNs for Crypto Trading

Best Crypto Analytics or On-Chain Data | Bexplus Review

10 Biggest NFT MarketPlaces to Mint a Collection

AscendEx Staking | Bot Ocean Review | Best Bitcoin Wallets

Bitget Review | Gemini vs BlockFi | OKEx Futures Trading

Open in app Get unlimited access

Programming Solidity Ethereum Blockchain Smart Contracts


Search Medium

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/coinmonks/ethereum-solidity-memory-vs-storage-which-to-use-in-local-functions-72b593c3703a 8/8
2/12/23, 7:54 PM Storage vs Memory in Solidity - Coinmonks - Medium

Published in Coinmonks

Dave Appleton Follow

Feb 16, 2018 · 2 min read · Listen

Save

Lest we forget…

Storage vs Memory in Solidity


A simple example to make you think

I was looking at some solidity code today and I was quite puzzled by it so I decided to
distill it down for you into a simple example which explains the difference between
memory and storage.

Using remix I created a contract with a mapping of structures as follows

struct St {
uint256 amountPaid;
uint256 amountOut;
bool registered;
}
mapping(address => St) store;

https://medium.com/coinmonks/storage-vs-memory-in-solidity-8251847186fd 1/5
2/12/23, 7:54 PM Storage vs Memory in Solidity - Coinmonks - Medium

If I wanted to update somebody’s amountPaid when they sent funds, I would normally
do this (Ignoring safeMath and other important issues)

function addMemFunds() public payable {


St memory mine = store[msg.sender];
mine.amountPaid += msg.value; // and the other members
store[msg.sender] = mine;
}

I was pretty amazed to find that the following works too.*

function addStorFunds() public payable {


St storage mine = store[msg.sender];
mine.amountPaid += msg.value;
}

*yeah it’s probably in the docs but I never could find it.
It seems that we are using a pointer into the structure instead of copying it.

The full code can be found in a github gist and can be loaded into remix directly ← with
this link

Compile and launch the contract

https://medium.com/coinmonks/storage-vs-memory-in-solidity-8251847186fd 2/5
2/12/23, 7:54 PM Storage vs Memory in Solidity - Coinmonks - Medium

click on “mine” to see the balance

Set a value

Click on either addStorFunds or addMemFunds and the value increases

Once you have done that you can PROVE that memory will not add without it by calling
addMemFail with a value. You will see that clicking mine shows that the value has not
been updated.

Get Best Software Deals Directly In Your Inbox


https://medium.com/coinmonks/storage-vs-memory-in-solidity-8251847186fd 3/5
2/12/23, 7:54 PM Storage vs Memory in Solidity - Coinmonks - Medium

Open in app Get unlimited access

Search Medium

Ethereum Solidity Smart Contracts Solidity Tutorial Tutorial

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/coinmonks/storage-vs-memory-in-solidity-8251847186fd 4/5
2/12/23, 7:54 PM Storage vs Memory in Solidity - Coinmonks - Medium

https://medium.com/coinmonks/storage-vs-memory-in-solidity-8251847186fd 5/5
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+

Storage vs Memory in Solidity


Difficulty Level : Basic ● Last Updated : 11 May, 2022

Read Discuss Courses Practice Video

Storage and Memor y keywords in Solidity are analogous to Computer ’s hard drive and

Computer ’s R AM. Much like R AM, Memor y in Solidity is a temporar y place to store data

whereas Storage holds data between function calls. The Solidity Smar t Contract can use

any amount of memor y during the execution but once the execution stops, the Memor y is

completely wiped off for the next execution. Whereas Storage on the other hand is

persistent, each execution of the Smar t contract has access to the data previously stored

on the storage area.

Ever y transaction on Ethereum Vir tual Machine costs us some amount of Gas. The lower

the Gas consumption the better is your Solidity code. The Gas consumption of Memor y is

not ver y significant as compared to the gas consumption of Storage. Therefore, it is

always better to use Memor y for intermediate calculations and store the final result in

Storage.

1. State variables and Local Variables of structs, array are always stored in storage by

default.

2. Function arguments are in memor y.

3. Whenever a new instance of an array is created using the keyword ‘memor y ’, a new

copy of that variable is created. Changing the array value of the new instance does

not affect the original array.

Example#1: In the below example, a contract is created to demonstrate the ‘storage’

keyword.

Start Your Coding Journey Now! Login Register


HIDE AD

https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 1/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks

Solidity

pragma solidity ^0.4.17;


 
// Creating a contract
contract helloGeeks
{
  // Initialising array numbers
  int[] public numbers;
 
  // Function to insert values
  // in the array numbers
  function Numbers() public
  {
    numbers.push(1);
    numbers.push(2);
 
    //Creating a new instance
    int[] storage myArray = numbers;
     
    // Adding value to the
    // first index of the new Instance
    myArray[0] = 0;
  } 
}

Start Your Coding Journey Now!


Output :

HIDE AD

https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 2/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks

When we retrieve the value of the array numbers in the above code, Note that the output

of the array is [0,2] and not [1,2]. 

This can be understood from the following diagram –

Using the keyword “storage”

Example#2: In the below example, a contract is created to demonstrate the keyword

‘memor y ’.

  Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 3/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks

Solidity

pragma solidity ^0.4.17;


 
// Creating a contract
contract helloGeeks

  // Initialising array numbers
  int[] public numbers;
   
  // Function to insert
  // values in the array
  // numbers
  function Numbers() public
  {
    numbers.push(1);
    numbers.push(2);
     
    //creating a new instance
    int[] memory myArray = numbers;
     
    // Adding value to the first
    // index of the array myArray
    myArray[0] = 0;
  } 
}

Output :

When we retrieve the value of the array numbers in the above code, Note that the output

of the array is [1,2]. In this case, changing the value of myArray does not affect the value

in the array numbers.

This can be understood from the following diagram –

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 4/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks

Using the keyword “memor y ”

Like 27

Previous Next

Related Articles

1. Solidity - Types

2. Solidity - Functions

3. What are Events in Solidity?

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 5/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks

4. Solidity - Inheritance

5. Solidity - Polymorphism

6. Solidity - View and Pure Functions

7. Solidity - Encapsulation

8. How to Install Solidity in Windows?

9. Solidity - While, Do-While, and For Loop

10. Solidity - Break and Continue Statements

Ar ticle Contributed By :

yathartharora
@yathartharora

Vote for difficulty

Current difficulty : Basic

Easy Normal Medium Hard Expert

Improved By : abhishek0719kadiyan

Article Tags : Blockchain, Solidity

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 6/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Advertise with us Video Tutorials
Courses

News Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Start Your
WebCoding Journey Now!
Development Contribute
HIDE AD

https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 7/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks

Web Tutorials Write an Article


Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now! HIDE AD

https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 8/8
2/12/23, 7:58 PM Solidity — Structs + Examples. Exploring Solidity structs with some… | by YBM | Coinmonks | Medium

Published in Coinmonks

YBM Follow

Mar 16, 2022 · 4 min read · Listen

Save

Solidity — Structs + Examples

Photo by Florian Olivo on Unsplash

There are a few quirks that come with writing smart contracts in Solidity. Many of
these issues come about with reference or mapping data types — namely, because

https://medium.com/coinmonks/solidity-structs-examples-635578c83bcc 1/8
2/12/23, 7:58 PM Solidity — Structs + Examples. Exploring Solidity structs with some… | by YBM | Coinmonks | Medium

these are more complex than your typical, run-of-the-mill value types—standard
booleans, integers, strings, etc.

This first post will just get into structs.

Some notes:

I won’t be discussing details on data location. You can read more about that here.

I’m always partial to examples — because there’s nothing more frustrating than
seeing an eloquent theoretical answer on StackOverflow, yet without example code
to do the actual thing.

In all the following examples, variables are public, which simply means that there
will automatically be getters created in Solidity to access them. (Making a variable
private or internal only prevents other contracts from reading or modifying it,
but it’s still visible to anyone outside of the blockchain.)

Everything here references Solidity v0.8.12, which is the latest current version at
the time of writing.

You can follow along with the source code for the examples here.

Structs
Simply, structs are a way for you to define a new custom type, containing members of
other types. Here is an example of a simple struct, written in Solidity.

Note that the struct is defined at the top of the contract, lumped in with other state
variables. You’ll also want to declare some instance variable of this struct (otherwise,
what’s the point?) because a struct is merely a type.

https://medium.com/coinmonks/solidity-structs-examples-635578c83bcc 2/8
2/12/23, 7:58 PM Solidity — Structs + Examples. Exploring Solidity structs with some… | by YBM | Coinmonks | Medium

1 struct SampleStruct1 {
2 uint256 id;
3 uint256 value;
4 string name;
5 bool isCreated;
6 }
7
8 SampleStruct1 public sample1;

SampleStruct.sol hosted with ❤ by GitHub view raw

Here are three ways that you can initialize your sample1 variable, populating it with
SampleStruct1 data.

1 function setSample1() public {


2 // method 1
3 sample1.id = 1;
4 sample1.value = 1;
5 sample1.name = "myname";
6 sample1.isCreated = true;
7
8 // method 2
9 sample1 = SampleStruct1({
10 id: 2,
11 value: 2,
12 name: "myname",
13 isCreated: true
14 });
15
16 // method 3
17 sample1 = SampleStruct1(3, 6, "myname", false);
18 }

initStruct.sol hosted with ❤ by GitHub view raw

I am partial to Method 2 — as it is most explicit, and yet readable.

https://medium.com/coinmonks/solidity-structs-examples-635578c83bcc 3/8
2/12/23, 7:58 PM Solidity — Structs + Examples. Exploring Solidity structs with some… | by YBM | Coinmonks | Medium

Structs can also contain more complex types as members — like mappings, arrays, or
other structs, but it is not possible for a struct to contain a member of its own type
(creating kind of a variable infinite loop).

Here is another more complex example, of SampleStruct2 struct, containing a member


array ( values ). In this case, the initialization changes slightly.

1 struct SampleStruct2 {
2 uint256 id;
3 uint256[3] values;
4 }
5 SampleStruct2 public sample2;
6
7 function setSample2() public {
8 // method 1
9 sample2.id = 1;
10 sample2.values = [1, 3, 4];
11
12 // method 2
13 sample2 = SampleStruct2({ id: 2, values: [uint256(1), 2, 3] });
14
15 // method 3
16 sample2 = SampleStruct2(3, [uint256(5), 6, 7]);
17 }

SampleStruct2.sol hosted with ❤ by GitHub view raw

Note that in Method 2 and Method 3, you now need to explicitly convert the first
element of the array to be uint256 type; otherwise, the type of the constants is
assumed to be uint8 . You don’t need to do so when using method 1.

Also note that we explicitly defined the member array ( values ) as a fixed-size type (of
length 3), rather than as a dynamically sized array — which would introduce even more
complexity during assignment. If values were instead uint256[] , then Method 2 and 3
would not be valid ways of declaring sample2 — because in those cases, you’d
essentially be assigning a fixed size array to a dynamically sized array, which is not
possible.
https://medium.com/coinmonks/solidity-structs-examples-635578c83bcc 4/8
2/12/23, 7:58 PM Solidity — Structs + Examples. Exploring Solidity structs with some… | by YBM | Coinmonks | Medium

Instead, you would have to use Method 1, or some variant — dynamic arrays also have
member functions push and pop like in Javascript:

1 sample2.values = [1, 3, 4];


2 // or
3 sample2.values.push(1);
4 sample2.values.push(3);
5 sample2.values.push(4);

dynamicArray.sol hosted with ❤ by GitHub view raw

We will proceed with our simpler fixed-size array.

Getters
As mentioned earlier, Solidity automatically creates a getter for public variables. Here
is how you can access your newly created structs in Javascript, using Hardhat and
ethers.js. First you must deploy the contract (named Sample.sol ):

1 const Sample = await ethers.getContractFactory("Sample");


2 const sample = await Sample.deploy();
3 await sample.deployed();

deploy.js hosted with ❤ by GitHub view raw

Next, in our case, call the function that sets the variable values ( setSample1() ). Then
use the getter, available in the form of publicVariable() , to access the data —
remember our variable is named sample1 .

1 await sample.setSample1();
2 const { id, value, name, isCreated } = { ...(await sample.sample1()) };
3 console.log(id);
4 console.log(name);
5 console.log(value);
6 console.log(isCreated);

sample1Getter.js hosted with ❤ by GitHub view raw

https://medium.com/coinmonks/solidity-structs-examples-635578c83bcc 5/8
2/12/23, 7:58 PM Solidity — Structs + Examples. Exploring Solidity structs with some… | by YBM | Coinmonks | Medium

Notice that we use the spread operator to retrieve each individual element within the
struct. The raw data from the getter (ie await sample.sample1() ), includes extraneous
keys of duplicated values, so we’ve selected only the relevant ones:

js console.log output of sample1

In the case of SampleStruct2 , we only had two members — a uint256 and an array . In
getters, mappings and arrays in structs are omitted because “there is no good way to
select individual struct members or provide a key for the mapping.” Therefore, in our
case we will only receive one element from the getter (the id ), so there is no need to
use the spread operator in that case.

1 await sample.setSample2();
2 const id = await sample.sample2();
3 console.log(id);

sample2Getter.js hosted with ❤ by GitHub view raw

And that’s it! A few specific examples of dealing with setting and getting structs in
Solidity.

Thanks for reading!

References:

https://jeancvllr.medium.com/solidity-tutorial-all-about-structs-b3e7ca398b1e

Solidity docs

*Final note — I might’ve found a Solidity bug, but defining a struct containing only an
array throws a TypeError , thusly:

https://medium.com/coinmonks/solidity-structs-examples-635578c83bcc 6/8
2/12/23, 7:58 PM Solidity — Structs + Examples. Exploring Solidity structs with some… | by YBM | Coinmonks | Medium

1 struct SampleStruct2 {
2 uint256[3] values;
3 }
4 SampleStruct2 public sample2;

StructBug.sol hosted with ❤ by GitHub view raw

error thrown by a struct containing only a member array

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also, Read
How to Start Earning Passive Income With Crypto Lending

Cryptocurrency Savings Accounts | Crypto Trading Bots

BigONE Exchange Review | CEX.IO Review | Swapzone Review

Best Bitcoin Margin Trading| Bityard Margin Trading

Crypto Margin Trading Exchanges | Earn Bitcoin

WazirX vs CoinDCX vs Bitbns | BlockFi vs CoinLoan vs Nexo

Solidity Ethereum Blockchain Cryptocurrency Java Script

https://medium.com/coinmonks/solidity-structs-examples-635578c83bcc 7/8
2/12/23, 7:58 PM Solidity — Structs + Examples. Exploring Solidity structs with some… | by YBM | Coinmonks | Medium

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter


Open in app Get unlimited access

Search Medium

https://medium.com/coinmonks/solidity-structs-examples-635578c83bcc 8/8
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+

Solidity – Mappings
Difficulty Level : Easy ● Last Updated : 11 May, 2022

Read Discuss Courses Practice Video

Mapping in Solidity acts like a hash table or dictionar y in any other language. These are

used to store the data in the form of key-value pairs, a key can be any of the built-in data

types but reference types are not allowed while the value can be of any type. Mappings

are mostly used to associate the unique Ethereum address with the associated value

type.

Syntax :

mapping(key => value) <access specifier> <name>;

Creating a Mapping

Mapping is defined as any other variable type, which accepts a key type and a value type.

Example : In the below example, the contract mapping_example a structure is defined

and mapping is created.

Start Your Coding Journey Now! Login Register


https://www.geeksforgeeks.org/solidity-mappings/ 1/11
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

Solidity

// Solidity program to 


// demonstrate mapping
pragma solidity ^0.4.18; 
   
// Defining contract 
contract mapping_example {
      
    //Defining structure
    struct student 
    {
        // Declaring different 
        // structure elements
        string name;
        string subject;
        uint8 marks;
    }
      
    // Creating a mapping
    mapping (
    address => student) result;
    address[] public student_result;    
}

Output : 

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-mappings/ 2/11
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

Adding values to mapping

A s the mapping is created let ’s tr y to add some values to the mapping for better

understanding.

Example : In the below example, the contract mapping_example defines a structure,

mapping is created and values are added to the mapping.

Solidity

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-mappings/ 3/11
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

// Solidity program to 


// demonstrate adding 
// values to mapping
pragma solidity ^0.4.18; 
  
// Creating contract
contract mapping_example {
      
    //Defining structure 
    struct student {
  
        //Declaring different 
        // structure elements
        string name;
        string subject;
        uint8 marks;
    }
  
    // Creating mapping
    mapping (
      address => student) result;
    address[] public student_result;
      
    // Function adding values to 
    // the mapping
    function adding_values() public {
        var student 
          = result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252];
  
        student.name = "John";
        student.subject = "Chemistry";
        student.marks = 88;
        student_result.push(
          0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1;
  
    }
      
}

Output : 

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-mappings/ 4/11
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

Getting values

We have added values to the mapping, to retrieve the values we have to create a function

that returns the values added to the mapping.

Example : In the below example, the contract mapping_example defines a structure,

mapping is created, values are added to the mapping, and values are retrieved from the

mapping.

Solidity

// Solidity program to
// demonstrate retrieve
// values from the mapping
  
pragma solidity ^0.4.18; 
   
contract mapping_example {
      
    // Defining Structure
    struct student {
  
        // Declaring different data types
        string name;
        string subject;
        uint8 marks;
    }
Start Your Coding Journey Now!
      

https://www.geeksforgeeks.org/solidity-mappings/ 5/11
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

    // Creating mapping


    mapping (
      address => student) result;
    address[] student_result;
     
    // Function adding values to the mapping
    function adding_values() public {
        var student 
          = result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252];
  
        student.name = "John";
        student.subject = "Chemistry";
        student.marks = 88;
        student_result.push(
          0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1;
  
    }
      
     // Function to retrieve 
     // values from a mapping
     function get_student_result(
     ) view public returns (address[]) {
        return student_result;
    }
}

Output : 

Start Your Coding Journey Now!


Counting Mappings

https://www.geeksforgeeks.org/solidity-mappings/ 6/11
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

Mappings can be counted so that we can know how many values are stored in mapping.

Example : In the below example, the contract mapping_example defines a structure,

mapping is created, values are added to the mapping, and values are retrieved from the

mapping.

Solidity

// Solidity program to
// count number of 
// values in a mapping
pragma solidity ^0.4.18; 
   
contract mapping_example {
      
    // Defining structure
    struct student {
  
        // Declaring different
        // structure elements
        string name;
        string subject;
        uint8 marks;
    }
      
    // Creating mapping
    mapping (address => student) result;
    address[] student_result;
      
    //Function adding values to the mapping
    function adding_values() public {
        var student
          = result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252];
  
        student.name = "John";
        student.subject = "Chemistry";
        student.marks = 88;
        student_result.push(
          0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1;
  
    }
      
     // Function to retrieve 
     // values from the mapping

Start Your Coding Journey Now!


     function get_student_result(
     ) view public returns (address[]) {
https://www.geeksforgeeks.org/solidity-mappings/ 7/11
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

        return student_result;
    }
  
    // Function to count number 
    // of values in a mapping
    function count_students(
    ) view public returns (uint) {
        return student_result.length;
    }
}

Output : 

Like 9

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-mappings/ 8/11
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

Previous Next

Related Articles

1. Solidity - Types

2. Solidity - Functions

3. What are Events in Solidity?

4. Solidity - Inheritance

5. Solidity - Polymorphism

6. Solidity - View and Pure Functions

7. Solidity - Encapsulation

8. How to Install Solidity in Windows?

9. Solidity - While, Do-While, and For Loop

10. Solidity - Break and Continue Statements

Ar ticle Contributed By :

jeeteshgavande30
@jeeteshgavande30

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-mappings/ 9/11
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

Vote for difficulty

Current difficulty : Easy

Easy Normal Medium Hard Expert

Article Tags : Blockchain, Solidity

Improve Article Report Issue

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305

[email protected]

Company Learn
About Us DSA
Careers Algorithms
In Media Data Structures
Contact Us SDE Cheat Sheet
Privacy Policy Machine learning
Copyright Policy CS Subjects
Advertise with us Video Tutorials
Courses

News Languages
Start Your Coding
Top News
Journey Now! Python
https://www.geeksforgeeks.org/solidity-mappings/ 10/11
2/12/23, 8:00 PM Solidity - Mappings - GeeksforGeeks

Technology Java
Work & Career CPP
Business Golang
Finance C#
Lifestyle SQL
Knowledge Kotlin

Web Development Contribute


Web Tutorials Write an Article
Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/solidity-mappings/ 11/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

Published in Geek Culture

Arun Follow

Feb 9, 2022 · 5 min read · Listen

Save

Learn Solidity : Addresses and Global Variables

This article is the continuation of ongoing Learn Solidity series. Please check out the
previous article for understanding this article easily.

https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 1/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

Learn Solidity — 1: Simple Variables


Since Ethereum introduced a Turing complete system, the Smart
Contracts, it revolutionized the functionalities of…
medium.com

More on Addresses
In Ethereum and Solidity, an address is of 20 byte value size (160 bits or 40 hex
characters). As we learned in the previous article, An address can be used to get
balance or to transfer a balance by balance and transfer method respectively. We will be
looking at these methods more closely in this section through an example contract.

We are going to create an example contract which can manage its own funds. We will
be receiving money from the address that interacts with the contract and also send
money from contract to an address specified by the user.

Example contract
https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 2/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

In the contract we define three functions, recieveMoneyTo(), which recieves money


from the address that interacts with the contract, getBalance(), which returns the
balance amount that contract address holds, and sendMoneyTo(), which sends the
money from the contract address to the address specified by the user.

Note that we use the modifier payable in recieveMoneyTo() function. The payable
modifier makes the function process transactions with non-zero Ether value. If a
transaction that transfers Ether comes to the contract and calls some function X, then
if this function X does not have the payable modifier, then the transaction will be
rejected.

Inside recieveMoney() function, we used a global variable msg to update the value of
totalRecieved. The msg global variables in particular are special global variables that
contain properties which allow access to the blockchain. msg.value is a member of the
msg (message) object when sending (state transitioning) transactions on the Ethereum
network. msg.value is automatically set to the amount of ether sent with that payable

function.

Also note that in function sendMoneyTo() we declares an address payable variable _to.
The distinction between address and address payable is that you can send Ether to a
variable defined as address payable but cannot send to variable defines just as address.

https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 3/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

10 Wei as value.

I have selected A JavaScript VM account with 100 test ethers and I have entered 10 Wei
as the value to be sent to the contract that the account is interacting with.

https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 4/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

deployed contract.

The recieveMoney() function recieved the 10 Wei that my account transferred. You can
see the balance with getBalance().

https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 5/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

getBalance() and totalRecieved().

I send another 3 Wei to the contract and the contract address now holds a total of 13
Wei.

https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 6/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

sendMoneyTo()

I used sendMoneyTo() function to send all the money that the contract account holds
to an another account that I specified.

As you can see the account received 13 Wei from the contract. Now if you check the
totalRecieved, the amount would be 13 Wei and getBalance would be 0.

In our example contract, we see that there are two types of accounts in which ether are
stored, Externally Owned Account and Contract Account. Externally Owned Accounts
are those that are controlled by a private key and have the ability to send ether and
messages from it. The JavaScript Virtual Machine accounts that we used to send ether
https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 7/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

to the contract are externally owned accounts. Contract Accounts has some code
associated to it and can send or receive ether. EOAs are outside of the Ethereum
blockchain while Contract Accounts are inside the blockchain and is controlled
completely by code.

Improving on our example contract


Sometimes we need only the owner of the contract to be able to withdraw the money
send to the contract unlike our previous contract. Let us learn how to do that using
Global variables and addresses.

Example contract 2

We define two functions sendMoney() through which sends money to the contract and
withdrawAllMoney() through which money can be withdrawn from the contract.

We then define an address owner, which in the constructor of the contract we


initialized as msg.sender , which is the address that is currently interacting with the
contract when it is deployed. Since constructor is called only when the contract is
deployed, the owner address is set.

To withdraw the money we check if the address that is currently interacting with the
contract is equal to the owner address. If yes, then then the money is withdrawn. We

https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 8/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

use the require function to check the condition. The require Solidity function
guarantees validity of conditions that cannot be detected before execution.

Contract Deploy and Run Transactions

I send 10 Ether to the contract from the owner account using sendMoney() function.

https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 9/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

withdraeAllMoney()

Now if I try to send money from contract to a different address that is not owner
address, I would get an error message saying “You are not the owner of the contract”
and The transaction will be reverted to the initial state.

We can add additional functions like pausing and destroying smart contracts to our
previous contract to make it more flexible.

setPaused() function

This
Open infunction
app will pause the contract from doing any transaction. We define setPaused()
Get unlimited access
function in such a way that only the contract owner can pause the contract.
Search Medium

destroyContract() function

To destroy the contract, solidity has selfdestruct() function that sends all remaining
Ether stored in the contract to a designated address. You have to be cautious when
using selfdestruct() function because a malicious contract can use it to force sending
Ether to any contract.

That is it for this Article! We will be discussing about Mappings, Structs, Arrays etc. in
the next article in this series.

Solidity Smart Contracts Ethereum Address Global Variable

https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 10/11
2/12/23, 8:10 PM Learn Solidity : Addresses and Global Variables | by Arun | Geek Culture | Medium

Sign up for Geek Culture Hits


By Geek Culture

Subscribe to receive top 10 most read stories of Geek Culture — delivered straight into your inbox, once a week. Take a
look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/geekculture/learn-solidity-2-addresses-and-global-variables-667ffdb924d7 11/11
2/12/23, 8:13 PM What you need to know about `msg` global variables in Solidity | by Doug Crescenzi | Upstate Interactive | Medium

Published in Upstate Interactive

Doug Crescenzi Follow

May 30, 2018 · 3 min read · Listen

Save

What you need to know about ` msg ` global


variables in Solidity

https://medium.com/upstate-interactive/what-you-need-to-know-about-msg-global-variables-in-solidity-566f1e83cc69 1/5
2/12/23, 8:13 PM What you need to know about `msg` global variables in Solidity | by Doug Crescenzi | Upstate Interactive | Medium

So, you’re new to Solidity and just starting to build smart contracts on the Ethereum
blockchain? Awesome!

You’ve likely read through the Solidity docs or played around with introductory
tutorials and come across syntax like msg.sender , msg.value , or msg.data . In
particular, I imagine you’ve asked yourself, “What does msg.sender mean?”

In Solidity there are special variables and functions which always exist globally and are
mainly used to provide information about the blockchain. They can also be used to
assist with error handling, employ mathematical and cryptographic functions, and
present information about contract addresses and the contracts themselves.

`msg` global variables explained


The msg global variables in particular are special global variables that contain
properties which allow access to the blockchain. For instance, msg.sender is always the
address where the current (external) function call came from. Let’s take a look at an
example from the blockchain-based puzzle game we built.

In our game there are six levels, each with their own puzzle to solve. The first user to
correctly solve all of the puzzles in order is awarded a sum of ETH.

Now let’s take a look at our incrementLevel() function. This function is called when a
user correctly solves a puzzle and is used to move them on to the next level in the
game:

// @dev A mapping of user addresses and their associated levels


mapping(address => uint) public userLevel;
// @dev This function will advance a user to the next level
function incrementLevel() internal {

userLevel[msg.sender]++;
}

You’ll notice we’re using the msg.sender special global variable to obtain the current
user’s address (e.g., 0x44d33a….) from where the function call came from. We’re then

https://medium.com/upstate-interactive/what-you-need-to-know-about-msg-global-variables-in-solidity-566f1e83cc69 2/5
2/12/23, 8:13 PM What you need to know about `msg` global variables in Solidity | by Doug Crescenzi | Upstate Interactive | Medium

advancing them to the next level in the game by incrementing their level (of type uint )

in the userLevel mapping.

Along with msg.sender there are other msg special global variables that are useful:

msg.data — The complete calldata which is a non-modifiable, non-persistent area


where function arguments are stored and behave mostly like memory

msg.gas — Returns the available gas remaining for a current transaction (you can
learn more about gas in Ethereum here)

msg.sig — The first four bytes of the calldata for a function that specifies the
function to be called (i.e., it’s function identifier)

msg.value — The amount of wei sent with a message to a contract (wei is a


denomination of ETH)

Take away
In Solidity there are special variables and functions. The special variables and
functions are always available globally and are mainly used to provide information
about the blockchain (i.e., transactions, contract info, address info, error handling,
math and crypto functions).

The msg global variables in particular are special global variables that contain
properties which allow access to the blockchain’s contracts, their functions, and their
values.

The msg.sender global variable — likely the most commonly used special variable — is
always the address where a current function call came from. For instance, if a function
call came from a user or smart contract with the address
0xdfad6918408496be36eaf400ed886d93d8a6c180 then msg.sender equals
0xdfad6918408496be36eaf400ed886d93d8a6c180 .

Lastly, the values of all members of msg , including msg.sender and msg.value , can
change for every external function call.

https://medium.com/upstate-interactive/what-you-need-to-know-about-msg-global-variables-in-solidity-566f1e83cc69 3/5
2/12/23, 8:13 PM What you need to know about `msg` global variables in Solidity | by Doug Crescenzi | Upstate Interactive | Medium

Interested is discussing msg global variables in Solidity further? Drop us a line!


[email protected]

☞ We build decentralized applications (DApps) on the Ethereum blockchain

Sign Up for our Monthly Email!


Email

First Name

Sign up

I agree to leave medium.com and submit this information, which will be collected
and used according to Upscribe's privacy policy.

Powered by Upscribe

Open in app Get unlimited access

Ethereum Blockchain
Search Medium Solidity Msg Global Variables Dapps

https://medium.com/upstate-interactive/what-you-need-to-know-about-msg-global-variables-in-solidity-566f1e83cc69 4/5
2/12/23, 8:13 PM What you need to know about `msg` global variables in Solidity | by Doug Crescenzi | Upstate Interactive | Medium

https://medium.com/upstate-interactive/what-you-need-to-know-about-msg-global-variables-in-solidity-566f1e83cc69 5/5
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

Published in QuillHash

Himanshu Chawla Follow

Apr 25, 2018 · 8 min read · Listen

Save

How to write upgradable smart contracts in


solidity!
While working on the smart contracts audits product QuillAudits at QuillHash, we are
given most of the time to research about best security practices in smart contracts.
QuillAudits considers the following distinct and crucial facets of the smart contract
code: Whether the code is secure. Whether the code corresponds to the
documentation (including white paper). Whether the code meets best practices
inefficient use of gas, code readability, etc. An approach to upgrade contracts must be
in the armor to prevent damage made by programming bugs after the contract got
deployed.

The Topic of upgradeable contracts is not very new to the world of ethereum. There
are some different approaches to upgrading smart contracts.

Some approaches we considered in development are:-


1. Separate logic and data.

2. Partially upgradable smart contracts system.

3. Separate logic and data in key-value pairs.

4. Eternal storage with proxy contract

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 1/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

With the first three approaches, the contract can be updated by pointing users to use
the new logic contract (through a resolver such as ENS) and updating the data contract
permissions to allow the new logic contract to be able to execute the setters. In the
fourth approach, we don’t need to do this redirection and it is a very flexible approach
to update smart contracts. We found that eternal storage with proxy contract approach
is flawless till now.

Readers are most welcome to comment if you know any flaw in this approach. It will be very
helpful for developers community.

There is a good reason for and against being able to update smart contracts. The good
reason is all the recent hacks were based on programming errors and could be fixed
very easily if it was possible to upgrade those contracts.

However, the ability to upgrade smart contracts after they got deployed is somewhat
against the ethics and immutability of the blockchain. People need to trust that you are
a good boy. One thing that might make sense would be to have multi-sig-upgrades,
where the “OK” from multiple people is necessary before a new contract is deployed
and can access the storage. I think that it is storage records that need to be immutable
in the blockchain. Logic must be improved with time as in all software engineering
practices.No one can guarantee to develop bug-free software in the first version. So
Upgradeable smart contracts with some upgrading governance mechanism can save
many hacks.

In this post, I will touch on the upgrade mechanism and in the follow-up post i will try
to come up with the best contract upgrading governance mechanism.

So let's start with the implementation approach !!


The most important thing to consider when upgrading contracts is how to preserve
the state of the original contract in the upgraded contract.

The state of the contract can be separated from the functionality of the contract.
This approach allows multiple contracts to share the same state.

In this approach, a proxy contract will act as an immutable storage contract and a
delegated contract will contain the functionality.

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 2/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

The storage structure of both these contracts must be similar.

To upgrade the logic of the contract we need to inform the proxy contract of the
address of the new delegate contract.

When a transaction is sent to a proxy contract, it does not know about the specified
function in the transaction.

The proxy contract will proxy the transaction to what we’ll refer to as a “delegate”
contract (Which contains the functionality logic). This is done using the native
EVM code, delegate call.

With delegate call, a contract can dynamically load code from a different address at

runtime. Storage, current address and balance still refer to the calling contract,

only the code is taken from the called address.

When a proxy contract uses a delegate contract’s functionality, state modifications

will happen on the proxy contract. This means that the two contracts need to define

the same storage memory. The order that storage is defined in memory needs to match

between the two contracts.

We will deploy these contracts initially:-


1. key Storage Contract (Contains the shared state)

2. Delegate contractV1 and Delegate contractV2

3. Proxy Contract (Contains the delegate call functionality)

Key Storage contract:-


It contains common storage for all storage state variables which will be shared among
all versions of the smart contract. It also contains getter and setter functions to update
and get the value of state from the delegate contract.

Key Storage contract can be consumed by any delegate contract via proxy contract
once deployed. We cannot create new getter and setters once key storage got deployed
so we need to consider this while designing the initial version of the smart contract.

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 3/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

The best approach is to make mappings for every type of field in key storage contract.
Where the key of mapping will be the name of the key simply in bytes and value will of
the type declared in mapping.

For ex:- mapping(bytes32 => uint)

Now we can use this mapping to set and get an integer value from the delegate contract
by calling the key storage getter and setter function for uint type. For ex: we can set the
total supply with the key “totalSupply” and with any uint value.

But wait something is missing, Now anyone can call our key storage contract getter and
setter function and update the state of storage that is getting used by our delegate
contract. So to prevent this unauthorized state change we can use the address of the
proxy contract as the key of mapping.

mapping(address => mapping(bytes32 => uint)) uintStorage

In our setter function:

function setUintStorage(bytes32 keyField, uint value) public {

uintStorage[msg.sender][keyField] = value

Now as we are using msg.sender address in setter function and only this state change
will be reflected in proxy contract state when it uses getter function to get the state.
Similarly, we can create other state mappings along with getter and setter functions as
shown in the code below:-

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 4/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

1 contract KeyValueStorage {
2
3 mapping(address => mapping(bytes32 => uint256)) _uintStorage;
4 mapping(address => mapping(bytes32 => address)) _addressStorage;
5 mapping(address => mapping(bytes32 => bool)) _boolStorage;
6
7 /**** Get Methods ***********/
8
9 function getAddress(bytes32 key) public view returns (address) {
10 return _addressStorage[msg.sender][key];
11 }
12
13 function getUint(bytes32 key) public view returns (uint) {
14 return _uintStorage[msg.sender][key];
15 }
16
17 function getBool(bytes32 key) public view returns (bool) {
18 return _boolStorage[msg.sender][key];
19 }
20
21 /**** Set Methods ***********/
22
23 function setAddress(bytes32 key, address value) public {
24 _addressStorage[msg.sender][key] = value;
25 }
26
27 function setUint(bytes32 key, uint value) public {
28 _uintStorage[msg.sender][key] = value;
29 }
30
31 function setBool(bytes32 key, bool value) public {
32 _boolStorage[msg.sender][key] = value;
33 }
34
35 }

KeyStorage.sol hosted with ❤ by GitHub view raw

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 5/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

Delegate contract:-
The delegate contract contains the actual functionality of dApp.It also contains a local
copy of the KeyStorage contract. In our dApp, if we include a certain functionality and
later we found a bug in deployed contract, in that case, we can create a new version of
the delegate contract.

In the code below, Delegate contract version 1 (“DelegateV1.sol”) is deployed.

1 pragma solidity ^0.4.18;


2
3 import "./SafeMath.sol";
4 import "./StorageState.sol";
5
6
7 contract DelegateV1 is StorageState {
8 using SafeMath for uint256;
9
10 function setNumberOfOwners(uint256 num) public {
11 _storage.setUint("total", num);
12
13 }
14 function getNumberOfOwners() view public returns (uint256) {
15 return _storage.getUint("total");
16
17 }
18
19
20
21
22 }

DelegateV1.sol hosted with ❤ by GitHub view raw

After deploying DelegateV1 we noticed the number of owners can be set by any user.
So now we want to upgrade the smart contract so that only the owner of the contract
can set a number of owners.

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 6/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

We cannot change the code of the already deployed contract in ethereum. So the
obvious solution is to create a new contract and the new contract too will contain a
local copy of the Key-Value contract. Here we are creating a DelegateV2.sol contract
with onlyOwner modifier added.

1 pragma solidity ^0.4.18;


2
3 import "./DelegateV1.sol";
4 import "./StorageState.sol";
5 import "./Ownable.sol";
6 contract DelegateV2 is StorageState {
7
8
9 modifier onlyOwner() {
10 require(msg.sender == _storage.getAddress("owner"));
11 _;
12 }
13
14 function setNumberOfOwners(uint num) public onlyOwner {
15 _storage.setUint("total", num);
16
17 }
18 function getNumberOfOwners() view public returns (uint) {
19 return _storage.getUint("total");
20
21 }
22
23
24
25 }

DelegateV2.sol hosted with ❤ by GitHub view raw

Now we have created a new contract but the storage of the previous contract is not
available in the new version of the contract. So we can include a reference to the actual
keyStorage contract in every version of the delegate contract.In this way, every version
of the delegate contract shares a same storage.But one thing is not desirable here, we

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 7/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

need to tell every user about the address of the updated version of the contract so that
they can use the updated contract.It sounds stupid.So we will not store actual copies of
key storage contracts in every version of the delegate contract.To get a shared storage
proxy contract comes in to the rescue, let's move on to proxy contract.

This typeform has moved


to a new address
Hit the button and we'll redirect you to
quillaudits.typeform.com

Continue

Proxy Contract:-
A proxy contract uses the delegatecall opcode to forward function calls to a target
contract which can be updated. As delegatecall retains the state of the function call,
the target contract’s logic can be updated and the state will remain in the proxy
contract for the updated target contract’s logic to use. As with delegatecall, the
msg.sender will remain that of the caller of the proxy contract.

A delegate call can dynamically load code from a different address at


runtime. Storage, current address and balance still refer to the
calling contract, only the code is taken from the called address.

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 8/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

SO we just need to pass the address of new version of contract to


proxy contract via upgradeTo function.

1 pragma solidity ^0.4.18;


2
3 import "./DelegateV1.sol";
4 import "./StorageState.sol";
5 import "./Ownable.sol";
6 contract DelegateV2 is StorageState {
7
8
9 modifier onlyOwner() {
10 require(msg.sender == _storage.getAddress("owner"));
11 _;
12 }
13
14 function setNumberOfOwners(uint num) public onlyOwner {
15 _storage.setUint("total", num);
16
17 }
18 function getNumberOfOwners() view public returns (uint) {
19 return _storage.getUint("total");
20
21 }
22
23
24
25 }

DelegateV2.sol hosted with ❤ by GitHub view raw

The code of proxy contract is quite complicated in fallback function as here low level
delegate call assembly code is used.

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 9/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

1 pragma solidity ^0.4.18;


2
3 import "./Ownable.sol";
4 import "./StorageState.sol";
5
6 contract Proxy is StorageState , Ownable {
7
8 function Proxy(KeyValueStorage storage_ , address _owner) public {
9 _storage = storage_;
10 _storage.setAddress("owner",_owner);
11
12 }
13
14 event Upgraded(address indexed implementation);
15
16 address public _implementation;
17
18 function implementation() public view returns (address) {
19 return _implementation;
20 }
21
22 function upgradeTo(address impl) public onlyOwner {
23 require(_implementation != impl);
24 _implementation = impl;
25 Upgraded(impl);
26 }
27
28 function () payable public {
29 address _impl = implementation();
30 require(_impl != address(0));
31 bytes memory data = msg.data;
32
33 assembly {
34 let result := delegatecall(gas, _impl, add(data, 0x20), mload(data), 0, 0)
35 let size := returndatasize
36 let ptr := mload(0x40)
37 returndatacopy(ptr, 0, size)
38 switch result
39 case 0 { revert(ptr, size) }
40 default { return(ptr, size) }
41 }
42 }
43
44 }

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 10/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

Proxy.sol
Let break hosted with ❤simply
it down by GitHubwhat is getting done in assembly code:- view raw

delegatecall(gas, _impl, add(data, 0x20), mload(data), 0, 0);

In above function delegate call is calling code at “_impl” address with the input
“add(data,0x20)” and with input memory size “mload(data)”,delegate call will return 0
on error and 1 on success and result of the fallback function is whatever will be
returned by the called contract function.

In proxy contract we are extending StorageState contract which will contain a global
variable to store address of keyStorage contract.

1 pragma solidity ^0.4.18;


2 import "./KeyValueStorage.sol";
3
4 contract StorageState {
5 KeyValueStorage _storage;
6
7
8
9 }

StorageState.sol hosted with ❤ by GitHub view raw

The order of extending storage state contract before ownable contract is important
here.This storage state contract will be extended by our delegate contracts and all the
functions logic executed in delegate contract will be from the context of proxy
contract.The order of storage structure of Proxy contract and Delegate contract must
be same.

Now user will always interact with dapp via same address of proxy contract and state
of key storage contract seems to be shared among all versions of contract but in actual
only proxy contract contains the reference to actual keyStorage contract.Delegate
contracts contains local copy of keyStorage contract to get the getter ,setter functions
logic and to have similar storage structure like proxy contract but actual storage
changes are getting done from the context of proxy contract only.

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 11/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

Deploying and testing it together:-

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 12/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

1
2 /* global describe it artifacts */
3
4
5
6
7
8 const KeyValueStorage = artifacts.require('KeyValueStorage')
9 const DelegateV1 = artifacts.require('DelegateV1')
10 const DelegateV2 = artifacts.require('DelegateV2')
11 const Proxy = artifacts.require('Proxy')
12
13 contract('Storage and upgradability example', async (accounts) => {
14 it('should create and upgrade idap token', async () => {
15 const keyValueStorage = await KeyValueStorage.new()
16 let proxy = await Proxy.new(keyValueStorage.address,accounts[2])
17 const delegateV1 = await DelegateV1.new()
18 const delegateV2 = await DelegateV2.new()
19
20 await proxy.upgradeTo(delegateV1.address)
21
22 proxy = _.extend(proxy,DelegateV1.at(proxy.address));
23
24
25
26 await proxy.setNumberOfOwners(10);
27 let numOwnerV1 = await proxy.getNumberOfOwners();
28 console.log(numOwnerV1.toNumber())
29
30 await proxy.upgradeTo(delegateV2.address);
31
32 proxy = DelegateV2.at(proxy.address);
33 let previousOwnersState = await proxy.getNumberOfOwners();
34 console.log(previousOwnersState.toNumber());
35 await proxy.setNumberOfOwners(20,{from:accounts[2]});
36
37 let numOfownersV2 = await proxy.getNumberOfOwners();
38 console.log(numOfownersV2.toNumber());
39
40
41
42
43
44
45
https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 13/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium
45
Here
46
output of test cases will be : 10 10 and 20
47
48 });
49 });

UpgradeTest.sol hosted with ❤ by GitHub view raw

We are calling getNumberOfOwners() three times in test case.First to get the state
change by DelegateV1 contract .Second time to get the state modified by DelegateV1
from DelegateV2 contract and we success fully managed to retain the state modified by
DelegateV1 and third time to get the state modification done by DelegateV2 contract.

Note here that we are calling getNumberOfOwners() every time from the same address
of proxy contract.So we successfully managed to update the functionality of our
contract with out losing the previous state.

If we call setNumberOfOwners() from any other address except account[2] which is


contract owner address, it will throw revert error.

Lets wind up the article with some diagrams:-

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 14/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

call upgrade to DelegateV2

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 15/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

You can see the complete code here:-

https://github.com/Quillhash/upradeableToken.git

Thanks for reading. Hopefully this guide has been useful to you and will help you to write
upgradable smart contracts in solidity and Also do check out our earlier blog posts.

At QuillAudits We provide smart contracts auditing and ÐApps pen testing services for deFi,
NFT projects ( 400+ projects secured ).

Overview of our audit process and expertise

https://audits.quillhash.com/smart-contracts-auditing-explained

To be
Open up
in app to date with our work, Join Our Community :- Get unlimited access

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 16/17
2/12/23, 8:17 PM How to write upgradable smart contracts in solidity! | by Himanshu Chawla | QuillHash | Medium

Telegram | Twitter | Facebook | LinkedIn


Search Medium

References:

https://blog.colony.io/writing-upgradeable-contracts-in-solidity-6743f0eecc88

https://medium.com/level-k/flexible-upgradability-for-smart-contracts-9778d80d1638

https://medium.com/cardstack/upgradable-contracts-in-solidity-d5af87f0f913

https://blog.zeppelinos.org/smart-contract-upgradeability-using-eternal-storage/

https://medium.com/rocket-pool/upgradable-solidity-contract-design-54789205276d

Ethereum Solidity Blockchain

Sign up for Hashing Bits From QuillAudits


By QuillHash

Stay current with latest DeFi/NFT events, hacks and innovations from around the globe. Don't fall behind! Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/quillhash/how-to-write-upgradable-smart-contracts-in-solidity-d8f1b95a0e9a 17/17
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Jean Cvllr Follow

May 17, 2020 · 10 min read · · Listen

Save

Solidity Tutorial: all about Contracts

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 1/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

Table of Contents

How are smart contracts created?

The “this” keyword

Abstract contracts

Contracts inheritance

The “super” keyword


https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 2/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

Function overriding

Deactivate and selfdestruct

How are smart contracts created ?


The EVM in Ethereum know that a smart contract is created when an Externally
Owned Account (EOA):

sends a transaction

specifies a zero-address ( 0x0000000000000000000000000000000000000000 ) as a


recipient.

The data field of the transaction contain the compiled bytecode of the smart contract
written in Solidity.

Do you want to see what does this data field / bytecode looks like?

Let’s first install the solc compiler.

brew update
brew upgrade
brew tap ethereum/ethereum
brew install solidity

To check that solc was installed successfully, run the following command:

solc --version

Let’s create a new file HelloWorld.sol and add the following Solidity code :

pragma solidity >=0.4.22 <0.6.0;

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 3/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

contract HelloWorld {
string public text = "hello world";
}

Open your terminal, go into the folder where you have your HelloWorld.sol file and
run the following command :

solc HelloWorld.sol --bin

Encountering any issues? Feel free to look back at the documentation to install the solc
compiler.

You should obtain the following output :

======= HelloWorld.sol:HelloWorld =======


Binary:
60806040526040518060400160405280600b81526020017f68656c6c6f20776f726c64
0000000000000000000000000000000000000000008152506000908051906020019061
004f929190610062565b5034801561005c57600080fd5b50610107565b828054600181
600116156101000203166002900490600052602060002090601f016020900481019282
601f106100a357805160ff19168380011785556100d1565b8280016001018555821561
00d1579182015b828111156100d05782518255916020019190600101906100b5565b5b
5090506100de91906100e2565b5090565b61010491905b808211156101005760008160
009055506001016100e8565b5090565b90565b6101ab806101166000396000f3fe6080
60405234801561001057600080fd5b506004361061002b5760003560e01c80631f1bd6
9214610030575b600080fd5b6100386100b3565b604051808060200182810382528381
8151815260200191508051906020019080838360005b83811015610078578082015181
84015260208101905061005d565b50505050905090810190601f1680156100a5578082
0380516001836020036101000a031916815260200191505b5092505050604051809103
90f35b60008054600181600116156101000203166002900480601f0160208091040260
2001604051908101604052809291908181526020018280546001816001161561010002
03166002900480156101495780601f1061011e57610100808354040283529160200191
610149565b820191906000526020600020905b81548152906001019060200180831161
012c57829003601f168201915b50505050508156fea26469706673582212203c453aaf
3f2976515227f11fba099d190cba5cfbcdcc0ad3adddbf3921c3950064736f6c637826
302e362e342d646576656c6f702e323032302e332e312b636f6d6d69742e6236356131
3635640057

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 4/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

The this keyword


The this keyword in Solidity refers to the current contract. It is convertible to the
address type and enables you to :

get the contract’s address: address(this) `

get the number of ether hold by the contract: address(this).balance

get one of the contract’s function selector (=function signature):


this.yourFunction.selector

call a function within the contract defined as external , using


this.externalFunction() syntax.

Here are some code snippets on how to use the this keyword.

function getContractAddress() public view returns (address) {


return address(this);
}
function getContractBalance() public view returns (uint) {
return address(this).balance;
}
// get function signature of `getContractBalance()`
function getFunctionSelector() public pure returns(bytes4) {
return this.getContractBalance.selector;
}

Abstract contracts

What is an abstract contract?


Solidity supports even more object-oriented design, like abstract contracts. These
contain functions definitions only, without implementation (or at least one). Other
contracts can then inherit them and implement their functions.

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 5/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

But why is this useful? Decoupling the definition of a contract from its implementation
offer several benefits:

Better extensibility and self-documentation

Facilitate patterns like the Template method.

Remove code duplication

Abstract contracts are useful in the same way that defining methods in an interface is
useful. As the Solidity documentation states:

It is a way for the designer of the abstract contract to say “any child of mine must implement
this method.

When a contract should be marked abstract ?


A contract needs to be marked as abstract in two cases:

at least one of its functions is not implemented.

It inherits from an abstract contract and does not implement all its non-
implemented functions.

In the example below, the function utterance() was defined, but no implementation
was provided (since there is nothing within the curly braces { } ).

pragma solidity >=0.4.0 <0.7.0;


abstract contract Feline {
function utterance() public virtual returns (bytes32);
}

Abstracts contracts have a particularity: they cannot be instantiated directly. The same
apply even if the contract has all its functions implemented, but defined with the
abstract keyword.

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 6/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

NB: Note that a function without implementation is different from a Function Type even
though their syntax looks very similar.

Contracts Inheritance
In Solidity, contracts behave like classes in Object Oriented Programming: they can
inherit and be inherited. This feature enables to build complex design patterns, such
as the Delegate Proxy pattern.

How to use inheritance?


To use inheritance, simple use the keyword is and specify the contract it derives
from.

contract A {}
contract B is A {}

A contract can also inherit from multiple contracts, as shown below:

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 7/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

contract A {}
contract B {}
contract C is A, B {}

Using the previous example, we might think that to deploy contract C , we must first
deploy contracts A and B. However, that is not the case.

When a contract inherits from other contracts, only a


single contract is created on the blockchain. The code
from all the base contracts is compiled into the
created contract.
This means that all internal calls to functions of base contracts will use internal
function calls.

Inheritance order
The order of inheritance for a contract is based on C3 Linearization. The Solidity
documentation explains as follow:

the order in which the base classes are given in the


" is” directive is important: You have to list the direct
base contracts in the order from “most base-like” to
“most derived”.
So if a contract inherits more than one contracts, it must inherits from “the most base”
first to “the most derived“ last, like in the following example.

contract Person {}
contract Employee is Person {}
contract Teacher is Employee, Person {} // will not compile!
contract Teacher is Person, Employee {} // will compile

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 8/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

In the example above, you will get the error:

“Linearization of inheritance graph impossible”

The order in which parent contracts are declared on the child contracts determines the
layout of the storage.

For more infos, I recommend this really in-depth blog post from Gnosis about
Delegate Proxy Contracts

The super keyword


It is possible to call functions further up in the inheritance hierarchy using the super

keyword. Use super.functionName() if you want to call the function one level higher up
in the flattened inheritance hierarchy.

Let’s go back to our Employee contract example. Our greetings() function that we have
overridden does not fit a general purpose. If you want to greet your colleagues at your
office, you would simply say “Hello”.

This function does not handle both case, so we might need to write a new one.

pragma solidity ^0.6.0;


contract Person {

function greetings() public pure virtual returns (string memory)


{
return "Hello";
}

}
contract Employee is Person {

function greetings() public pure virtual override returns (string


memory) {

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 9/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

return "Hello. How can I help you? :)";


}

function welcomeMessage(bool isClient) public pure returns (string


memory) {

return isClient ? greetings() : super.greetings();


}

Our new welcomeMessage() handle both cases now.

If we talk to a client, we call the greetings() function within the Employee

contract.

If we do not talk to a client, we call the super.greetings() . This enables us to refer


to the greetings() function one level up, within the Person contract.

One of the extra benefit of using super is that it uses JUMP internally and not a
message call.

Function overriding
Before to start talking about function overriding, let’s first understand the basis of
function calls in the context of contracts inheritance.

We will reuse our previous inheritance graph of Person -> Employee -> Teacher , and
write some functions.

Introduction

NB: The first code samples are just a basic introduction, to get a high level overview. They
apply for Solidity 0.5.0 only.
For 0.6.0, you can look at the next section titled “Virtual and override keywords”

Let’s write the first function within the Person contract.

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 10/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

pragma solidity ^0.6.0;


contract Person {

function greetings() public pure returns (string memory) {


return "Hello";
}
}

The Employee contract inherits directly this function. But what about if you want to
adapt the greeting message to the employee?

If the employee works in a customer service department, the message should be


adapted to what should be said to a client, like “Hello. How can I help you?”.

We have seen before, function overriding enables to do that easily.

pragma solidity ^0.5.0;


contract Person {

function greetings() public pure returns (string memory) {


return "Hello";
}
}
contract Employee is Person {

function greetings() public pure returns (string memory) {


return "Hello. How can I help you? :) ";
}

So far so good. But let’s look at the following sample. By calling sayHello() `, which
message should you receive? “Hello”, or “Hello, how can I help you?” ?

pragma solidity ^0.5.0;

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 11/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

contract Person {

function greetings() public pure returns (string memory) {


return "Hello";
}
}

contract Employee is Person {

function greetings() public pure returns (string memory) {


return "Hello. How can I help you? :) ";
}

}
contract Teacher is Person, Employee {

function sayHello() public pure returns(string memory) {


greetings();
}
}

Those familiar with Polymorphism will say " Hello. How can I help you? :) .
However, there is more detailed explanation from the Solidity documentation:

When a function is called that is defined multiple times


in different contracts, the given bases are searched
from right to left in a depth-first manner, stopping at
the first match.

If a base contract has already been searched, it is


skipped.
Polymorphism means that a function call (internal and external) always executes the
function of the same name (and parameter types) in the most derived contract in the
inheritance hierarchy.

This is the basis of function overriding.

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 12/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

Virtual and override keyword


Since Solidity 0.6.0, overriding functions has to be explicitly specified. Each function
of the same name the inheritance hierarchy has to be defined with:

the virtual keyword, to enable overriding in future contracts

the override keyword, to states that the function is being overridden

Let’s rewrite and upgrade our previous example contract to version 0.6.0.

pragma solidity ^0.6.0;


contract Person {

function greetings() public pure virtual returns (string memory) {


return "Hello";
}

}
contract Employee is Person {

function greetings() public pure virtual override returns (string


memory) {
return "Hello. How can I help you? :)";
}

The greetings function inside our Person contract contains the virtual keyword. It
means that it can be overridden.

The greetings function inside our Employee contract contains both the virtual and
override keyword. This mean that 1) it has overridden the greetings() function , and
2) it can be overridden again in future contracts that inherit it.

The only “burden” is that you must specify all the overridden contracts between
parentheses, as follow:

contract Teacher is Person, Employee {

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 13/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

function greetings() public pure override(Employee, Person)


returns (string memory) {
return "Hello students ! Welcome to 'All About Solidity'
series";
}

What about when only one keyword is specified?

only virtual : future derived contracts can change the behaviour of that function.

only override : you are overriding a function from a base contract, but you will not
be able to override it in future derived contracts.

For multiple inheritance, the most derived base


contracts that define the same function must be
specified explicitly after the override keyword.

In other words, you have to specify all base contracts


that define the same function and have not yet been
overridden by another base contract (on some path
through the inheritance graph).

Additionally, if a contract inherits the same function


from multiple (unrelated) bases, it has to explicitly
override it:
NB: Functions with the private visibility cannot be virtual .

NB2: Functions without implementation have to be marked virtual outside of interfaces.

Overriding external functions with public variables


Public state variables can override functions only if:
https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 14/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

the function is marked with the external visibility.

the return type of the function matches the type of the variable declared as public .

pragma solidity >=0.5.0 <0.7.0;


contract A
{
function f() external pure virtual returns(uint) { return 5; }
}
contract B is A
{
uint public override f;
}

The only restriction is that public variables ( f in our example) can override, but
cannot be overriden.

In other words, such variables cannot be marked as virtual .

Deactivate and selfdestruct


The selfdestruct function in Solidity destroys the current contract, sending all the
ethers it contains to the address passed as a function parameter.

selfdestruct(address payable recipient)

Prior to version 0.5.0, there was a function called suicide with the same semantics as
selfdestruct .

The mortal contract from the Solidity documentation provides a good example of the
selfdestruct function.

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 15/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

pragma solidity ^0.5.0;

contract owned {
address payable owner;
constructor() public {
owner = msg.sender;
}

contract mortal is owned {


function kill() public {
if (msg.sender == owner) selfdestruct(owner);
}
}

Does selfdestruct removes code from the Blockchain?


According to the Solidity Documentation, selfdestruct is the only way to remove a
contract from the blockchain.

Considering a scenario where a call to selfdestruct is performed on contract A at


block 1,000,000. The contract A will not be callable and available anymore in the future
blocks following block 1,000,000, because the contract’s code and storage are removed
from the state.

However, the Solidity documentation mentions an important point:

Even if a contract is removed by selfdestruct , it is still part of the history of the blockchain
and probably retained by most Ethereum nodes. So using “selfdestruct” is not the same as
deleting data from a hard disk.

Benefits of using selfdestruct


The selfdestruct function in Solidity corresponds to the SELFDESTRUCT opcode
(0xFF) in the Ethereum Virtual Machine.

This function is considered useful when you are finished with a contract, because it
costs far less gas than just sending the balance with address.transfer(this.balance) .

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 16/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

In fact, the SELFDESTRUCT opcode uses negative gas because the operation frees up
space on the blockchain, by clearing all of the contract’s data

This negative gas deducts from the total gas cost of the transaction, so if you’re doing
some clean-up operations first, SELFDESTRUCT can reduce your gas costs.

See Ethereum Stack Exchange : https://ethereum.stackexchange.com/a/347

Security considerations about selfdestruct


There are two main issues when it comes to the use of the selfdestruct function in
Solidity.

Security issue 1:

Removing a contract using selfdestruct can sounds like a good idea in theory, but it is
potentially dangerous. Someone (= any other contract or address) can still send Ether
to a removed contract. In this case, the Ether are forever lost.

Security issue 2:

If a contract’s code does not contain a call to selfdestruct , it can still perform that
operation using delegatecall or callcode .

If you want to deactivate your contracts, you should instead disable them by changing
some internal state which causes all functions to revert. This makes it impossible to
use the contract, as it returns Ether immediately.

Solidity Ethereum Smart Contract Blockchain Programming Blockchain

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 17/18
2/12/23, 8:20 PM Solidity Tutorial: all about Contracts | by Jean Cvllr | Medium

About Help Terms Privacy

Open in app Sign up Sign In

Get the Medium app


Search Medium

https://jeancvllr.medium.com/solidity-tutorial-all-about-contracts-e8e30bd1b289 18/18
2/12/23, 8:24 PM HOW TO USE PAYABLE FUNCTION IN SOLIDITY | by Scofield O. Idehen | Coinmonks | Medium

Published in Coinmonks

Scofield O. Idehen Follow

Apr 28, 2022 · 4 min read · Listen

Save

HOW TO USE PAYABLE FUNCTION IN SOLIDITY

In this article, I will be breaking down the transfer function and showing you how it
works and how best to use it in solidity.

I will also be showing you how to send 5 ether from one address to another address

What is the Transfer function?


https://medium.com/coinmonks/how-to-use-payable-function-in-solidity-fa871e79b167 1/7
2/12/23, 8:24 PM HOW TO USE PAYABLE FUNCTION IN SOLIDITY | by Scofield O. Idehen | Coinmonks | Medium

The transfer function allows you to send funds from your smart contract, so whenever
you use the transfer function, solidity is made aware that a transfer is about to take
place.

Let us use the following contract I created to explain the transfer more better.

// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

contract pay{

//2nd stage

//the account of the user we want to send ether to

address payable receiver = payable(0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db);

I created a contract pay and added an address called receiver with this
0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db

From remix i picked a different address as we want to pay some ether to this address.

//we are creating a function that allows for user to send money from

//our smart contract

//notice if we deploy this contract and transfer 1 ether it will work but where

//did our money go.

function cell() public payable returns (uint){

//we gave the returns (uint) keyword to give us the balance

return address(this).balance;

//give us the balance of the address of our smart contract

https://medium.com/coinmonks/how-to-use-payable-function-in-solidity-fa871e79b167 2/7
2/12/23, 8:24 PM HOW TO USE PAYABLE FUNCTION IN SOLIDITY | by Scofield O. Idehen | Coinmonks | Medium

I created a function that allows us to call the balance of the transaction, notice I called
the (uint) that tells the function that the argument is an unsigned variable.

I called the return address of this which is our address as this is called when we are
making reference to our internal variable so our address will give us the balance after
sending the Funds

//this function sends 5 ether to the receiver address above

function sendEther()public {

receiver.transfer(5 ether);

This is the logic that sends the ether to the address receiver we created above.

Let’s test it out and see how the payable works.

I will deploy the contract and make sure there is no error if there is an error the
contract will not deploy.

I picked a different account and then I deployed the contract.

https://medium.com/coinmonks/how-to-use-payable-function-in-solidity-fa871e79b167 3/7
2/12/23, 8:24 PM HOW TO USE PAYABLE FUNCTION IN SOLIDITY | by Scofield O. Idehen | Coinmonks | Medium

After deployment, noticed we have two function called Cell and sendEther which are
our function for this contract.

Next, I have to send funds into the contract, I will be sending 10 Ether into the
contract, make sure to change the value from Wei to Ether

Click on the call function and if you have a green tick that means the funds were
successfully sent into the blockchain.

https://medium.com/coinmonks/how-to-use-payable-function-in-solidity-fa871e79b167 4/7
2/12/23, 8:24 PM HOW TO USE PAYABLE FUNCTION IN SOLIDITY | by Scofield O. Idehen | Coinmonks | Medium

We have funds in the blockchain(Local), check the accounts and you will notice that 10
Ether has left out primary address but it is has not reflected in any address.

Lets send the 5 Ether to the address we set in our receiver account. click on the
sendEther and the 10 Ether is added to the account.

https://medium.com/coinmonks/how-to-use-payable-function-in-solidity-fa871e79b167 5/7
2/12/23, 8:24 PM HOW TO USE PAYABLE FUNCTION IN SOLIDITY | by Scofield O. Idehen | Coinmonks | Medium

Wow.

Exciting right, next week we would look at how to use modifiers and constructors.

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also, Read
How to buy Monero | IDEX Review | BitKan Trading Bot

CoinDCX Review | Crypto Margin Trading Exchanges

Red Dog Casino Review | Swyftx Review | CoinGate Review

Bookmap Review | 5 Best Crypto Exchanges in the USA

How to trade Futures on FTX Exchange | OKEx vs Binance

CoinLoan Review | YouHodler Review | BlockFi Review

Solidity Ethereum Bitcoin Learning To Code Nft

https://medium.com/coinmonks/how-to-use-payable-function-in-solidity-fa871e79b167 6/7
2/12/23, 8:24 PM HOW TO USE PAYABLE FUNCTION IN SOLIDITY | by Scofield O. Idehen | Coinmonks | Medium

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Open
Emails in
willapp
be sent to [email protected]. Not you? Get unlimited access

Get this newsletter


Search Medium

https://medium.com/coinmonks/how-to-use-payable-function-in-solidity-fa871e79b167 7/7
2/12/23, 8:29 PM Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by Zaryab Afser | Coinmonks | Medium

Published in Coinmonks

Zaryab Afser Follow

Jun 20, 2022 · 6 min read · Listen

Save

Deciphering Solidity: Does adding a PAYABLE


keyword actually save GAS?

Hey, fam 👋🏻

Welcome to another article in the Decipher Series, where we take one specific Smart
Contract/Web3 topic and get to the very bottom of it.

https://medium.com/coinmonks/deciphering-solidity-does-adding-a-payable-keyword-actually-save-gas-89d1d8298d3f 1/10
2/12/23, 8:29 PM Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by Zaryab Afser | Coinmonks | Medium

If you have been developing smart contracts using Solidity lately, chances are you
might have come across the payable keyword.

This blog is specifically about the same where we decipher all its interesting and weird
secrets. 😃

Quick Intro: Basics of the Payable Keyword


Out of all the wonderful things that a smart contract can do, storing your money(ETH)
is one of them. Now in order to take receive ETH in a smart contract, Solidity language
has got a specific keyword called payable.

A payable keyword, in very simpler terms, is a modifier in the solidity language that
can be attached to any function. Once attached, this keyword allows the function to
receive ether. In other words, while triggering a function with a payable keyword, you
can send ether (msg.value) along with that transaction.

While this is all good, I came across an interesting caveat around the payable keyword
while scrolling through Twitter a couple of months ago. It grabbed all my attention and
I figured that an interesting (but really wired) scenario takes place whenever a payable
modifier is attached to any function 👀.

Let’s take a quick look at this interestingly wired scenario:

https://medium.com/coinmonks/deciphering-solidity-does-adding-a-payable-keyword-actually-save-gas-89d1d8298d3f 2/10
2/12/23, 8:29 PM Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by Zaryab Afser | Coinmonks | Medium

A setter function with NO Payable Keyword

In the image attached above, we have a very simple setter function that sets the uint256
variable state to 100. If you trigger this function, you will find that the transaction gas
cost is somewhere around 43300.

Alright, now let’s look at a 2nd condition.

A setter function WITH Payable Keyword

In the 2nd case, we have the exact same function that executes an exactly similar
transaction of setting a state variable. However, the only difference here is an
https://medium.com/coinmonks/deciphering-solidity-does-adding-a-payable-keyword-actually-save-gas-89d1d8298d3f 3/10
2/12/23, 8:29 PM Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by Zaryab Afser | Coinmonks | Medium

additional payable modifier attached to the function.

Quite interestingly if you look at the transaction gas cost for calling this function, it's
around 43276 which is lower than the function with no payable keyword mentioned
above.

Yes, you got that right.

Adding a simple payable keyword just reduced the amount of gas consumption in the
function. 😃

The AHA Moment 💡💡


Alright, now it's time to understand — Why exactly does the payable modifier lower the
Gas consumption?

A very simple answer to that question is:

https://medium.com/coinmonks/deciphering-solidity-does-adding-a-payable-keyword-actually-save-gas-89d1d8298d3f 4/10
2/12/23, 8:29 PM Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by Zaryab Afser | Coinmonks | Medium

Adding a payable keyword lowers the number of


opcodes being executed, thus lowering the amount of
gas consumption.
That’s weird, isn’t it? How does adding an extra modifier to a function lower down the
number of opcodes instead of increasing it???

Well, here’s some technical (and logical) explanation for it. 😃

1. As we already know, for a function to be capable of receiving ether, a payable


modifier must be attached to it. While a function without any payable modifier
shall never be able to receive any ether.

2. It must be noted that this is a strict rule in Solidity and therefore if you try to pass
Ether while calling a non-payable function, it will simply revert.

3. Therefore in the case of Non-Payable functions, there are additional opcodes that
are executed while calling a non-payable function which ensures that the function
shall only be executed if the ether (msg.value) that is sent along with the
transaction is exactly equal to ZERO.

4. However, the same is not true for Payable function. Payable functions allow users
to pass in both non-zero or zero ether values while calling the function.

5. This basically means that even if zero ether (msg.value == 0) is sent while calling a
payable function, the transaction is not reverted. Hence, there is no need to
explicitly check the msg.value in the case of Payable functions.

In a Nutshell 🥜

https://medium.com/coinmonks/deciphering-solidity-does-adding-a-payable-keyword-actually-save-gas-89d1d8298d3f 5/10
2/12/23, 8:29 PM Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by Zaryab Afser | Coinmonks | Medium

GAS Difference between PAYABLE and NON-PAYABLE Functions in Solidity

In the case of Non-Payable Functions:

a. Additional checks are included to ensure that no ether value is passed while calling the
function.

b. These checks increase the number of opcodes being executed.

c. The increased number of opcodes ultimately results in higher gas usage.

In the case of Payable functions:

a. No additional checks are required since the function can accept both zero or non-zero
values of ether.

b. No additional checks means no additional opcodes being executed.

https://medium.com/coinmonks/deciphering-solidity-does-adding-a-payable-keyword-actually-save-gas-89d1d8298d3f 6/10
2/12/23, 8:29 PM Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by Zaryab Afser | Coinmonks | Medium

c. Lower opcodes in execution means lower consumption of gas.

My TWO CENTS 🪙🪙
Does all of the above-mentioned details, mean we should use PAYABLE Functions to save
gas?

Well, that could be a discussion.

Gas optimization is undoubtedly something that every smart contract wizard dreams
of in their contracts.

However, an imperative question is:

While saving gas is important, it’s not really a good idea to compromise on the
intended behavior of the function, minimizing the use of necessary state changes, or
using inadequate tactics just to save a few extra amounts of gas.

https://medium.com/coinmonks/deciphering-solidity-does-adding-a-payable-keyword-actually-save-gas-89d1d8298d3f 7/10
2/12/23, 8:29 PM Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by Zaryab Afser | Coinmonks | Medium

In other words, if a function has nothing to do with


receiving ether, then it should not really have any
payable keyword attached to it, even if that saves you
some gas.

Dropping John Adler’s 2 Cents as well 😇

Therefore, I firmly believe that adding an unnecessary payable keyword in a function


just to save gas is probably a bad decision. The above-mentioned scenario of reduction
in gas while adding the payable keyword is just a wired solidity language design that is
not at all effective.

About myself

Who am I? 🙋🏻‍♂️

https://medium.com/coinmonks/deciphering-solidity-does-adding-a-payable-keyword-actually-save-gas-89d1d8298d3f 8/10
2/12/23, 8:29 PM Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by Zaryab Afser | Coinmonks | Medium

𝙃𝙞, 𝙄 𝙖𝙢 𝙕𝙖𝙧𝙮𝙖𝙗 👋🏻
I am a proficient Blockchain and Smart Contract Engineer with a vision of
Decentralizing and Securing the traditional Web with Web3. Mostly work on Smart
Contracts with significant experience in both Development and Smart Contract
Security.

What I Do 🧑🏼‍💻
I write secure and optimized Smart Contracts

I perform security audits on smart contracts and enhance the overall security of
smart contracts on EVM chains

I write and speak about Web3 and Smart Contracts & contribute my part towards
expanding the boundaries for Web3.

Drop a ‘HI’ and Get in Touch 🤝


Linkedin. | Twitter |Follow my Weekly Newsletter | Invite me for Web3 Events

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also, Read
Bookmap Review | 5 Best Crypto Exchanges in the USA
Open in app Get unlimited access
The Best Crypto Hardware wallet | Bitbns Review
Search Medium
10 Best Crypto Exchange in Singapore | Buy AXS

Red Dog Casino Review | Swyftx Review | CoinGate Review

Best Crypto to Invest in India | WazirX P2P | Hi Dollar Review

Smartcontractdevelopment Solidity Web 3 Blockchain Ethereum

https://medium.com/coinmonks/deciphering-solidity-does-adding-a-payable-keyword-actually-save-gas-89d1d8298d3f 9/10
2/12/23, 8:29 PM Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by Zaryab Afser | Coinmonks | Medium

337 2

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/coinmonks/deciphering-solidity-does-adding-a-payable-keyword-actually-save-gas-89d1d8298d3f 10/10
2/12/23, 8:33 PM Lesson 5: Visibility in Solidity. In the previous lessons, we’ve already… | by Lajos Deme | Solidify | Medium

Published in Solidify

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Lajos Deme Follow

Apr 11, 2022 · 5 min read · · Listen

Save

Lesson 5: Visibility in Solidity

Photo by Tobias Tullius on Unsplash

https://medium.com/solidify/lesson-5-visibility-in-solidity-a837b249d538#:~:text=There are four possible modes,%2C private %2C internal and external . 1/9
2/12/23, 8:33 PM Lesson 5: Visibility in Solidity. In the previous lessons, we’ve already… | by Lajos Deme | Solidify | Medium

In the previous lessons, we’ve already got familiar with some basic concepts in Solidity
programming, such as functions and reference types. In this one, we are going to look
at how visibility works in Solidity.

First of all, it’s important to make one thing crystal clear right from the start.
Everything on the blockchain is public and visible to everyone else. Just because you
mark a variable as private or internal it does not mean that it is actually private or
secret. Anyone can look into the storage of any contract ever deployed on Ethereum
and see everything (we will show examples of how to do this in later lessons). There
are various attempts to make storing stuff on the blockchain more private, but that is
beyond the scope of this article.

So visibility clearly does not equal privacy. Visibility is rather a way for the smart
contract developer to determine what variables and functions should be exposed to
other smart contracts inheriting from and/or integrating the smart contract, or to say
what regular users of the contract can and should interact with.

There are four possible modes of visibility in Solidity. These are public , private ,
internal and external .

private
private is the most restrictive visibility. private functions and state variables are only
visible to the contract they were defined in. This means no inheriting contract,
externally owned account (EOA), or another contract can call a function or read a state
variable that is marked private .

Let’s see an example:

https://medium.com/solidify/lesson-5-visibility-in-solidity-a837b249d538#:~:text=There are four possible modes,%2C private %2C internal and external . 2/9
2/12/23, 8:33 PM Lesson 5: Visibility in Solidity. In the previous lessons, we’ve already… | by Lajos Deme | Solidify | Medium

Here we have two contracts, ContractA and ContractB . ContractA defines a private

function that adds two numbers. ContractB inherits from ContractA and tries to call
that private function. However, this won’t work and ContractB won’t compile. We will
get an error with the message Undeclared identifier , meaning ContractB can’t find
our function addPrivate .

However, as we can see in addAndMulTwo , calling addPrivate inside ContractA works


just fine.

internal
internal is the default visibility for state variables. internal means variables and
functions are accessible within the contract and from deriving contracts. They are still
inaccessible from EOAs and other contracts.

Let’s look at another example:

https://medium.com/solidify/lesson-5-visibility-in-solidity-a837b249d538#:~:text=There are four possible modes,%2C private %2C internal and external . 3/9
2/12/23, 8:33 PM Lesson 5: Visibility in Solidity. In the previous lessons, we’ve already… | by Lajos Deme | Solidify | Medium

Here again, we have ContractB inheriting ContractA , but this time ContractA defines a
state variable, an internal function, and a function that uses both the internal

function and the state variable.

Then in ContractB we have a function that calls the internal function and another that
reads the state variable. Nothing raises an error here and this works as expected.

However, we now have ContractC which tries to read meaningOfLife from the external
contract ContractA . This will fail and raise the error that meaningOfLife is not visible.

internal functions can be called both within the contract and within inheriting
contracts. If we would try to call addInternal from the outside, it would fail.

https://medium.com/solidify/lesson-5-visibility-in-solidity-a837b249d538#:~:text=There are four possible modes,%2C private %2C internal and external . 4/9
2/12/23, 8:33 PM Lesson 5: Visibility in Solidity. In the previous lessons, we’ve already… | by Lajos Deme | Solidify | Medium

public
The public visibility has the least restrictions. State variables and functions defined as
public can be accessed both from the inside and the outside. This means that the
defining contract, inheriting contracts, EOAs, and other smart contracts can all access
it.

For public state variables the compiler automatically generates a getter function, so if
we have uint256 public meaningOfLife = 42; we can access it from the outside as if we
would be calling a view function: meaningOfLife();

Here we ContractA , ContractB and ContractC again, but this time meaningOfLife is
defined as public so all three contracts compile and work without errors. Both the
inheriting contract and the outside contract can access the public state variables and
functions just the same as the defining contract.
https://medium.com/solidify/lesson-5-visibility-in-solidity-a837b249d538#:~:text=There are four possible modes,%2C private %2C internal and external . 5/9
2/12/23, 8:33 PM Lesson 5: Visibility in Solidity. In the previous lessons, we’ve already… | by Lajos Deme | Solidify | Medium

external
The external visibility modifier achieves what its name implies: the function can only
be called externally, from the outside.

Only functions can be marked external. They can be called from other contracts or
EOAs, and not from inside the contract or inheriting contracts.

One interesting and useful thing to note and remember is external functions are
cheaper than public functions. This is because arguments of external functions can
be read directly from calldata and they don’t need to be copied over to memory like
public functions. Memory allocation is pricey while reading from calldata is cheap.

You may recall that public functions can also be called internally, and internal calls
are executed via jumps in the code. The compiler expects all internal function
arguments to be located in memory. For external calls, the compiler does not need to
allow internal calls, so it can work with arguments being directly in calldata ,

therefore saving the cost of copying into memory.

Let’s see an example of an external function:

https://medium.com/solidify/lesson-5-visibility-in-solidity-a837b249d538#:~:text=There are four possible modes,%2C private %2C internal and external . 6/9
2/12/23, 8:33 PM Lesson 5: Visibility in Solidity. In the previous lessons, we’ve already… | by Lajos Deme | Solidify | Medium

Open in app Sign up Sign In

Search Medium

Here we ContractA defining an external function, which the inheriting ContractB tries
to call unsuccessfully, and ContractC , which is an external contract, can call
successfully.

Conclusion
In this lesson, we looked at visibility in Solidity. Specifying the correct visibility is
really important and has serious implications in smart contract and protocol design so
the right visibility for each function and state variable should be thought about deeply.

Thank you for staying with us till the end. If you enjoyed reading this piece please keep
in touch and follow Solidify to keep up with our lessons on Solidity. In the upcoming
articles, we will deep dive into the intricacies of the language, progressing from
beginner to advanced level.

If you are new to Solidity, the previous lessons might be of value to you.

Lesson 4: Solidity Functions and Function Modifiers

https://medium.com/solidify/lesson-5-visibility-in-solidity-a837b249d538#:~:text=There are four possible modes,%2C private %2C internal and external . 7/9
2/12/23, 8:33 PM Lesson 5: Visibility in Solidity. In the previous lessons, we’ve already… | by Lajos Deme | Solidify | Medium

In the previous introductory lessons, we started to dip our toes into the
world of Solidity and reviewed a few basic…
medium.com

Lesson 3: Reference Types in Solidity


Introduction to reference types
medium.com

Lesson 2: Value Types in Solidity


Introduction to value types
medium.com
153

Lesson 1: Your First Solidity Smart Contract


In the previous lesson, we looked at how to set up your local Solidity
development environment. Here we will continue…
medium.com

How to Setup Your Local Solidity Development Environment


Get started with smart contract development
medium.com

Solidity Ethereum Smart Contracts Blockchain Programming

https://medium.com/solidify/lesson-5-visibility-in-solidity-a837b249d538#:~:text=There are four possible modes,%2C private %2C internal and external . 8/9
2/12/23, 8:33 PM Lesson 5: Visibility in Solidity. In the previous lessons, we’ve already… | by Lajos Deme | Solidify | Medium

About Help Terms Privacy

Get the Medium app

https://medium.com/solidify/lesson-5-visibility-in-solidity-a837b249d538#:~:text=There are four possible modes,%2C private %2C internal and external . 9/9
2/12/23, 8:36 PM Visibility of functions and variables in Solidity | Coinmonks

Published in Coinmonks

Abdulrasheed Adediran Follow

Feb 7, 2022 · 2 min read · Listen

Save

Visibility in Solidity

In Solidity, you can control who has access to the functions and state variables in your
contract and how they interact with them. This concept is known as visibility.

A function’s visibility can be set to external , public , internal or private , while state
variables only have three possible visibility modifiers; public , internal or private .

The keyword external is not applicable to state variables.


https://medium.com/coinmonks/visibility-in-solidity-e758a4739c95 1/3
2/12/23, 8:36 PM Visibility of functions and variables in Solidity | Coinmonks

External

External functions can only be called from outside the contract in which they were
declared.

Public

Public functions and variables can be accessed by all parties within and outside the
contract. When the visibility is not specified, the default visibility of a function is
public .

Internal

Functions and variables declared with the internal keyword are only accessible within
the contract in which they were declared, although they can be accessed from derived
contracts. When visibility is not specified, state variables have the default value of
internal .

Private

Functions declared with the private keyword are only accessible within the contract
in which they were declared. Private functions are also the only functions that cannot
be inherited by other functions.

Note: Setting the visibility of a function or variable to private does not make it
invisible on the blockchain. It simply restricts its access to functions within the
contract.

Join Coinmonks Telegram Channel and Youtube


Channel get daily Crypto News
Also, Read
Copy Trading | Crypto Tax Software

Grid Trading | Crypto Hardware Wallet

Crypto Telegram Signals | Crypto Trading Bot


https://medium.com/coinmonks/visibility-in-solidity-e758a4739c95 2/3
2/12/23, 8:36 PM Visibility of functions and variables in Solidity | Coinmonks

Best Crypto Exchange | Best Crypto Exchange in India

Best Crypto APIs for Developers

OpenBest
in appCrypto Lending Platform Get unlimited access

An ultimate guide to Leveraged Token


Search Medium

Web 3 Solidity Blockchain Visibility Ethereum

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

https://medium.com/coinmonks/visibility-in-solidity-e758a4739c95 3/3
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

Published in Coinmonks

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Tom Terado Follow

Apr 23, 2021 · 4 min read · · Listen

Save

How to Learn Solidity in 30 days

Over the past month, I spent my free time learning Solidity (Ethereum Smart Contract
language). Due to the NFT hype and my never-ending interest in decentralized finance
(Defi), I thought it was finally time to learn Solidity properly.

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 1/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

They power the common Ethereum based tokens called ERC20 and the NFT’s that we
hear of selling for exuberant prices through ERC721 and ERC1125 protocols.

* If you are not a developer, I have listed some resources in the No Code section to help
you get started :)

** Also created a short Youtube video breaking all the concepts in this article

How to Learn Solidity in 30 Days

What is Solidity?
Solidity is a programming language created in 2014–2015 by Gavin Wood as a Turing-
complete computer language to interact with the Ethereum Virtual Machine. Turing
Complete means a system that can any computation problem with sufficient memory
and power.

The language allows developers to create “computerized transaction protocols that


execute terms of a contract” — smart contracts. (Nick Szabo)

The syntax is similar to Javascript and is statically typed which makes it quite
understandable for most programmers.

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 2/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

Try EatTheBlock Courses, If you want to learn


blockchain development.
What can Solidity do?
Solidity === Smart Contracts.

Smart contracts power the Ethereum ecosystem and have enabled many great projects
since 2015. The use cases include:

Non Fungible Tokens

Prediction Markets & Real Estate collateral

Decentralized Finance: Stablecoins, Lending, Derivatives, and much more

The Learning Process


When it comes to learning a new skill or language, we often get overwhelmed with
what direction to take. So it is important to remember to just stick with the process.

It may not make sense at first and that is perfectly ok.


Just keep trying.
Here are the resources and steps I took to learn Smart Contracts.

1. Understand the fundamentals of Blockchain by reading the Bitcoin Whitepaper


and Ethereum Whitepaper

2. Watch a few youtube videos of “What is Bitcoin” + “What is Ethereum” to refresh


your understanding.

3. Ethereum Blockchain Developer Bootcamp With Solidity (2021) Udemy Course

4. Beginner ERC20 or ERC721 tutorials

5. Company project documentation

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 3/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

6. Read some of their Smart Contracts

7. More Beginner/Intermediate ERC20 or ERC721 tutorials

8. Crypto Education Games

9. Try to teach or explain the concepts you learned to a friend

10. Keep Learning and writing code :)

NoCode Stream
1. Understand the fundamentals of Blockchain by reading the Bitcoin Whitepaper
and Ethereum Whitepaper

2. Watch a few youtube videos of “What is Bitcoin” + “What is Ethereum” to refresh


your understanding.

3. Crypto Education Games

4. Keep Learning!

Bitcoin and Ethereum Explainer Videos


These should help you understand the fundamentals of Bitcoin and the last video by
Vitalik Buterin (co-founder of Ethereum) is a great explainer and primer to the
technical aspects.

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 4/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

But how does bitcoin actually work?

What is Ethereum? Everything you need to know!

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 5/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

DEVCON1: Understanding the Ethereum Blockchain Protocol - Vitalik Bu…


Bu…

Solidity Courses
I paid $10 for the below course and it was incredibly worth it and was able to learn the
fundamentals and do tutorial exercises to learn about how Solidity works, the nuances,
syntax, and do a few projects.

Have included other free Youtube courses for alternatives.

Ethereum Blockchain Developer Bootcamp With Solidity (2021)


Welcome to the Complete Ethereum Blockchain Development
Bootcamp With Solidity - created by the co-creator of the…
www.udemy.com

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 6/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

Solidity Tutorial - A Full Course on Ethereum, Blockchain Development, …

Learning Solidity : Tutorial 1 The Basics

Beginner Tutorials
These tutorials help you build upon the courses from above and test out your Solidity
skills and build real applications with the web and EVM.

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 7/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

What is Ethereum?
In order to get a proper grasp of Ethereum, we should first briefly go
through the history of blockchain systems. This…
www.ludu.co

How to Build ERC-721 NFTs with IPFS


Using Open Zeppelin, Truffle, and Pinata
medium.com

Create ERC721 Token with OpenZeppelin

Medium Level Tutorials


Use these to build upon the beginner tutorials and dive deeper into testing, the Graph,
Hardhat, and learn web3 interfaces with React.

The Complete Guide to Full Stack Ethereum Development

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 8/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

The code for this project is located here. The video course for this
tutorial is located here I recently joined Edge &…
dev.to

Maksim Ivanov
If you've read previous articles about Ethereum DAPPs ( First, Second) -
you already have your very own ERC20 compliant…
maksimivanov.com

Crypto Education Games


These two Crypto Education Games are very well-regarded and will help people of all
levels refresh and understand the fundamentals of Solidity and Smart Contracts.

#1 Solidity Tutorial & Ethereum Blockchain Programming Course |


CryptoZombies
CryptoZombies is The Most Popular, Interactive Solidity Tutorial That
Will Help You Learn Blockchain Programming on…
cryptozombies.io

Ethernaut
Edit description
ethernaut.openzeppelin.com

Great YouTubers to Follow


The following Youtubers are awesome resources to help you understand what is
happening in the Ethereum space and teach you the fundamentals.

Dapp University
Learn to build decentralized apps on the Ethereum Blockchain.
www.youtube.com

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 9/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

EatTheBlocks
Do you want to learn how to build Solidity smart contracts and
Ethereum decentralized applications (Dapps)? On this…
www.youtube.com

Finematics
Educational videos on DeFi (Decentralized Finance). Website (extra
tutorials) ► http://finematics.com Patreon ►…
www.youtube.com

The Defiant
The Defiant curates, digests, and analyzes all the major developments
in decentralized finance, so that you can stay…
www.youtube.com

Hopefully, these resources help people get started in learning the power of Solidity and
what they can create.

Please leave comments 💬 if you found any other great resources and I will be happy
to include them in an edit!

P.S. If this was useful, please give me at least 20 claps for some Solidity good luck 😉

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 10/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

My Twitter → @crypblizz

Join Coinmonks Telegram Channel and Youtube


Channel get daily Crypto News
Also, Read
Crypto Telegram Signals | Crypto Trading Bot

Copy Trading | Crypto Tax Software


Open in app Sign up Sign In
Grid Trading | Crypto Hardware Wallet

Search Medium
Crypto Exchange | Crypto Apps in India

Ethereum Ethereum Blockchain Solidity Solidity Tutorial Coinmonks

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Your email

Get this newsletter

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 11/12
2/12/23, 4:22 PM How to Learn Solidity in 30 days. Over the past month, I spent my free… | by Tom Terado | Coinmonks | Medium

About Help Terms Privacy

Get the Medium app

https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 12/12

You might also like