Solidity Beginner To Advanced Guides
Solidity Beginner To Advanced Guides
Solidity Beginner To Advanced Guides
Published in Coinmonks
Save
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.
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.
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 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
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.
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.
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.
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.
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
Give a tip
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.
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
Save
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
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.
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
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
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-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
Save
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
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.
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
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
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
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.
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
2. Go to Goreli Faucet and enter your MetaMask wallet address and send some test Eth
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
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
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.
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
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
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 }
.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
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
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
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
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
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.
Congratulations!!! we have deployed our smart contract successfully. Time for some
celebration ;-)
Smart Contract: Deployment successful and now it’s time for celebration
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
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
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
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
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
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
Save
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.
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
:)
We are starting with the MomContract and creating the DaughterContract using the new
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.
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.
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
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 .
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 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).
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;
}
}
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 :
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.
And in the DaughterContract I’ve added a variable called allowance , and set it to equal
100. I’ve also added:
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.
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:
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.
First Name
Sign up
Powered by Upscribe
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
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+
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
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).
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
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“.
example.sol- Below is the sample solidity code used for testing. All it does is set a public
Solidity
// 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;
}
}
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-
Give it a name.
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
Javascript
Step 4 – Add Metamask extension to google chrome from the chrome web store.
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
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 :
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.
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
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
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
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.
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
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.
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
Related Articles
10. Creating a Smart Contract that Returns Address and Balance of Owner using
Solidity
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
Improved By : shelleyolto0v
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
Published in Edureka
Save
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.
1. What is Solidity?
5. Operators
7. Control Structures
8. Functions
9. Inheritance
What is Solidity?
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
Stick to your screen because next in our Solidity tutorial we’re gonna start coding…
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
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.
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.
…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.
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.
Boolean
Keyword: Bool
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)
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.
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’.
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
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
Incremental Operators
Incremental operators in solidity: a++, a–, ++a, –a, a+=1, a=a+1
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.
Structs
Solidity provides a way to define new types in the form of structs. Structs are custom
defined types that can group several variables.
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.
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.
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.
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.
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
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.
The above-declared is an empty body function which takes two parameters: a string
and a uint.
sampleFunc("Shashank", 10000);
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
7. Hyperledger Fabric
8. Hyperledge vs Ethereum
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
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
Save
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
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.
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.
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.
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
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
Save
In this blog post, I will introduce how data is stored in Ethereum smart contract, and
how to verify the storage state with proof.
// 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
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.
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"
}
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"
}
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.
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)
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
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": []
}
}
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.
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.
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
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:
State variables are stored in storage slots, each slot is 32 bytes long.
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:
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
Save
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.
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:
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.
Search Medium
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+
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
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
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
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
Step 6: The output below shows the address and the balance of the owner.
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
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
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
Published in Coinmonks
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Save
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
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.
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 {
// ...
}
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?).
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:
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.
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.
_;
}
}
An other example is to check for instance that it is not a specific address that is calling
the function.
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.
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:
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 in Practice
The following section describes some practical use cases for using modifiers.
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
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.
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
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.
}
}
Some code snippet from the Solidity documentation provides good examples on how
to do this.
Prevent Re-Entrancy
Look at the modifier nonReentrant from OpenZeppelin
https://docs.soliditylang.org/en/v0.5.3/contracts.html#function-modifiers
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)”);
_;
}
Before Solidity version 0.4.0, it was possible to skip the part after _;
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
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
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
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
Save
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
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.
We can rewrite this function without the return statement by explicitly assigning to the
return values:
This function takes two uint256 values as inputs, and returns a bool and a uint256 .
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:
2. emitting events
4. using selfdestruct
According to the docs, the following statements are considered (in addition to the
above) reading from the state:
3. accessing any of the members of block , tx , msg (excluding msg.sig and msg.data )
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):
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;
}
}
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.
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
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
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:
or:
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.
Function overloading
Function overloading means having two functions with the same name in a contract,
but with different parameter types.
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.
// 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.
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
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.
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
Search Medium
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 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
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
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
Creating a Contract
which has a built-in function web3.eth.Contract to create the contracts. When a contract
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 :
contract <contract_name>{
constructor() <visibility>{
.......
}
// rest code
}
Example : In the below example, the contract Test is created to demonstrate how to
Solidity
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
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
2. Public : Public functions or variables can be called both externally or internally via
solidity.
3. Internal: These functions or variables can be accessed only internally i.e. within the
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.
Solidity
https://www.geeksforgeeks.org/solidity-basics-of-contracts/ 4/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
9. Solidity - Types
Ar ticle Contributed By :
jeeteshgavande30
@jeeteshgavande30
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
Published in Coinmonks
Save
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.
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.
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
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
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/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
Save
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
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.
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!
🚀 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
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.
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
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
Save
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.
How to generate Contract ABI & EVM bytecode with ’solc’ command-line
Not explained
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
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.
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 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.
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.
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.
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
Install
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
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
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
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
Save
Smart Contract
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
[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”.
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….
👉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.
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
Search Medium
Ethereum Ethereum Blockchain Smart Contracts Web 3 Blockchain
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-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
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Save
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!
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
“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.”
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!
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)!
// 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
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.
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
// 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));
}
}
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.
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.
// 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
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
returns
Finally, the returns statement followed by the (Message[] memory) states what data this
function will return.
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.
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
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.
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!
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.
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
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.
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
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.
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.
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
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
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.
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 .
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:
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!
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
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:
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!
Give a tip
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/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
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
Save
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
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.
I will walk you through how to compile and run your first smart contract on a local test
environment.
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.
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. 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.
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
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
In addition, learn how to build decentralized applications (DApps) using some of the
web programming languages you’re already familiar with.
What is Bitcoin?
What is Ethereum?
Alternative cryptocurrencies
Cryptography basics
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
Ethereum API
Truffle Framework
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.
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.
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.
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.
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
In this course you will learn everything related to Solidity to build Smart Contracts
based Blockchain application on Ethereum.
Building 2 Applications
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.
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
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.
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.
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.
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
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
Ethereum of course
Github Pages
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
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.
Section#1
Section#2
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
Section#3
Ethereum Client
Hands-on: Install Geth, Try out the geth commands & options
Hands-on: Try out the various API i console and by writing scripts
Section#5
Web3 API
Section#6
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
Hands-on: Code simple contracts in Solidity + write test cases for testing
Section#8
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
Section#9
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.
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.
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.
Disclosure: We may get a small affiliate commission if you buy a course through links on this
page. Thank you.
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
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
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
hummingbot Follow
Save
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”).
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.
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.
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.
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”.
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.
Search Medium
Save
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
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 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.
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
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.
📌 youtube.com/0xblocktrain
Open in app Get unlimited access
📌 instagram.com/0xblocktrain
Search Medium
📌 twitter.com/0xblocktrain
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
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Save
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
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
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.
Click Continue.
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
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.
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.
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 Settings.
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.
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.
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
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://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
Save
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
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
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
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.
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
MetaMask integrated with hardware wallets Trezor and Ledger so that users can use
the service while keeping their crypto on a hardware wallet.
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
Save
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/.
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 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.
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.
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
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.
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.
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
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.
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:
Halt producing the chainIdChanged event, and in its place only emit
chainChanged.
Eliminate ethereum.publicConfigStore.
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.
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.
Search Medium
Metamask
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
Save
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.
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.
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.
MetaMask will now show you a 12 word recovery key (Seed) as below.
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.
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”.
Decrypt Follow
Save
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.
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
To use MetaMask, you will need either Chrome, a Chromium-based browser such as
Brave, or Firefox.
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
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.
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
🕐 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
🔗 Integrated — Dapps are designed to work with it, so it becomes much easier to
send Ether in and out.
🖥️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.
https://medium.com/@decryptmedia/metamask-the-beginners-guide-6111143f2581 12/14
2/12/23, 4:42 PM MetaMask: The Beginner’s Guide | Medium
Search Medium
In September 2020, MetaMask launched MetaMask Mobile for Android and iPhone, its
first smartphone app.
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
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
Save
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.
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
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
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
Save
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.
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
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+
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
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
Note: Test ethers are used only for development purposes in a way they are fake ethers.
First, go to the Chrome web store and search for MetaMask. You can get MetaMask
Step 2: Switch your network to the Rinkeby test network in MetaMask. You will see your
Step 3: Copy your account address by just clicking on your account address.
https://faucet.rinkeby.io/
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.
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
Step 10: The ether transfer process may take 2-15 minutes to be done. When test ethers
Af ter the process completed you will see something like this in your MetaMask.
Like 22
Previous Next
Related Articles
Ar ticle Contributed By :
raman111
@raman111
Improved By : unclebigbay
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
Save
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
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
Search Medium
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
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
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
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 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
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.
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
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!
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
Save
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 .
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.
React
MetaMask
Create a Wallet
Using a wallet, end users are allowed to send and receive ethers from dApps.
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
Agree with Privacy Policy , put a password, and create the wallet
Now your wallet is All Set Up , You should get your Account Address
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 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 ,
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
Language as Solidity
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
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.
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
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
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.
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
Server
Client
Test Application
It is important to test your smart-contract before deployment.
References:
Contract Source Code
Metamask Installation
Ethereum Contract
TxAddress
Udemy
TxHash: 0x3349da25727612e32d292b2fd1f1d2ac5d07b35b9b0f62f356f60d3aa65c6241
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
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
Save
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
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.
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.
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.
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
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
Save
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
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
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.
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.
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.
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.
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 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!
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.
This smart contract is complete, but how do we actually use it? Now we can harvest the
fruits of our labour.
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
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”.
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
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
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
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
Save
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?
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
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
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.
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.
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
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.
See the images below to create this file in the Remix IDE.
Create workspace
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
// 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
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.
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
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
Save
Before diving into solidity, let’s understand where solidity originated from and what
solidity means, and why it should be used?
What is Solidity?
Solidity
Solidity is an object-oriented, high-level language(Human readable) for implementing
smart contracts.
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.
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
are among some which we will discuss in great detail with examples.
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.
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.
This command will pull the latest version of IDE into your system. Now let’s run it.
Execute the below command to run it.
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
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 }
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.
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
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.
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 }
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
For deploying on the blockchain, some Ether has to be spent which is known as gas.
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.
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.
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.
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
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 🚀
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
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
Save
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.
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.
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
2. Reference type: These are variables whose values are references to where the
actual data is stored in memory.
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 .
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.
6. Literals
Literals refer to fixed values that the program may not alter during its execution.
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.
Search Medium
theblockchainchick Follow
Save
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
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.
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:
Example:
uint8 i;
Example:
bool a;
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 addr2;
Example:
Example:
string newWord;
Enum: enum
Example:
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
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.
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:
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.
Functions can also be declared as view which means that they will not modify ant state
variables.
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.
Examples:
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.
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
Save
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.
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
Search Medium
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
Save
YouTube: https://youtu.be/537AZqx_5Ec
Discord: https://discord.gg/J73qhkj7kr
Twitter: https://twitter.com/CryptoverseDAO
Linktree: https://linktr.ee/cryptoversedao
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
Value Types
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;
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,
contract SolidityTest {
constructor() public {
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
contract SolidityTest {
constructor() public {
storedData = 10;
uint b = 2;
uint result = a + b;
}
]
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.
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
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/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
Save
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.
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.
…
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:
3. Accessing any of the members of block , tx , msg (with the exception of msg.sig
and msg.data ).
https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 2/9
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium
…
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
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;
}
}
https://medium.com/@yangnana11/solidity-function-types-4ad4e5de6d56 5/9
2/12/23, 5:21 PM Solidity function types. Reference… | by Yang Nana | Medium
CryptoKitties source code has this external function. The function looks like this:
And we have another sol file from another contract call this function
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
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.
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.
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
Save
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"
}
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
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!
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.
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.
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
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
Save
View
So in this case we could declare it as a view function, meaning it’s only viewing the data
but not modifying it:
Pure
Solidity also contains pure functions, which means you’re not even accessing any data
in the app. Consider the following:
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.
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
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Save
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:
Emit an event,
Create a contract,
Use self-destruct,
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 pure functions make sure that they do not read or modify the state.
Access a special variable block , tx , msg ( msg.sig and msg.data can be read),
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
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-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+
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
Example : In the below example, the contract Test defines a view function to calculate
Solidity
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
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
Example : In the below example, the contract Test defines a pure function to calculate
Solidity
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
5. Creating a Smart Contract that Returns Address and Balance of Owner using
Solidity
9. Solidity - Types
Ar ticle Contributed By :
jeeteshgavande30
@jeeteshgavande30
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
Published in Coinmonks
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Save
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
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.
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
If there is no constructor specified in the contract, the contract will assume the default
empty constructor, equivalent to constructor() {} .
Therefore if contract has an internal constructor, you cannot deploy the contract at
all.
Neither directly
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.
contract C {
constructor() internal {}
}
contract D {
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.
In fact, you just have to 1) remove the internal keyword in your constructor, and 2)
define your contract as abstract .
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.
But what about if a contract B derived from another contract A that has a constructor
argument?
uint feet;
bool canSwim;
If a base contract has arguments, derived contracts need to specify all of them. This
can be done in 2 ways:
The way is more convenient if the constructor arguments are constants and they
define the behaviour of the contract, or describes it.
To illustrate, let’s extend add another state variable to our Animal contract.
contract Animal {
string name;
uint feet;
bool canSwim;
}
}
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 defined as payable , this 8 EVM instructions are removed and not
present.
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
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.
Save
However, this can possibly cause unintended bugs when contracts are renamed
and their constructors are not renamed.
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
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.
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
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
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
constructor.
Creating a constructor
Syntax :
Solidity
Output :
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
Solidity
https://www.geeksforgeeks.org/solidity-constructors/ 4/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks
Output :
base class.
Solidity
https://www.geeksforgeeks.org/solidity-constructors/ 6/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks
Output :
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
Solidity
https://www.geeksforgeeks.org/solidity-constructors/ 8/12
2/12/23, 5:35 PM Solidity - Constructors - GeeksforGeeks
Like 13
Next
Related Articles
1. Solidity - Types
2. Solidity - Functions
4. Solidity - Inheritance
5. Solidity - Polymorphism
7. Solidity - Encapsulation
Ar ticle Contributed By :
jeeteshgavande30
@jeeteshgavande30
Improved By : rkbhola5
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
Published in Coinmonks
Sayrarh Follow
Save
What is Solidity?
statically typed language, which means that you have to specify every variable(state
&local) at compile time.
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.
! (logical negation)
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:
uint — unsigned integers.
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.
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 {…}’
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
· == (equal to)
Bit operators
· ~ (bitwise NOT)
Arithmetic operators
· + (addition)
· — (subtraction)
· / (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
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 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.
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).
· 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
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 }
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
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
Save
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.
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
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 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.
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
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.
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.
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.
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
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
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:
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.
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
Give a tip
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
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
Save
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
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.
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.
contract UintWrapping {
uint public zero = 0;
uint public max = 2**256-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
/**
* @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
To fix this, assert(), SafeMath library, or require() functions should be adopted to pre-
check the operators and maybe rollback an illegal transaction.
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.
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
Save
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 …
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{
lockTime[msg.sender]=lockTime[msg.sender] + _timeinsecond;
}
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.
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 …
Solidity 0.8 defaults to throwing an error for overflow / underflow but if you are
working with old solidity version, consider Using SafeMath library .
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.
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 …
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
Save
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:
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.
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
where unit/bool/address is the variable type, followed by [] and then the name of the
array which can be any name.
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
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
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 () .
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.
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
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
[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:
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
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
Manipulation of a map:
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:
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
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:
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
If you got this far, you are cute, thank you for reading.
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
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/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
Save
Array types
In this section, we provide two types of categorisation for arrays:
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
… but you will see that multi-dimensional arrays can have any level of nesting ! Here
are some examples.
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.
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:
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
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
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
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.
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 ).
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
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"];
}
}
You cannot use the .push method in an array that has a fixed length. You must specify
the index.
// 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
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:
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
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
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 ).
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() {
An example of a memory array would be an array that contains x prime numbers that
you want to reduce (cumulate).
_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.
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 .
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 member function is only available for dynamic sized arrays and bytes.
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
address[] 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.
https://ethereum.stackexchange.com/questions/11870/create-a-two-dimensional-
array-in-solidity
Programming
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
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Save
string is similar to bytes but does not provide length and index.
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
Example:
uint balance[10];
To declare an array of dynamic size, specify the type of elements: <type>[] <array-
name>; .
To initialize arrays :
If the size of the array is not specified, an array of the right size is created to hold the
initialization:
balance[2] = 5;
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:
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.
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.
Examples of arrays
// 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
Calculate the total, which is 30, since there is only the first element, which is 30,
left.
Let’s compile and deploy this contract. Then execute the fixedArrayMemory() function:
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.
data2[0] = 10;
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
Example:
uint len = 3;
uint[] memory data2 = new uint[](_len);
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
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
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+
The Dynamic arrays are the arrays that are allocated memor y at the runtime and the
Syntax :
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
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
What is Solidity?
similar to the structure of classes in object-oriented languages. The solidity file has an
extension .sol.
collection of code (its functions) and data (its state) that resides at a specific address on
Ethereum.
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
Step 3: Enter the following Solidity Code. Select the same solidity version as in your
code.
Solidity
// 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.
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.
Like 3
Previous Next
Related Articles
2. Solidity - Arrays
7. Creating a Smart Contract that Returns Address and Balance of Owner using
Solidity
Ar ticle Contributed By :
muskan02
@muskan02
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
Data Structures and Algorithms Interview Preparation Data Science Topic-wise Practice C C+
Solidity – Arrays
Difficulty Level : Easy ● Last Updated : 11 May, 2022
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
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
Syntax :
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
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
Solidity
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
Solidity
Output :
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
Solidity
https://www.geeksforgeeks.org/solidity-arrays/ 5/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks
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
Example: In the below example, the contract Types first initializes an array[data] and
Solidity
Output :
3. Push: Push is used when a new element is to be added in a dynamic array. The new
Example: In the below example, the contract Types first initializes an array[data], and
Solidity
// 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.
https://www.geeksforgeeks.org/solidity-arrays/ 8/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks
Output :
Like 6
Previous Next
Related Articles
2. Solidity - Types
3. Solidity - Functions
5. Solidity - Inheritance
6. Solidity - Polymorphism
8. Solidity - Encapsulation
https://www.geeksforgeeks.org/solidity-arrays/ 10/12
2/12/23, 5:56 PM Solidity - Arrays - GeeksforGeeks
jeeteshgavande30
@jeeteshgavande30
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
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Save
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
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)
This is how a variable y with a value of 0x01234567 (hexa-decimal representation) would be stored in both
formats
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.
Note: you will also find the term “left aligned” or “right aligned”. To better clarify and avoid
confusion:
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 :
Bytes
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.
String
This string literal is interpreted in its raw byte form when assigned to a bytes32 type.
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.
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.
———————————————————————————————
& (AND) : both bits must be 1s (white rows) to result in true (1 => yellow rows).
———————————————————————————————
| (OR) : at least one of the bits have to be 1 (white rows), to result in true (1 => yellow
rows)
———————————————————————————————
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)
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.
———————————————————————————————
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
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.
———————————————————————————————
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]
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]
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;
}
Members of Bytes
.length (read-only). : yields the fixed length of the byte array
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.
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.
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
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.
1. Create a mask of needed number N of 1s in order to filter the part in a that we are
looking to retrieve.
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;
}
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:
var n = 5;
var lastBits = uint8(a) % 2 ** n;
bytes1(lastBits); // Result: 0x15 [00010101]
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)
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)
bytes2 _d
) public pure returns (bytes4) {
return (_c << 4) | _d;
}
References
Endianness - Wikipedia
Historically, various methods of endianness have been used in
computing, including exotic forms such as…
en.wikipedia.org
Programming
Cryptopusco Follow
Save
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
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.
contract BytesOrStrings {
string constant _string = "cryptopus.co Medium";
bytes32 constant _bytes = "cryptopus.co Medium";
function getAsString() public returns(string) {
return _string;
}
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
{
"transactionHash":
"0xa50b4f040acb653735a0d496c34c1b6b5a635e1b21de334fb2427f3e866fbc47",
"transactionIndex": 0,
"blockHash":
"0xbfd158d140cec5015baa989dc32f075599ed7186dcc026e86690521ac6b8fb5f",
"blockNumber": 7,
"cumulativeGasUsed": 21484,
"gasUsed": 21484,
"contractAddress": null
}
{
"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
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:
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.
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
Save
(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 Solidity
If you have already worked with programming languages, looping is pretty much the
same in Solidity as well.
//Do Something
uint i =0;
while(i<10){
i++;
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.
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;
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.
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.
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.
Import the library(mention the full path) in your test contract. My test contract is
named TestLibrary.
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.
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.
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
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.
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
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
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.
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
✕
Solidity
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
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
while loop and how an array can be initialized using the do-while loop.
Solidity
Output :
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
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
Syntax :
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
loop and how an array can be initialized using the while loop.
Solidity
Output :
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
Like 8
Previous Next
Related Articles
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
8. Solidity - Types
9. Solidity - Functions
Ar ticle Contributed By :
jeeteshgavande30
@jeeteshgavande30
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
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
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
Save
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
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 }
https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 4/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks
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
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 }
https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 7/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks
Assignment Operators
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 }
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
https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 12/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks
Operators
Reference Types
Control Structures
https://medium.com/coinmonks/solidity-fundamentals-1fb0e6b3b607 13/14
2/12/23, 7:25 PM Solidity Fundamentals : Operators | Coinmonks
Ferdi Kurt
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/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
Save
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.
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.
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.
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.
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.
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
Let’s write an example to iterate over an array and change all of its entries.
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
Solidity Ethereum
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
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
Save
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.
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
2. Reference type: These are variables whose values are references to where the
actual data is stored in memory.
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 .
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.
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
Save
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
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.
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
enums
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.
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
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.
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
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.
If we want to get the value of choice and defaultChoice , we can define the following
functions:
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 .
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
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.
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
https://medium.com/solidify/lesson-2-value-types-in-solidity-a594f152da64 8/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks
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
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
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
Address : Address hold a 20-byte value which represents the size of an Ethereum
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,
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
integral constant which makes the contract more readable, maintainable, and less
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
https://www.geeksforgeeks.org/solidity-types/ 2/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks
Output :
Reference Types
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
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
Strings : Strings are like arrays of characters. When we use them, we might occupy
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
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
Example : In the below example, the contract Types initializes the values of various
Reference Types.
Solidity
https://www.geeksforgeeks.org/solidity-types/ 4/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks
Output :
https://www.geeksforgeeks.org/solidity-types/ 5/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks
Like 7
Next
Related Articles
1. Solidity - Functions
3. Solidity - Inheritance
4. Solidity - Polymorphism
6. Solidity - Encapsulation
Ar ticle Contributed By :
https://www.geeksforgeeks.org/solidity-types/ 6/8
2/12/23, 7:36 PM Solidity - Types - GeeksforGeeks
jeeteshgavande30
@jeeteshgavande30
Read Discuss Courses Practice Video
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
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
Save
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
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.
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
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;
}
instructors[_address] = Instructor(
{
age: _age,
first_name: _first_name,
last_name: _last_name
}
);
instructorAccounts.push(_address) — 1;
}
The readable and shorter way are similar to how you instantiate a struct in Rust.
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.
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.
struct Instructor {
uint age;
string first_name;
string last_name;
}
You could also write the the _age , _first_name and _last_name directly in the return
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).
1. save all the Instructor ‘s addresses who registered in your contract in an array.
3. Retrieve the information in the mapping based on the instructor’s address that you
iterated in your mapping.
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;
}
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
The function below would do exactly the same, but it is simply to explain the idea of
storage .
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
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.
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.
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.
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;
}
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: "Ronaldinho",
age: 38,
mentor: _Maradonna {
name: "unknown",
age: ∞,
mentor: _Unknown {
name: ...,
age: ...,
mentor: ... {
name: ...
age: ...
mentor: ... {
...
...
... {
...
...
... {
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
References
https://www.youtube.com/watch?v=t0DE5ytTcvs
Programming
Search Medium
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
Save
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?
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 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).
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.
Using our previous example of the Status enum, you can modify its value as follow:
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.
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.
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;
}
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 ?
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…
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.
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.
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 .
You could also return an enum value via a function by writing uint(status) .
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.
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);
}
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.
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
// 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();
}
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”.
“ transact to CardDeck.changeSuit errored: VM error: revert. revert The transaction has been
reverted to the initial state. “
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 :
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
Published in Coinmonks
Save
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
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
Example of enum
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
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;
}
}
// 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;
return choice;
}
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
// Defining function to
// return default value
function getdefaultvalue(
) public pure returns(week_days) {
return default_value;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract test {
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;
}
}
// 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
// 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);
}
}
// Lets see Enums which are often used for state machine like this
enum State { Created, Locked, Inactive };
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Enum {
enum Status {Pending,Shipped, Accepted, Rejected,Canceled}
mapping(uint=> Status) enumMappnig;
}
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;
}
}
21
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/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
Save
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
Operations on Mappings
Nested 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.
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
...
}
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.
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.
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.
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;
}
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.
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
So in conclusion:
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
NB: the same principle applies to nested mappings. We will talk about it later.
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
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.
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.
Nested Mappings
If you have a look at the table above, for keys and value types allowed, you will notice
that:
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.
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.
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 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
This is why you cannot iterate through a mapping. There would be too many possible
keys ( = also read slots) to iterate. As a result:
In other words, every possible key exist by default, and is mapped to a default zero /
null value.
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
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
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.
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
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
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.
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
Save
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:
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:
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
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 .
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
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
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
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.
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
Save
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
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?
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.
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
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
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,
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
// addItemUsingStorage
// `units` changes in `items`
"gasUsed": 27053,
// addItemUsingMemory
// `units` does not change in `items`
"gasUsed": 22287,
1. memory and storage specifies which data location the variable refers to
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.
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:
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
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/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
Save
Lest we forget…
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.
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)
*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
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
Set a value
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.
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.
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 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
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
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.
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
keyword.
https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 1/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks
Solidity
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
‘memor y ’.
https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 3/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks
Solidity
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
https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 4/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks
Like 27
Previous Next
Related Articles
1. Solidity - Types
2. Solidity - Functions
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
7. Solidity - Encapsulation
Ar ticle Contributed By :
yathartharora
@yathartharora
Improved By : abhishek0719kadiyan
https://www.geeksforgeeks.org/storage-vs-memory-in-solidity/ 6/8
2/12/23, 7:56 PM Storage vs Memory in Solidity - GeeksforGeeks
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
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
Save
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.
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;
Here are three ways that you can initialize your sample1 variable, populating it with
SampleStruct1 data.
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).
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 }
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:
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 ):
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);
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:
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);
And that’s it! A few specific examples of dealing with setting and getting structs in
Solidity.
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;
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
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.
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
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 :
Creating a Mapping
Mapping is defined as any other variable type, which accepts a key type and a value type.
Solidity
Output :
A s the mapping is created let ’s tr y to add some values to the mapping for better
understanding.
Solidity
Output :
Getting values
We have added values to the mapping, to retrieve the values we have to create a function
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
Output :
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.
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
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
Previous Next
Related Articles
1. Solidity - Types
2. Solidity - Functions
4. Solidity - Inheritance
5. Solidity - Polymorphism
7. Solidity - Encapsulation
Ar ticle Contributed By :
jeeteshgavande30
@jeeteshgavande30
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
Arun Follow
Save
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
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
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
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.
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.
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.
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.
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
Subscribe to receive top 10 most read stories of Geek Culture — delivered straight into your inbox, once a week. Take a
look.
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
Save
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.
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:
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 )
Along with msg.sender there are other msg special global variables that are useful:
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)
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
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
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
Save
The Topic of upgradeable contracts is not very new to the world of ethereum. There
are some different approaches to upgrading smart contracts.
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.
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
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,
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
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.
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.
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 }
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.
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.
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.
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.
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
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
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
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.
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
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 });
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.
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
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
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 ).
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
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
Stay current with latest DeFi/NFT events, hacks and innovations from around the globe. Don't fall behind! Take a look.
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
Save
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
Abstract contracts
Contracts inheritance
Function overriding
sends a transaction
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?
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 :
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 :
Encountering any issues? Feel free to look back at the documentation to install the solc
compiler.
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
Here are some code snippets on how to use the this keyword.
Abstract contracts
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:
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.
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 { } ).
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.
contract A {}
contract B is A {}
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.
Inheritance order
The order of inheritance for a contract is based on C3 Linearization. The Solidity
documentation explains as follow:
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
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
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.
}
contract Employee is Person {
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
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”
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
The Employee contract inherits directly this function. But what about if you want to
adapt the greeting message to the employee?
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?” ?
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 {
}
contract Teacher is Person, Employee {
Those familiar with Polymorphism will say " Hello. How can I help you? :) .
However, there is more detailed explanation from the Solidity documentation:
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
Let’s rewrite and upgrade our previous example contract to version 0.6.0.
}
contract Employee is Person {
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:
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
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.
the return type of the function matches the type of the variable declared as public .
The only restriction is that public variables ( f in our example) can override, but
cannot be overriden.
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
contract owned {
address payable owner;
constructor() public {
owner = msg.sender;
}
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.
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.
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.
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
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
Save
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
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
contract pay{
//2nd stage
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
//notice if we deploy this contract and transfer 1 ether it will work but where
return address(this).balance;
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
function sendEther()public {
receiver.transfer(5 ether);
This is the logic that sends the ether to the address receiver we created above.
I will deploy the contract and make sure there is no error if there is an error the
contract will not deploy.
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.
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
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
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
Save
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. 😃
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 👀.
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
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.
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
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.
Adding a simple payable keyword just reduced the amount of gas consumption in the
function. 😃
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
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
a. Additional checks are included to ensure that no ether value is passed while calling the
function.
a. No additional checks are required since the function can accept both zero or non-zero
values of ether.
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
My TWO CENTS 🪙🪙
Does all of the above-mentioned details, mean we should use PAYABLE Functions to save
gas?
Gas optimization is undoubtedly something that every smart contract wizard dreams
of in their contracts.
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
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.
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
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/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
Save
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 .
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 .
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.
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
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 ,
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
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.
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
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
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
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 .
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.
OpenBest
in appCrypto Lending Platform Get unlimited access
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/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
Save
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
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 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
Smart contracts power the Ethereum ecosystem and have enabled many great projects
since 2015. The use cases include:
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
NoCode Stream
1. Understand the fundamentals of Blockchain by reading the Bitcoin Whitepaper
and Ethereum Whitepaper
4. Keep Learning!
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
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
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.
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
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
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
Ethernaut
Edit description
ethernaut.openzeppelin.com
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
Search Medium
Crypto Exchange | Crypto Apps in India
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
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
https://medium.com/coinmonks/how-to-learn-solidity-in-30-days-78b02e503d23 12/12