0% found this document useful (0 votes)
1K views239 pages

Ethers - Js Beginner To Advanced Guides

The Ethers.js Beginner to Advanced Guides is a comprehensive resource designed to empower developers with the knowledge and skills to effectively utilize the Ethers.js library. This series of guides takes users on a journey from the fundamental concepts of Ethereum and blockchain development to advanced topics such as smart contract interactions and decentralized application (dApp) creation. With clear explanations, practical examples, and hands-on exercises, beginners can quickly grasp the basi

Uploaded by

Walid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views239 pages

Ethers - Js Beginner To Advanced Guides

The Ethers.js Beginner to Advanced Guides is a comprehensive resource designed to empower developers with the knowledge and skills to effectively utilize the Ethers.js library. This series of guides takes users on a journey from the fundamental concepts of Ethereum and blockchain development to advanced topics such as smart contract interactions and decentralized application (dApp) creation. With clear explanations, practical examples, and hands-on exercises, beginners can quickly grasp the basi

Uploaded by

Walid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 239

2/12/23, 9:46 PM Blockchain interaction using Ethers.

js | Coinmonks

Published in Coinmonks

Chikku George Follow

Oct 15, 2022 · 3 min read · Listen

Save

BLOCKCHAIN SERIES

How to Interact with Blockchain using Ethers.js


Utilizing ethers, read data and send transactions on the blockchain

Ethers.js
Ethers.js is a library that allows us to connect with the Ethereum Blockchain and its
ecosystem. We can use ethers to connect to Ethereum nodes through JSON-RPC,
https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8#:~:text=js-,Ethers.,Alchemy%2C Cloudflare%2C or Met… 1/6
2/12/23, 9:46 PM Blockchain interaction using Ethers.js | Coinmonks

Infura, Alchemy, Cloudflare, or Metamask.

Installation

npm install ethers

Authentication
Crypto wallets like Metamask, Coinbase, TrustWallet, and Phantom are used to
connect to the blockchain. They provide an entry point to every decentralized
application. We can install crypto wallets as add-ons or plugins to our browsers.

When we add crypto wallets as an extension to our browsers, they automatically inject
themselves into the browser window object. For example, If we add the Metamask
extension, it injects an ethereum object into the browser window.

Establish Provider Connection


Ethers.js library makes it easy to connect to any node in a blockchain. We can either
use the default provider given by the browser extension or third-party RPC providers
like Alchemy, Infura, and Moralis.

Credits: Author

Fetch Wallet Balance

https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8#:~:text=js-,Ethers.,Alchemy%2C Cloudflare%2C or Met… 2/6


2/12/23, 9:46 PM Blockchain interaction using Ethers.js | Coinmonks

After initializing the provider, we can invoke the provider method, getBalance() to
fetch the balance of an ethereum account.

Credits: Author

Handling BigNumber
In Ethereum, many operations are performed on numbers that are outside the range
of values in javascript, called BigNumbers. Ethers.js helps us to convert BigNumbers
into numbers that are in human readable format.

Credits: Author

Create Signer

https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8#:~:text=js-,Ethers.,Alchemy%2C Cloudflare%2C or Met… 3/6


2/12/23, 9:46 PM Blockchain interaction using Ethers.js | Coinmonks

A signer is an abstraction of a blockchain account that is used to sign messages and


send transactions on the blockchain. After initializing the provider, we can create a
signer from it.

Credits: Author

Send Transactions
We can use the signer to send the transaction. A transaction object might contain from
and to addresses, the token value to be sent, the gas price, and the gas limit.

Credits: Author

Interaction with Smart Contract


We can connect to a smart contract and invoke the methods specified in contract ABI
using the signer. ABIs are written in JSON format. It contains details on smart
contracts, such as what functions are available, how to use them, and how to retrieve
data from them.

https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8#:~:text=js-,Ethers.,Alchemy%2C Cloudflare%2C or Met… 4/6


2/12/23, 9:46 PM Blockchain interaction using Ethers.js | Coinmonks

For example, if your ABI contains a balanceOf() function, we can invoke the method as
follows:

Credits: Author

Thank You:)

New to trading? Try crypto trading bots or copy


trading

Ethersjs Blockchain Send Transactions Blockchain Interaction

Open in app Get unlimited access


Ethereum Blockchain

Search Medium

Sign up for Coinmonks


By Coinmonks

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

https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8#:~:text=js-,Ethers.,Alchemy%2C Cloudflare%2C or Met… 5/6


2/12/23, 9:46 PM Blockchain interaction using Ethers.js | Coinmonks

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

Get this newsletter

https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8#:~:text=js-,Ethers.,Alchemy%2C Cloudflare%2C or Met… 6/6


2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | Coinmonks | Medium

Published in Coinmonks

Alexandr Kumancev Follow

Oct 1, 2022 · 9 min read · Listen

Save

Web3.js vs Ethers.js — Fully Guide


These days, crypto developers can choose among multiple programmable blockchains
to build on. And, while you can hear the term “Ethereum killers” being thrown around
quite often, the first mover remains the king. As such, the majority of blockchain
developers still focus on Ethereum. Moreover, since other programmable chains tend
to follow Ethereum’s lead, most of them are EVM-compatible. Thus, the same
JavaScript libraries can be used to deploy dApps (decentralized applications) across
multiple chains. With that in mind, you ought to take a closer look at Web3.js vs
Ethers.js comparison.

https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 1/11
2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | Coinmonks | Medium

Herein, you will get a chance to learn what Web3.js and Ethers.js are. You’ll also learn
about JavaScript modules. Moreover, I’ll take a quick overview of the modules of each
of the two JavaScript ETH libraries. However, the core of this article is the Web3.js vs
Ethers.js comparison. It will help you establish a clear picture of the benefits and
disadvantages of each library. Moreover, it should also make things clearer why the
majority of the crypto industry is moving towards the younger of the two libraries.

What is Web3.js?
As mentioned above, Web3.js is an open-source library or a collection of JavaScript (JS)
libraries. If you can’t answer “what is JavaScript?”, make sure to read our guide on this
popular programming language. I’ve also mentioned in the introduction that Web3.js
serves for Ethereum-based projects. As such, it enables developers to interact with the
Ethereum blockchain when creating dApps. Moreover, it is worth pointing out that the
Web3.js library was built by the Ethereum Foundation. Thus, it has a rather large
community behind it, which is usually an added value.

Furthermore, Web3.js essentially incorporates functions for communicating with


Ethereum nodes. This communication is performed via the JavaScript Object Notation
— Remote Procedure Call (JSON-RPC) protocol. In case this is the first time you’re
hearing about Web3, make sure to jump over to my switching guide to Web3.
Moreover, before taking on our Web3.js vs Ethers.js comparison, we need to ensure
you all know what JS modules are. For now, note that both Web3.js and Ethers.js
contain modules.

JS Modules Explained
https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 2/11
2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | Coinmonks | Medium

You can think of JavaScript modules as book chapters or sections. Moreover, this
principle of compartmentalization is something all experienced programmers apply.
As such, you can see many programs and programming libraries divided into modules.
And, both ETH JS libraries covered herein follow that practice.

Furthermore, modules are basically clusters of code. So, when the JavaScript
programming language is in question, modules represent a cluster of meaningful
combinations of words and special characters. Also, keep in mind that each module
normally covers specific functionality within a larger program. However, circling back
to the book chapter analogy, unlike book sections, good programming modules can be
removed, added, or shuffled as necessary. Moreover, all these alterations don’t affect
the system as a whole. As such, they are essentially highly self-contained with specific
functionality. In addition, dividing programs and libraries into modules also makes
maintainability and reusability much simpler. Nonetheless, if you are familiar with any
other coding languages (e.g.: Java or Python), you may think of classes. They are a very
close analogy to modules.

Web3.js Modules
Now that you know what JS modules are, let’s take a quick overview of Web.js modules:

Web3.eth: The Eth module is there for interacting with the Ethereum network. It offers
several sub-modules, including Web3.eth.subscribe, Web3.eth.contract,
Web3.eth.accounts, Web3.eth.personal, and more.

Web3.*.net: The Net module is there for interacting with network properties. Of course, it
may be used as a sub-module to interact with Ethereum (Web3.eth.net).

Web3.bzz: The Bzz module is there for interacting with the swarm network.

Web3.shh: The Shh module is there for interacting with the whisper protocol.

Web3.utils: This module provides utility functions for Ethereum dApps and other web3.js
packages.

Like with most programming languages, platforms, and libraries, it is best to use their
documentation for more details. You can find the link to the Web3.js documentation in the
“Web3.js vs Ethers.js — Documentation” section below.

https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 3/11
2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | Coinmonks | Medium

What is Ethers.js?
Ethers.js is also an Ethereum JavaScript library that enables developers to
communicate and interact with the Ethereum network. Moreover, it is an open-source
library with the MIT License. So, what’s the point of Ethers.js if it serves the same
purpose as Web3.js? Well, keep in mind that having options is normally a good thing.
As such, Ethers.js offers an impressive (in many aspects a superior) alternative to
Web3.js. However, just like with any product out there, Ethers.js and Web3.js have their
own drawbacks and benefits. More on that in the “Web3.js vs Ethers.js — A
Comparison” section below.

Ethers.js Modules
Just like Web3.js, Ethers.js also has several modules. To be exact, there are four
modules in this JS library: Ethers.contract, Ethers.provider, Ethers.utils, and
Ethers.wallets. These modules are the core of the Ethers.js’ API (Application
Programming Interface). Moreover, let’s take a quick overview of all four Ethers.js
modules:

Ethers.Provider: This module enables you to establish a connection with the Ethereum
blockchain. You use it to issue queries and send signed transactions. Through this module,
Ethers.js users get to change the state of the blockchain.

Ethers.Contract: You use this module to deploy and interact with smart contracts. While
deploying smart contracts is one of the main purposes of Ethers.Contract, it has more to
https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 4/11
2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | Coinmonks | Medium

offer. As such, it also packs functions that enable developers to ‘listen’ to smart contract
events (sync and index smart contract events). Furthermore, you also use this module to
get information about smart contracts and call particular functions provided by smart
contracts.

Ethers.Utils: You will use this module when you want to format data and process user
inputs. As such, Ethers.utils makes building dApps a whole lot easier.

Ethers.Wallet: As you can assume based on the ‘.wallet’, Ethers.Wallet provides a way to
connect to any existing Ethereum address (an Ethereum wallet). On top of that important
feature, this module also enables you to create new wallets and sign transactions.

Web3.js vs Ethers.js — ETH JS Libraries Side-by-side


So far we’ve covered the basics of both JS ETH libraries, including their modules. As
such, you should have a proper understanding of what Ethers.js and Web3.js are. Also,
you now know what they are used for. As such, you understand they are very important
for developing dApps on the Ethereum blockchain or other EVM-compatible chains.

https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 5/11
2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | Coinmonks | Medium

In the following subsection, I’ll cover the main aspects of both JS libraries. As a result,
you will be able to use this Web3.js vs Ethers.js comparison to determine which of the
two options to use. However, please note that you do not need to overthink this. I’m
assure you that you can work successfully with either of the two JS ETH libraries. With
that said, let’s do the Web3.js vs Ethers.js comparison.

Web3.js vs Ethers.js — A Comparison


In the subsections that follow, we will compare Web3.js vs Ethers.js in the following
aspects:

The team behind it

Popularity

Downloads

Updates

Testing

Web performance

Documentation

License

https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 6/11
2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | Coinmonks | Medium

Web3.js vs Ethers.js — The Team Behind It


Web3.js: It is a project of the Ethereum Foundation (a non-profit organization).
With an entire organization behind a project, there are more developers offering support.
Unfortunately, this also means that there is no clear responsibility as to who should
ensure that all is in order.

Ethers.js: It was developed and is maintained by Richard “RicMoo” Moore. This


clearly puts full responsibility on RicMoo.

As you can see, each of the backing types has its pros and cons. What kind of backing
do you prefer?

Web3.js vs Ethers.js — Popularity


Here, you need to keep in mind that Web3.js was created first. As such, it makes sense
that it wins the overall use cases title. By leaning on GitHub’s data, Web3.js has more
stars and more repositories. On the other hand, when it comes to the speed of growth
in popularity, Ethers.js comes on top.

Web3.js vs Ethers.js — Downloads

https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 7/11
2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | Coinmonks | Medium

Another way to compare these two JS libraries is to look at the download. However, the
overall number of downloads doesn’t paint a clear picture. Since Web3.js has been on
the scene noticeably longer it has an unfair advantage. Luckily, we can rather focus on
daily downloads. According to npm-stat.com, Ethers.js is a winner in that aspect.

Web3.js vs Ethers.js — Staying Updated


It is important to go with a library that is updated regularly and properly. That way it
ensures that the support team removes all known bugs and adds new features in a
timely manner. According to available reviews and devs feedback, both ETH JS
libraries are updated relatively regularly.

Web3.js vs Ethers.js — Testing


When it comes to testing, Ethers.js may be the better choice. It has pre-written tests
and clear documentation of its tests. However, you should keep in mind that this
conclusion is based on previous versions of the Ethers.js. With the new version, things
may be different.

Web3.js vs Ethers.js — Web Performance


Ethers.js loads slightly faster thanks to its noticeably smaller size, which may offer
better performance. Though, the size factor plays a noticeable role only when it comes
to small dApps. Also, it is important to point out that there is not sufficient speed test
https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 8/11
2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | Coinmonks | Medium

data for the exact same dApps using Web3.js and Ethers.js. Thus, any performance
advantage remains to be confirmed.

Web3.js vs Ethers.js — Documentation


According to my experience and comments from developers, we can say that neither
of the two ETH JavaScript libraries has perfect documentation. However, they both
provide you with more than enough details to get going. Then, it is up to you to cover
the key aspects of your interests. This is also the way you will determine, which one
better fits your project. Moreover, here are the links to the currently latest versions (at
the time of writing) of documentation for each library:

The Web3.js documentation: https://web3js.readthedocs.io/en/v1.7.0/

The Ethers.js documentation: https://docs.ethers.io/v5/

Furthermore, you should also keep in mind that JavaScript itself is always evolving,
thus its libraries must be updated as well. Things evolve even faster in the blockchain
world. As such, teams release updates and newer visions of both ETH JavaScript
libraries quite often.

Web3.js vs Ethers.js — License


Web3.js: It has an LGLv3 license.

Ethers.js: It has an MIT license.

If your project has specific requirements regarding the license, you need to pay attention to
that. In some cases, it is smart to hire a license expert. A professional will help you determine
which of the two ETH JavaScript libraries is more suitable for you.

https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 9/11
2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | Coinmonks | Medium

Web3.js vs Ethers.js — Fully Guide — Summary


We’ve covered a lot of ground and have managed to wrap up our Web3.js vs Ethers.js
comparison. By now you know that both JS ETH libraries offer several modules that
enable you to interact with the Ethereum chain. Moreover, you’ve learned that each
library has its advantages and disadvantages. However, the blockchain industry as a
whole is slowly migrating towards a younger alternative — Ethers.js.

Thank you for your support!👐🏼

New to trading? Try crypto trading bots or copy


trading

Web 3 Ethersjs Ethereum Blockchain Development Java Script

Sign up for Coinmonks


By Coinmonks
https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 10/11
2/12/23, 9:48 PM Web3.js vs Ethers.js — Fully Guide | by Alexandr Kumancev | 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.

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

Get this newsletter


Open in app Get unlimited access

Search Medium

https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 11/11
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

codedamn

Introduction to ethers.js – Complete Guide


(2022)
Saturday, Dec 3rd 2022 (2 months ago)
Anas Khan
Author

Ether.js is one of the fastest-growing libraries for building unstoppable web 3.0
applications. It’s become a strong preference by many experienced developers as their
go-to library for building javascript-based blockchain applications because it is elegant
and it’s easy to use. You can get up to speed pretty fast.
In this blog, I will give you an introduction, how to get started with ether.js, and the
complete guide you need. This blog will cover all the things like the prerequisite of
ether.js and the proper steps to follow so that you can get up to speed and start building
your own blockchain applications in no time.
https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 1/12
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

Table of Contents
1.About Ether.js
1.1.Overview of Web 3.0
1.2.How Ether.js works?
1.3.Ether.js Modules
1.4.Where Ether.js are used?
2.Getting started with Ether.js
2.1.Installing
2.2.Importing
2.3.Metamask
2.4.Start Developing the Project
3.Conclusion

About Ether.js
Before learning about ether.js, let’s discuss Blockchain
Blockchain is a worldwide computer or it’s a peer-to-peer network of nodes that all talk
to one another. Consider it like a web server in the sense that each of the nodes on the
network is a computer but each node keeps a redundant copy of all the information and
all the programs on the blockchain.

https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 2/12
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

Ether.js
Ether.js is one of the most popular javascript-based tooling kits that allow us to interact
with different blockchains and it has all the wrappers that help to make the APIs call and
do all sorts of things with Ethereum and polygon and avalanche and any EVM-compatible
chain.
Ether.js is a javascript library that enables you to work with Ethereum-based virtual
machines i.e EVM. Basically, we all use web applications through browsers like chrome,
brave, safari, and many others out there, when you are browsing the browsers are talking
directly to the websites.

Overview of Web 3.0


Those websites are usually written in HTML, CSS, and Javascript which are called the
frontend part, and then that website talks to a backend typically that in on a central
server, it has some APIs that help it to talk to the backend and get the data. That’s how a
typical web 2.0 website works where you have a website and all the information is stored
in a central server.
https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 3/12
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

Web 2 model
Let’s look at a web 3.0 way of doing things which is a very similar scenario where you
have your web browsers like chrome, safari, or brave and then you talk to front-end
websites where you might be interacting with a decentralized application or adapt.
Web 3.0 got the same website in HTML, CSS, and Javascript, and then instead of talking
to a backend that might directly talk to a blockchain. Like normal websites, it doesn’t
have any central server, and all the code and data of the application is on a server that is
present on a blockchain replacing the typical backend from the web 2 scenario and it
uses smart contracts to deal with it.

https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 4/12
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

Web 3 model
To create such websites that actually talk to a blockchain then the critical piece to
understand is how to get the frontend to talk to the backend in the website to a
blockchain so you can interact with smart contracts and also get information to the
blockchain itself and write information to the blockchain.

How Ether.js works?


If you want to create a website that talks to the nodes of the blockchain so that you can
interact with the smart contracts, you know to get information from the blockchain and
write new transactions that you need to connect to a node.

https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 5/12
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

Nodes
Initializing connection to the blockchain nodes can achieve in many ways like directly
from your web browser with a website, or you could do it with a script on your computer
or you could do ti with a back-end server.
Any of these things can wire up a connection to an individual node on a blockchain to
start using it so that it can get information about cryptocurrencies, and NFTS, and write
new transactions. It can help you to create a website that powers the full-stack
decentralized applications.
You need something that connects your client to one of these nodes of blockchain so
they can start using the full power of the blockchain, that’s exactly what ether.js is it’s a
library written in javascript that lets you create any javascript application that talks to the
blockchain so you can use and create many applications which are going to be based n
decentralized application (daps). It’s the bridge that essentially that takes your client and
it allows it to connect to the blockchain.

Ether.js Modules
Ether.js consists of some important modules that can be used to interact with blockchain
nodes easily, and get the transaction data as required. To get started with the modules
of Ehter.js, let’s take an overview of all the Ether.js modules.

https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 6/12
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

Ethers.Provider: In this module it lets you initialize a connection with the Ethereum
blockchain, and it provides you the features to issue queries and send signed
transactions. Managing the state of the blockchain is also possible through this
module.
Ethers.Contract: In this module, you can deploy and interact with smart contracts,
during the deployment part of smart contracts and to make it successful is the part
of Ethers.Contract module. It also offers some unique packs of functions that let the
developer “listen” to smart contract events and after listening to the contracts you
can also get information about them.
Ethers.Utils: This module lets you process the user data inputs and format them
according to your requirements. Ether. utils make it easy to build decentralized
applications.
Ethers.Wallet: As the name suggests it provides a way to connect to any co-existing
Ethereum address to a proper wallet. It also has important features like it lets you
create new wallets and also make sign transactions too.

Where Ether.js are used?


The Ether.js library provides many sets of tools as we saw in the above context to
interact with the Ethereum Nodes along with Javascript or Typescript. It was originally
designed for use in some other field but turns out into a more general-purpose library.
Because of Ether.js we now connect to the blockchain with ease and get all the
information required like transaction details, block updates, and many other things.
One of the blockchain products which uses ether.js as their solely reliable communication
to blockchain nodes is uniswap.org

Getting started with Ether.js


Starting with Ether.js is fairly easy. You can follow these steps in order to start
using `Ether.js`.

Installing
https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 7/12
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

Before installing Ether.js, you need Nodejs installed on your computer, to install node js
just click on this link . After setting up the Nodejson your computer type this command in
the terminal.

// this will install ether libray on your particualr folder


npm install --save ethers

Importing
We will see how to import ether.js after installing it in our folder. There are two ways for
javascript and react.
Javascript:
// this will import ether.js in your project
const { ethers } = require("ethers");

React:
// this will import ether.js in your project
import { ethers } from "ethers";

Metamask
Metamask is a cryptocurrency wallet that lets you enable users to store Ethereum and
other tokes which lies in ERC-20. It is a browser plugin that helps you to store or transfer
Ethereum or any other ERC-20 tokens.
The quickest and easiest way to develop any Ethereum-based product is to use
Metamask which is a browser extension that provides:
Connection to the Ethereum network
Reserved your private keys and can use them as a signer.
Interact with faucets like virtual coins with the help of a test network.
https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 8/12
Start Developing the Project
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

After you have successfully executed the above code, you have successfully performed
the installation and setup of `Ether.js`.
Now, you can install and use `truffle` framework in order to create a project that will
help you use Ether.js with React, which is one of the most popular frameworks for
building a front end.
Also, you should `install ganache-cli,` which will help you to set up an Ethereum-like
blockchain on your machine. It will also provide you with some wallet addresses with
some fake testing, which you can use to perform some operations and pay the required
gas fee (fee required to create the transaction block on the chain)
Truffle provides some of the features and many tools which will help you to compile and
deploy the smart contract  Ethereum or other Ethereum-based blockchains
(testnet/mainnet) and many more. These will help you create a fully-fledged
decentralized app like  `NFT(Non-Fungible Token) Marketplace` based on `ERC721
Standards`, a token-minting app based on `ERC20 Tokens`, and many more.

Conclusion
Ether.js is essentially one of the lightest libraries compared with web3.js. It is a small,
compact library, with a very good number of test cases. The popularity of a library is
crucial because if the demand is less then the project will not get updated day by day
and the error or bugs will not get fixed. Ether.js is really popular so this will never arrive in
the future for sure.
The performance of ether.js is more compared to web3.js and the ether.js library also
claims to be 284kb uncompressed, and on NPM it is listed at 3.5 MB unpacked. Web.js is
quite heavy with respect to ether.js. The documentation is great and it still getting
updated as per the new features roll out.
We saw about Ether.js and what features it provides. And learning it would be really
beneficial for your career in web3 if you are thinking of starting. Codedamn provides a
whole web3 full-fledged curated hands-on learning and practicing course check it out
too .
https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 9/12
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

Learn programming on codedamn


Try to explore all the stuff in ether.js and have great learning!😊

Codedamn is an interactive coding platform with tons of sweet programming courses


that can help you land your first coding job. Here's how:
Step 1 - Create a free account
Step 2 - Browse the structured roadmaps (learning paths), or see all courses.
Step 3 - Practice coding for free on codedamn playgrounds.
Step 4 - Upgrade to a Pro membership account to unlock all courses and platforms.
Programming is one of the most in-demand jobs today. Learning to program can change
your future. All the best!

Sharing is caring
Did you like what Anas Khan wrote? Thank them for their work by sharing it
on social media.
Share

Add your comment. Some markdown is supported.


Report a problem Comment

Write on codedamn
Truffle Framework: Complete Tutorial To
Using Truffle with Blockchain
https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 10/12
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

Complete Hardhat Tutorial: How to build


smart contracts with hardhat and
blockchain
Complete Guide To ERC-20 standard for
Ethereum network (2022)
How to create a Smart Contract in
Solidity? Full Guide 2022
Smart Contract Developer
RoadMap to Getting Started with Web
3.0 & to be a Web 3.0 Developer
Web3.js Complete Tutorial 2022 – Get
Started with Web3.js
How to become a solidity developer in
2022?
Definition of Solidity – What is Solidity
and how to get started with it?
Definition of Solidity – What is Solidity
and how to get started with it?

Learn to code interactively - without ever leaving your browser.

[email protected]

SOLUTIONS
Create a free account POPULAR GUIDES
https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 11/12
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)

Learning paths How much JS before React?


Which field should I build my career in? Solidity require keyword
Student Account Next.js vs Nuxt.js
Online compilers React.js online compiler
Web Tools Python online IDE
Next.js best practices
COMPANY Payable function solidity
Contact us Solidity online compiler
Pricing Cannot read properties of null
Blog Prerequisite for Node.js
Refer and Earn Bun.js Tutorial
Work at codedamn
Write on codedamn Master React.js
Campus Evangelist Solidity challenges
Affiliate Program Deploy MERN app
Platform Feedback Uninstall Node.js
Privacy Policy What is IDE
Terms of Service TypeScript beginner tutorial
Quick Sort
useEffect React.js
Free Node.js Hosting
Reverse a string in JS

© codedamn™ 2023 | All rights reserved.

https://codedamn.com/news/blockchain/introduction-to-ethers-js-complete-guide-2022 12/12
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

Published in BlockChannel

BlockChannel Follow

Mar 7, 2019 · 7 min read · Listen

Save

Build an Ethereum DApp Using Ethers.js


Tutorial from Zastrin.com CEO, Mahesh Murthy

Note: This post originally was published on the Zastrin.com blog, by Mahesh Murthy

If you have built dapps on Ethereum, you most likely have used Web3.js to build your
javascript frontend. Ethers.js is a lightweight javascript library which can be used as an
alternative to Web3.js to build your javascript frontend and interact with the Ethereum
blockchain. I had a chance to tinker with Ethers.js recently and was impressed with it.

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 1/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

In this post/tutorial, I show how you can use Ethers.js to build a simple dapp. I hope
this helps you evaluate and get started using Ethers.js for your next project.

In this tutorial, we will create a simple Voting dapp (very similar to our popular ‘Hello
world voting dapp’ many of you might know!). The Solidity contract will be the same
but we will use Ethers.js instead of Web3.js for the frontend. The application is
extremely simple, all it does is initialize a set of candidates, let anyone vote for those
candidates and display the total votes received by each candidate.

If you are new to Ethereum, here are some courses that can help you get started.

The goal of this tutorial is to:

1. Set up the development environment


2. Learn the process of writing a contract, compiling it and deploying it in your
development environment
3. Interact with the contract using ethers.js through a nodejs console
4. Interact with the contract using ethers.js in a simple web page to display the vote
counts and vote for candidates through the page

If you have already worked through the ‘Hello world voting dapp’, you can skip to Step
3.

This is how I would visualize this application we are going to build.

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 2/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

1. Setting up the development environment


Instead of developing the app against the live blockchain, we will use an in- memory
blockchain (think of it as a blockchain simulator) called ganache. Below are the steps
to install ganache, ethersjs, solc (to compile our contract) and start the test blockchain
on a macos. The exact same instructions work on linux as well.

zastrin@macbook$ brew update


zastrin@macbook$ brew install nodejs
zastrin@macbook$ mkdir -p ethereum_voting_dapp/chapter1-ethersjs
zastrin@macbook$ cd ethereum_voting_dapp/chapter1-ethersjs
zastrin@macbook$ npm install ganache-cli ethers [email protected]
zastrin@macbook$ node_modules/.bin/ganache-cli

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 3/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

Ganache CLI v6.0.3 (ganache-core: 2.0.2)


Available Accounts
==================
(0) 0x5c252a0c0475f9711b56ab160a1999729eccce97
(1) 0x353d310bed379b2d1df3b727645e200997016ba3
(2) 0xa3ddc09b5e49d654a43e161cae3f865261cabd23
(3) 0xa8a188c6d97ec8cf905cc1dd1cd318e887249ec5
(4) 0xc0aa5f8b79db71335dacc7cd116f357d7ecd2798
(5) 0xda695959ff85f0581ca924e549567390a0034058
(6) 0xd4ee63452555a87048dcfe2a039208d113323790
(7) 0xc60c8a7b752d38e35e0359e25a2e0f6692b10d14
(8) 0xba7ec95286334e8634e89760fab8d2ec1226bf42
(9) 0x208e02303fe29be3698732e92ca32b88d80a2d36
Private Keys
==================
(0) a6de9563d3db157ed9926a993559dc177be74a23fd88ff5776ff0505d21fed2b
(1) 17f71d31360fbafbc90cad906723430e9694daed3c24e1e9e186b4e3ccf4d603
(2) ad2b90ce116945c11eaf081f60976d5d1d52f721e659887fcebce5c81ee6ce99
(3) 68e2288df55cbc3a13a2953508c8e0457e1e71cd8ae62f0c78c3a5c929f35430
(4) 9753b05bd606e2ffc65a190420524f2efc8b16edb8489e734a607f589f0b67a8
(5) 6e8e8c468cf75fd4de0406a1a32819036b9fa64163e8be5bb6f7914ac71251cc
(6) c287c82e2040d271b9a4e071190715d40c0b861eb248d5a671874f3ca6d978a9
(7) cec41ef9ccf6cb3007c759bf3fce8ca485239af1092065aa52b703fd04803c9d
(8) c890580206f0bbea67542246d09ab4bef7eeaa22c3448dcb7253ac2414a5362a
(9) eb8841a5ae34ff3f4248586e73fcb274a7f5dd2dc07b352d2c4b71132b3c73f
HD Wallet
==================
Mnemonic: cancel better shock lady capable main crunch alcohol derive
alarm duck umbrella
Base HD Path: m/44'/60'/0'/0/{account_index}

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 4/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

Listening on localhost:8545

Notice that the ganache-cli creates 10 test accounts to play with automatically. These
accounts come preloaded with 100 (fake) ethers.

2. Simple voting contract


We are going to use the solidity programming language to write our contract. If you are
familiar with object oriented programming, learning to write solidity contracts should
be a breeze. We will write a contract (think of contract as a class in your favorite OOP
language) called Voting with a constructor which initializes an array of candidates. We
will write 2 methods, one to return the total votes a candidate has received and another
method to increment vote count for a candidate.

Note: The constructor is invoked once and only once when you deploy the contract to
the blockchain. Unlike in the web world where every deploy of your code overwrites
the old code, deployed code in the blockchain is immutable. i.e, If you update your
contract and deploy again, the old contract will still be in the blockchain untouched
along with all the data stored in it, the new deployment will create a new instance of
the contract.

Below is the voting contract code with inline comment explanation:

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 5/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

1 pragma solidity ^0.6.4;


2 // We have to specify what version of compiler this code will compile with
3
4 contract Voting {
5 /* mapping field below is equivalent to an associative array or hash.
6 The key of the mapping is candidate name stored as type bytes32 and value is
7 an unsigned integer to store the vote count
8 */
9
10 mapping (bytes32 => uint256) public votesReceived;
11
12 /* Solidity doesn't let you pass in an array of strings in the constructor (yet).
13 We will use an array of bytes32 instead to store the list of candidates
14 */
15
16 bytes32[] public candidateList;
17
18 /* This is the constructor which will be called once when you
19 deploy the contract to the blockchain. When we deploy the contract,
20 we will pass an array of candidates who will be contesting in the election
21 */
22 constructor(bytes32[] memory candidateNames) public {
23 candidateList = candidateNames;
24 }
25
26 // This function returns the total votes a candidate has received so far
27 function totalVotesFor(bytes32 candidate) view public returns (uint256) {
28 require(validCandidate(candidate));
29 return votesReceived[candidate];
30 }
31
32 // This function increments the vote count for the specified candidate. This
33 // is equivalent to casting a vote
34 function voteForCandidate(bytes32 candidate) public {
35 require(validCandidate(candidate));
36 votesReceived[candidate] += 1;
37 }
38
39 function validCandidate(bytes32 candidate) view public returns (bool) {
40 for(uint i = 0; i < candidateList.length; i++) {
41 if (candidateList[i] == candidate) {
42 return true;
43 }
44 }
45 return false;
https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 6/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium
45 return false;
Copy
46
the
}
above code to a file named Voting.sol in the ethereum_voting_dapp/chapter1-
ethersjs
47 } directory. Now let’s compile the code and deploy it to ganache blockchain.

Follow the
Voting.sol commands
hosted below to compile the contract.
with ❤ by GitHub view raw

zastrin@macbook$ node_modules/.bin/solcjs — bin — abi Voting.sol


zastrin@macbook$ ls
Voting.sol Voting_sol_Voting.abi Voting_sol_Voting.bin

When you compile the code successfully using the command above, the compiler
outputs 2 files that are important to understand:

1. Voting_sol_Voting.bin: This is the bytecode you get when the source code in
Voting.sol is compiled. This is the code which will be deployed to the blockchain.
2. Voting_sol_Voting.abi: This is an interface or template of the contract (called abi)
which tells the contract user what methods are available in the contract. Whenever you
have to interact with the contract in the future, you will need this abi definition. You
can read more details about ABI here

We will now use ethersjs library to deploy our application and interact with it.

First, run the ‘node’ command in your terminal to get in to the node console and
initialize the ethers object. All the code snippets below need to be typed in the node
console. To compile the contract, load the bytecode and abi from the file system in to a
string like shown below

zastrin@macbook$ node
> ethers = require(‘ethers’)
> bytecode = fs.readFileSync(‘Voting_sol_Voting.bin’).toString()
> abi =
JSON.parse(fs.readFileSync(‘Voting_sol_Voting.abi’).toString())

Next is to initialize the provider which is a generic interface to connect to the


blockchain. Since we are running the blockchain locally, we will use the
https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 7/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

JsonRPCProvider to connect to it. If you wanted to connect to a real blockchain, you


have many other provider options. Once connected, you can test the connection by
querying ganache and listing all the accounts. Running the below commands in your
nodejs console should list 10 accounts.

> provider = new ethers.providers.JsonRpcProvider()


> provider.listAccounts().then(result => console.log(result))

The next step is to initialize the signer which is used to sign the transactions. We can
select which account we want to use (we have 10 accounts ganache in setup) by passing
the index to getSigner as shown below. Once the wallet is intialized, create a contract
factory and deploy the contract as shown. The deploy function takes an array of
arguments that is passed to the constructor of the contract. In our case, we pass in the
names of the candidates. We have to explicitly convert string to bytes32 because our
contract takes bytes32 as argument.

> signer = provider.getSigner(0)


> factory = new ethers.ContractFactory(abi, bytecode, signer)
> contract = null
> factory.deploy([ethers.utils.formatBytes32String(‘Rama’),
ethers.utils.formatBytes32String(‘Nick’),
ethers.utils.formatBytes32String(‘Jose’)]).then(© => { contract = c})

If you successfully deployed the contract, your contract object should have all the
details of the deployed contract. There are hundreds of thousands of contracts
deployed on the blockchain. So, how do you identify your contract in that blockchain?
Answer: contract.address. When you have to interact with your contract, you need this
deployed address and abi definition we talked about earlier.

3. Interact with the contract in the nodejs console

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 8/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

>
contract.totalVotesFor(ethers.utils.formatBytes32String(‘Rama’)).then(
(f) => console.log(f.toNumber()))
>
contract.voteForCandidate(ethers.utils.formatBytes32String(‘Rama’)).th
en((f) => console.log(f))
>
contract.totalVotesFor(ethers.utils.formatBytes32String(‘Rama’)).then(
(f) => console.log(f.toNumber()))

Try the above commands in your node console and you should see the vote count
increment. Every time you vote for a candidate, you get back a transaction id: Example:
‘0xdedc7ae544c3dde74ab5a0b07422c5a51b5240603d31074f5b75c0ebc786bf53’ above).
This transaction id is the proof that this transaction occurred and you can refer back to
this at any time in the future. This transaction is immutable. This immutability is one
of the big advantages of blockchains such as Ethereum.

4. Webpage to connect to the blockchain and vote


Now that most of the work is done, all we have to do now is create a simple html file
with candidate names and invoke the voting commands (which we already tried and
tested in the nodejs console) in a js file. Below you can find the html code and the js
file. Drop both of them in the ethereum_voting_dapp/chapter1-ethersjs directory and
open the index.html in your browser.

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 9/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>Hello World DApp</title>
5 <link href='https://fonts.googleapis.com/css?family=Open Sans:400,700' rel='stylesheet' type='tex
6 <link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='styleshee
7 </head>
8 <body class="container">
9 <h1>A Simple Hello World Voting Application</h1>
10 <div class="table-responsive">
11 <table class="table table-bordered">
12 <thead>
13 <tr>
14 <th>Candidate</th>
15 <th>Votes</th>
16 </tr>
17 </thead>
18 <tbody>
19 <tr>
20 <td>Rama</td>
21 <td id="candidate-1"></td>
22 </tr>
23 <tr>
24 <td>Nick</td>
25 <td id="candidate-2"></td>
26 </tr>
27 <tr>
28 <td>Jose</td>
29 <td id="candidate-3"></td>
30 </tr>
31 </tbody>
32 </table>
33 </div>
34 <input type="text" id="candidate" />
35 <a href="#" onclick="voteForCandidate()" class="btn btn-primary">Vote</a>
36 </body>
37 <script charset="utf-8"
38 src="https://cdn.ethers.io/scripts/ethers-v4.min.js"
39 type="text/javascript">
40 </script>
41 <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
42 <script src="./index.js"></script>
43 </html>

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 10/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium
index.html hosted with ❤ by GitHub view raw
You should now see the vote counts and you should also be able to vote for candidates.
1 abi = JSON.parse('[{"constant":true,"inputs":[{"name":"candidate","type":"bytes32"}],"name":"totalV
2
3 provider = new ethers.providers.JsonRpcProvider()
4 signer = provider.getSigner(0);
5 contract = new ethers.Contract('0x5735731eEbDA5BE1eEe9f0b119B9374a63b0f507', abi, signer)
6
7 candidates = {"Rama": "candidate-1", "Nick": "candidate-2", "Jose": "candidate-3"}
8
9 function voteForCandidate(candidate) {
10 candidateName = $("#candidate").val();
11 console.log(candidateName);
12
13 contract.voteForCandidate(ethers.utils.formatBytes32String(candidateName)).then((f) => {
14 let div_id = candidates[candidateName];
15 contract.totalVotesFor(ethers.utils.formatBytes32String(candidateName)).then((f) => {
16 $("#" + div_id).html(f);
If17you are})using a wallet like Metamask, you will need to use a Web3 provider instead of
JsonRPCProvider
18 }); we used earlier. To do that, simply change the provider in your
19 }
index.js to:
20
21 $(document).ready(function() {
provider = new ethers.providers.Web3Provider(web3.currentProvider);
22
23 candidateNames = Object.keys(candidates);
If24you want to interact through Metamask, you can’t just open index.html and interact
in25yourfor(var
browser
i=0; anymore. You have to i++)
i<candidateNames.length; server
{ the file through a server. So, install a

simple
26 webserver
let and start like below
name = candidateNames[i];
27 contract.totalVotesFor(ethers.utils.formatBytes32String(name)).then((f) => {
28 $("#" + candidates[name]).html(f);
29 })
zastrin@macbook$ npm install http-server
30 }
31zastrin@macbook$
}); http-server

index.js hosted with ❤ by GitHub view raw


You can now go to localhost:8080 and interact with your application. Below is a quick
demo which includes loading test ether account into metamask.

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 11/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

I hope you were able to follow along and get the application working. Check out
Zastrin.com, and sign-up to get more tutorials and lessons so you can build and deploy
real working dApps.

Start contributing to the community and decentralization, and become a Zastrin


developer. If you run into issues getting the application working, feel free to DM me on
twitter @zastrinlab or email [email protected].

Ethereum Development Solidity Etherjs Dapps

Sign up for BlockChannel


By BlockChannel

An educational new media org (+show) focused on the sociocultural/cryptoeconomic issues related to
blockchains/crypto. Take a look.

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 12/13
2/13/23, 1:31 AM Build an Ethereum DApp Using Ethers.js | by BlockChannel | BlockChannel | Medium

Open
Emails in
willapp
be sent to [email protected]. Not you? Get unlimited access

Get this newsletter


Search Medium

https://medium.com/blockchannel/build-an-ethereum-dapp-using-ethers-js-a1b1930d332 13/13
2/13/23, 1:34 AM Blockchain interaction using Ethers.js | Coinmonks

Published in Coinmonks

Chikku George Follow

Oct 15, 2022 · 3 min read · Listen

Save

BLOCKCHAIN SERIES

How to Interact with Blockchain using Ethers.js


Utilizing ethers, read data and send transactions on the blockchain

Ethers.js
Ethers.js is a library that allows us to connect with the Ethereum Blockchain and its
ecosystem. We can use ethers to connect to Ethereum nodes through JSON-RPC,
https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8 1/6
2/13/23, 1:34 AM Blockchain interaction using Ethers.js | Coinmonks

Infura, Alchemy, Cloudflare, or Metamask.

Installation

npm install ethers

Authentication
Crypto wallets like Metamask, Coinbase, TrustWallet, and Phantom are used to
connect to the blockchain. They provide an entry point to every decentralized
application. We can install crypto wallets as add-ons or plugins to our browsers.

When we add crypto wallets as an extension to our browsers, they automatically inject
themselves into the browser window object. For example, If we add the Metamask
extension, it injects an ethereum object into the browser window.

Establish Provider Connection


Ethers.js library makes it easy to connect to any node in a blockchain. We can either
use the default provider given by the browser extension or third-party RPC providers
like Alchemy, Infura, and Moralis.

Credits: Author

Fetch Wallet Balance

https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8 2/6
2/13/23, 1:34 AM Blockchain interaction using Ethers.js | Coinmonks

After initializing the provider, we can invoke the provider method, getBalance() to
fetch the balance of an ethereum account.

Credits: Author

Handling BigNumber
In Ethereum, many operations are performed on numbers that are outside the range
of values in javascript, called BigNumbers. Ethers.js helps us to convert BigNumbers
into numbers that are in human readable format.

Credits: Author

Create Signer

https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8 3/6
2/13/23, 1:34 AM Blockchain interaction using Ethers.js | Coinmonks

A signer is an abstraction of a blockchain account that is used to sign messages and


send transactions on the blockchain. After initializing the provider, we can create a
signer from it.

Credits: Author

Send Transactions
We can use the signer to send the transaction. A transaction object might contain from
and to addresses, the token value to be sent, the gas price, and the gas limit.

Credits: Author

Interaction with Smart Contract


We can connect to a smart contract and invoke the methods specified in contract ABI
using the signer. ABIs are written in JSON format. It contains details on smart
contracts, such as what functions are available, how to use them, and how to retrieve
data from them.

https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8 4/6
2/13/23, 1:34 AM Blockchain interaction using Ethers.js | Coinmonks

For example, if your ABI contains a balanceOf() function, we can invoke the method as
follows:

Credits: Author

Thank You:)

New to trading? Try crypto trading bots or copy


Open in app Get unlimited access

tradingSearch Medium

Ethersjs Blockchain Send Transactions Blockchain Interaction

Ethereum Blockchain

10

Sign up for Coinmonks


By Coinmonks

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

https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8 5/6
2/13/23, 1:34 AM Blockchain interaction using Ethers.js | Coinmonks

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

Get this newsletter

https://medium.com/coinmonks/how-to-interact-with-blockchain-using-ethers-js-7d0be4a8a6e8 6/6
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

Aw Kai Shin Follow

Sep 27, 2022 · 6 min read · Listen

Save

Connect Metamask with Ethers.js


The Ethers.js library enables us to easily interact with the Ethereum blockchain using
Javascript. As such, it significantly speeds up the development process for web
applications which have to interface with EVM blockchains. We had previously
explored how to connect Metamask to our web app without the use of convenience
libraries here:

Connecting Metamask to your Web Application (Express)

This guide extends upon the above and describes how much more intuitive Ethers.js is
through implementing a simple ETH transfer form running in your Express app.
Through this transfer, you will be able to see how your web app is able to:

Run Ethers.js in the browser (using Browserify)

Expose the Metamask account as a Javascript object

Create and sign an Ethereum transaction request

Send the signed transaction request to the network

View the transaction receipt returned from the network

The Github repository for this guide can be found here. If you would like to configure
Metamask, you can refer to a separate guide:

Connecting Metamask with a Local Hardhat Network

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 1/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

Further info on how to deploy and interact with smart contracts (tokens, NFTs,
decentralised storage):

ERC20 Using Hardhat: An Updated Comprehensive Guide

ERC721 Using Hardhat: An Updated Comprehensive Guide To NFTs

Creating Truly Decentralised NFTs — A Comprehensive Guide to ERC721 & IPFS

Create form to send ETH


As we will be building on top of the previous guide, we will first need to clone the
Github repository and install the dependencies:

git clone https://github.com/0xKai27/ExpressMetamask.git


npm install

Once the installation is complete, you can run nodemon start and you should see the
following when visiting localhost:3000 in the browser:

You can refer to this guide if you would like further details on how we managed to get
the above connection with vanilla node.js. With the base application working, we can
https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 2/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

then start adding our form.

Navigate to the index.ejs file located in the /views directory and copy and paste the
following code:

1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title><%= title %></title>
5 <link rel='stylesheet' href='/stylesheets/style.css' />
6 </head>
7 <body>
8 <h1><%= title %></h1>
9 <button class="enableEthereumButton">Connect to Metamask</button>
10 <h2>Account: <span class="showAccount"></span></h2>
11 <h2>Chain ID: <span class="showChainId"></span></h2>
12 <br>
13 <h1>Send ETH using Web App</h1>
14 <form id="sendETH">
15 <h2>Send to:</h2>
16 <input type="text" id="addressTo"/>
17 <h2>Amount in ETH:</h2>
18 <input type="number" id="ETHAmount"/>
19 <br>
20 <button>Send ETH</button>
21 </form>
22 <script src="javascripts/index.js"></script>
23 <script src="javascripts/bundle.js"></script>
24 </body>
25 </html>

MetamaskExpressEthers - index.ejs hosted with ❤ by GitHub view raw

Our form will have two inputs:

addressTo : The recipient address

ETHAmount : The amount to send denominated in ETH

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 3/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

Also note that we have included an additional bundle.js script which will contain the
logic for our form. Save the file and nodemon would have refreshed the page.

Now it’s time to link the form to our backend code.

Script to connect with Metamask


In the main project directory, create a provider.js file:

touch provider.js

This file will contain the required logic linking together Metamask and Ethers.js (we
will get to the bundle.js file in the next section). As such, we first need to install the
Ethers.js library:

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 4/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

npm install ethers

We can then copy and paste the following into the newly created provider.js :

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 5/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

1 const { ethers } = require("ethers");


2
3 // Get the provider and signer from the browser window
4 const provider = new ethers.providers.Web3Provider(window.ethereum);
5 const signer = provider.getSigner();
6
7 // Initialise the document objects
8 const sendETH = document.querySelector('#sendETH');
9 const addressTo = document.querySelector('#addressTo');
10 const ETHAmount = document.querySelector('#ETHAmount');
11
12 sendETH.addEventListener('submit', async(e) => {
13 e.preventDefault();
14
15 // Get the form values
16 const addressToValue = addressTo.value;
17 const ETHAmountValue = ETHAmount.value;
18 // Calculate amount to transfer in wei
19 const weiAmountValue = ethers.utils.parseEther(ETHAmountValue) //parseInt(ETHAmountValue) * 10**
20
21 // Form the transaction request for sending ETH
22 const transactionRequest = {
23 to: addressToValue.toString(),
24 value: weiAmountValue.toString()
25 }
26
27 // Send the transaction and log the receipt
28 const receipt = await signer.sendTransaction(transactionRequest);
29 console.log(receipt);
30
31 })

MetamaskExpressEthers - provider.js hosted with ❤ by GitHub view raw

Line 4 and 5 are actually the key lines of code which exposes the Metamask account for
us to use in our application. It creates two objects:

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 6/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

provider : An abstraction of a connection to the Ethereum network (ie alchemy,


infura, etc). In other words, which is the service provider that our application is
using to connect to the Ethereum network.

signer : An abstraction of an Ethereum Account. This is the object which we can


use to sign and send transactions.

To make the above more concrete, the rest of the code implements the required form
logic to send an ETH transaction. The form components are first initialised and their
respective values are stored in addressToValue and ETHAmountValue . Based on the
ETHAmountValue , we also convert the amount in ETH to WEI using the Ethers.js utils,
whereby 1 ETH is equal to 10^18 wei.

These 2 values then form part of the full transactionRequest . For the
transactionRequest to be successful, there are a number of other variables which have
to be filled prior to transacting (gas price, nonce, etc.). Note that you can view the
complete transactionRequest structure on the Ethers.js docs.

Fortunately, Ethers.js provides a handy sendTransaction function which also


conveniently populates the transaction based on the signer object. sendTransaction()

forms the full transaction and submits the transaction to the network. A promise
containing the transaction receipt hash is then returned and logged in the console.

Browserify: Running Ethers.js in the Browser


While we have written out the logic required to connect Metamask, we now run into an
issue as we are unable to import the Ethers.js module into our browser where our
script will run. Recall that this script will be hosted on the client’s browser and
therefore needs to be served as a static file as opposed to running on our local server.
This is the reason why our code also references window.ethereum which is a property of
the browser’s window object.

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 7/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

Browserify provides just the tooling required enabling us to run Ethers.js (or any other
require module) in the browser. We can install it globally by using the command
below:

npm install -g browserify

Once installed, we can use browserify --help to access the list of options. For our
purposes, we will be defining an output file path using the -o flag:

browserify app.js -o public/javascripts/bundle.js

The above will create the bundle.js file in the public directory which static assets are
served from. Note that our index.ejs file also contains a script tag referencing this
path. Once bundle.js has been generated, nodemon would have automatically
refreshed our application and it should now be working.

Sending Test Ethers


In order to test the form, we will be connecting to our Hardhat test network which we
setup previously here. Once connected, refresh the network bootstrap state by
running:

npx hardhat node

With Metamask connected to our Hardhat network, we should be able to see 10,000
HARDHATETH in both our imported test accounts.

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 8/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

For this test, we will be transferring 32 HARDHATETH from Hardhat1 to Hardhat2. Copy
the Hardhat2 address from Metamask and paste it into the “Send to:” box. For the
“Amount in ETH:”, we can put in the ETH denominated amount which is 32 .

Upon clicking the “Send ETH” function, Metamask should prompt you to confirm the
transaction. Note that you might need to reset the account or enable a custom nonce if

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 9/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

the account was previously used for testing on another network.

On clicking “Confirm”, you will then be able to see the transaction receipt being
printed into the browser’s console.

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 10/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

Additionally, the Hardhat network console would have also logged the incoming
transaction which is pending network confirmation. You can monitor the network
console to see what other functions are called once the transaction has been “mined”
by the network.

Upon transaction success, Metamask should then reflect the respective balances as
well as the transaction status.

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 11/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

Open in app Get unlimited access

Search Medium

Congrats, you have successfully connected Ethers.js to Metamask and even


implemented a send function!

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 12/13
2/13/23, 1:37 AM Connect Metamask with Ethers.js. The Ethers.js library enables us to… | by Aw Kai Shin | Medium

Thanks for staying till the end. Would love to hear your thought/comments so do drop a
comment. I’m active on twitter @AwKaiShin if you would like to receive more digestible
tidbits of crypto-related info or visit my personal website if you would like my services :)

Metamask Ethersjs Express Web 3 Guides And Tutorials

Enjoy the read? Reward the writer.Beta


Your tip will go to Aw Kai Shin through a third-party platform of their choice, letting them know you appreciate their story.

Give a tip

https://medium.com/@kaishinaw/connect-metamask-with-ethers-js-fc9c7163fd4d 13/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

Published in Coinmonks

Mohamed Noushad Follow

Jun 25, 2018 · 6 min read · Listen

Save

‘Hello World’ Smart Contract using Ethers.js


Ethers.js is an alternative to web3.js and is designed to make it easier to communicate
with Ethereum Blockchain. Well, Using Keythereum along with Ethers.js helps us to
implement wallet function saving private key on the client side which we will see in
detail in part 2 of this series which will be released soon.

Blockchain is the solution to the real world problems and Ethers.js is one of our tool to
realize it.

We will walk through this in three sections:


https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 1/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

1. Smart Contract

2. Deploying the smart contract to Ethereum Rinkeby Testnet

3. Communicating with the contract from Nodejs

New to trading? Try crypto trading bots or copy


trading
1. Smart Contract

1 pragma solidity ^0.4.18;


2
3 contract HelloWorld {
4
5 string public name;
6
7 function setValue(string _name) returns (string){
8 name = _name;
9 return name;
10 }
11
12 function getValue() public constant returns (string){
13 return name;
14 }
15
16 }

gistfile1.txt hosted with ❤ by GitHub view raw

2. Deploying Smart Contract to Ethereum Rinkeby Testnet


To deploy this smart contract we need to have Metamask plugin installed on our google
chrome browser and account should be loaded with sufficient ether. Please refer to the
below guide, if you are new to installing metamask.

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 2/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

How to use MetaMask for Chrome


MetaMask is an Ethereum extension for your browser. It connects you to
Ethereum applications (called dApps) easily and…
blog.ujomusic.com

Switch your network to Rinkeby testnet and copy your address. Anyone having a
Twitter, Google+ or Facebook account may request funds within the permitted limits
from https://faucet.rinkeby.io/.

I am going to use twitter where my account address is


0x7c477A59578710eC7bfD2bf29D7a24F53A33979a.

I will now tweet with this address and copy the tweet link to paste it in faucet.

Copying the tweet to use it in the faucet to load ethers

Paste the tweet link in Rinkeby faucet and request ethers as shown in the picture
below.

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 3/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

Load 18.75 Ethers for 3 days

Upon success, you will be able to see 18.75 Ether as balance in your account address in
Metamask.

Well, now we have to deploy our smart contract to Ethereum Rinkeby Testnet from
online IDE called Remix. Open Remix at: http://remix.ethereum.org

Deploying Smart Contract

Please ensure to use Environment as Injected Web3 and when you press the Deploy
button, Metamask popup appears asking you to confirm by submitting the
transaction. Once you submit the transaction, you will be able to see the Rinkeby
transaction link explorer beneath in the Remix console. Once you click on the link, the
transaction can be viewed in the Rinkeby Etherscan as shown below.

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 4/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

When the contract creation is successful, the TxReceiptStatus: will show ‘Success’ and
please take note of the ‘To’ address which we will have to use later once we have to
communicate with the Blockchain contract from our Nodejs app.

In my case, the To address is 0x74a9a20f67d5499b62255bfa1dca195d06aa4617.

Now from Remix IDE, we need to copy the ABI which is the Application Binary
Interface with which is also required to communicate with the smart contract later. In
Remix, under the ‘Compile’ tab, click on ‘Details’ where you will see ABI. Click just
right to ABI to copy it. You may use a JSON uglifier(http://jsonmate.com/) to uglify the
obtained ABI and it will look like this.

1 [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false

newabi.js hosted with ❤ by GitHub view raw

3. Communicating with Smart Contract from Nodejs


Now we have the address where our contract lives and also the ABI which are enough
for us to communicate with our smart contract from Nodejs. We need to use the
module ‘ethers’ to communicate with the contract.

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 5/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

Go to your working directory and type ‘npm init’ from your command line to create the
package.json file. Please note that you need to have ‘node’ and ‘npm’ installed in your
system.

Now, we can install ethers module by executing ‘npm install — save ethers@3’ which
will install ethers node modules in the directory.

‘Please note that at the time of writing this, it was ethers version 3, but now ethers has gone to
newer versions and hence when you are installing ethers with npm, you have to use npm
install — save ethers@3’.

Now create setvalue.js file in the same directory with the below contents.

1 var ethers = require('ethers');


2 var provider = ethers.providers.getDefaultProvider('rinkeby');

firstsetvalue.js hosted with ❤ by GitHub view raw

‘Please note that at the time of writing this, the ethers version 3 supported directly accessing
the infura rinkeby node by calling provider in the above method. However, now infura has
changed and you have to create an account with infura and you will get a project id for free. I
have created one and a sample of how the new provider initialisation has to be done is given
below.

var provider = new


ethers.providers.JsonRpcProvider(“https://rinkeby.infura.io/v3/62349edb
370e4523b328b8823d211551",“rinkeby”);
where 62349edb370e4523b328b8823d211551 is my project id. Please take care to replace
everywhere in the following with this provider. Please do not spam.

This sets the network provider to be Rinkeby testnet. Now we need to add the address
where the contract lives and also the ABI which we have obtained from Step 2.

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 6/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

1 var ethers = require('ethers');


2 var provider = ethers.providers.getDefaultProvider('rinkeby');
3
4 var address = '0x74a9a20f67d5499b62255bfa1dca195d06aa4617';
5
6 var abi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"paya

secondsetvalue.js hosted with ❤ by GitHub view raw

3.1 Setting Hello World


Now our smart contract has two functions, one is to set a value and the other is to get
the value. Please note that setting a value is changing the state of the smart contract
where a transaction has to take place while getting the value does not invoke state
change and is a constant function.

So, to set the value, we have to sign the transaction with the private key of the account
from which we are communicating with the smart contract. We can get the private key
of the account from the Metamask. Click on ‘Export Private Key’ from Metamask and
provide your password.

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 7/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

Exporting Private Key From Metamask

The obtained private key for me is


3ab6468f2465130c51946a5456b8e2d309be7af2f8afcd6823996d281c0990d0.

We have to add prefix 0x to make it hex and hence the private key will be
0x3ab6468f2465130c51946a5456b8e2d309be7af2f8afcd6823996d281c0990d0.

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 8/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

1 var ethers = require('ethers');


2 var provider = ethers.providers.getDefaultProvider('rinkeby');
3 var address = '0x74a9a20f67d5499b62255bfa1dca195d06aa4617';
4 var abi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"paya
5
6 var privateKey = '0x3ab6468f2465130c51946a5456b8e2d309be7af2f8afcd6823996d281c0990d0';

withprivatekey hosted with ❤ by GitHub view raw

Now we have to have the wallet functionality provided by Ethers.js to sign our
transaction and the Contract functionality which initializes the contract to
communicate with it as shown below.

1 var ethers = require('ethers');


2
3 var provider = ethers.providers.getDefaultProvider('rinkeby');
4 var address = '0x74a9a20f67d5499b62255bfa1dca195d06aa4617';
5 var abi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"pay
6 var privateKey = '0x3ab6468f2465130c51946a5456b8e2d309be7af2f8afcd6823996d281c0990d0';
7
8 var wallet = new ethers.Wallet(privateKey,provider);
9
10 var contract = new ethers.Contract(address,abi,wallet);

walletandcontract. hosted with ❤ by GitHub view raw

Lets now call the setValue function by setting ‘Hello World’ as the parameter.

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 9/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

1 var ethers = require('ethers');


2 var provider = ethers.providers.getDefaultProvider('rinkeby');
3 var address = '0x74a9a20f67d5499b62255bfa1dca195d06aa4617';
4 var abi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"pay
5 var privateKey = '0x3ab6468f2465130c51946a5456b8e2d309be7af2f8afcd6823996d281c0990d0';
6 var wallet = new ethers.Wallet(privateKey,provider);
7 var contract = new ethers.Contract(address,abi,wallet);
8
9 var sendPromise = contract.setValue('Hello World');
10
11 sendPromise.then(function(transaction){
12 console.log(transaction);
13 });

setvalue.js hosted with ❤ by GitHub view raw

Now from your working directory, run ‘node setvalue.js’ to call setValue function
setting the value to ‘Hello World’.

You will be able to see the transaction as shown below in the console.

1 { nonce: 170,
2 gasPrice: BigNumber { _bn: <BN: 3b9aca00> },
3 gasLimit: BigNumber { _bn: <BN: 16e360> },
4 to: '0x74a9A20F67D5499b62255bFA1dca195d06Aa4617',
5 value: BigNumber { _bn: <BN: 0> },
6 data: '0x93a093520000000000000000000000000000000000000000000000000000000000000020000000000000000
7 v: 44,
8 r: '0xfb70c60eed8f47c3be8f3ca15c27906263243f7954632844505f43385789702f',
9 s: '0x4ef8cce0c804bba2b2730e95437d56dd9da14f307358167ccaa7d74c2ca954db',
10 chainId: 4,
11 from: '0x7c477A59578710eC7bfD2bf29D7a24F53A33979a',
12 hash: '0x52704193c2b9a27f3028dae18287caed12c6d27dc49057b31247c022074e6191',
13 wait: [Function] }

transaction.js hosted with ❤ by GitHub view raw

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 10/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

3.2 Getting HelloWorld


As I mentioned, getting the value is a constant function which does not change the
state of the blockchain, so we dont need to sign he transaction or use wallet feature
from Ethers.js. So, instead of wallet as a parameter in contract, we will just use
provider which is enough to communicate with the blockchain.

1 var ethers = require('ethers');


2 var provider = ethers.providers.getDefaultProvider('rinkeby');
3 var address = '0x74a9a20f67d5499b62255bfa1dca195d06aa4617';
4 var abi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"paya
5
6
7 var contract = new ethers.Contract(address,abi,provider);

getvaluefirst.js hosted with ❤ by GitHub view raw

Now we will call the getValue function as shown below.

1 var ethers = require('ethers');


2 var provider = ethers.providers.getDefaultProvider('rinkeby');
3 var address = '0x74a9a20f67d5499b62255bfa1dca195d06aa4617';
4 var abi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"pay
5 var contract = new ethers.Contract(address,abi,provider);
6
7 var callPromise = contract.getValue();
8
9 callPromise.then(function(result){
10 console.log(result);
11 });

callPromise.js hosted with ❤ by GitHub view raw

Now from your working directory, run ‘node callPromise.js’ to get the returned value
from the smart contract function getValue().

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 11/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | Coinmonks | Medium

You will be able to see the returned ‘Hello World’ in


your console.
Thank you for reading and feel free to clap aside if you found this worth.

Join Coinmonks Telegram Channel and Youtube


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

Grid Trading | Crypto Hardware Wallet

Crypto Telegram Signals | Crypto Trading Bot

Best Crypto Exchange | Best Crypto Exchange in India


Open in app Get unlimited access
Best Crypto APIs for Developers
Search Medium
Best Crypto Lending Platform

Free Crypto Signals | Crypto Trading Bots

An ultimate guide to Leveraged Token

Ethereum Smart Contracts Ether Dapps Web 3

Sign up for Coinmonks


By Coinmonks

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 12/13
2/13/23, 1:41 AM ‘Hello World’ Smart Contract using Ethers.js | by Mohamed Noushad | 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.

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

Get this newsletter

https://medium.com/coinmonks/hello-world-smart-contract-using-ethers-js-e33b5bf50c19 13/13
2/13/23, 1:43 AM Interact With Smart Contracts Via etherJs | by Sathish Kumar Sundaram | Medium

Sathish Kumar Sundaram Follow

Jun 3, 2020 · 2 min read · Listen

Save

Interact With Smart Contracts Via etherJs


3 Simple Steps to Interact with Smart contract using etherjs.

3 Simple Steps to Interact with Smart Contract

The Complete tutorial you can find in Tutorial Wiki → Examples → EtherJs API.

Dynamic deployment of smart contract I have provided in my other blog please go


through.

https://medium.com/@sundar.sat84/interact-with-smart-contracts-via-etherjs-44f49dcee7b0 1/4
2/13/23, 1:43 AM Interact With Smart Contracts Via etherJs | by Sathish Kumar Sundaram | Medium

Prerequisite :

1. You need Infura Account Or any TestNets Or Your Private Ethereum Account Or
Ganache.

2. Deploy smart contract As I mentioned in my other blog. Or deploy using Truffle Cli
in any one of the networks.

Assumption :

Your private network is ready & Smart contract were deployed. I have provided very
detailed setup in my other blog.

Invoke Smart Contract :

Step 1 : Create index.html file and add below script in body tag.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Ether Js</title>
<title>Invoke Smart Contract Using Ether.jS </title>
</head>
<body>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
></script>
<script src="https://cdn.ethers.io/scripts/ethers-v4.min.js"
charset="utf-8" type="text/javascript"></script>
</body>
</html>

The above script will download Jquery & EtherJs when open through browsers. Now
Need to write Javascript onload function to intract with our smart contract

Step 2 : Define below properties in another sctipt tag and replace the actual values.

https://medium.com/@sundar.sat84/interact-with-smart-contracts-via-etherjs-44f49dcee7b0 2/4
2/13/23, 1:43 AM Interact With Smart Contracts Via etherJs | by Sathish Kumar Sundaram | Medium

<script>
//provider from ganache network. Or Infura account.
let url = "http://localhost:8454";
//Base address not the deployed smart contract address
//You should have enough ethers. If not get it using Faucets.
let baseAddress = "base address"
let privateKey = "private key of base address";
let contract_address = 'smart contract address to invoke';
let abi = [
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "x",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "get",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function",
"constant": true
}
];
</script>

Step 3 : Sign and Sumit the transaction to invoke multiple smart contract methods.

https://medium.com/@sundar.sat84/interact-with-smart-contracts-via-etherjs-44f49dcee7b0 3/4
2/13/23, 1:43 AM Interact With Smart Contracts Via etherJs | by Sathish Kumar Sundaram | Medium

<script>

$(window).on('load', function() {
invokeNewContract();
});

async function invokeNewContract() {


let provider = new ethers.providers.JsonRpcProvider(url);
let contract = new ethers.Contract(contract_address,abi,provider);
let contractWithSigner = await contract.connect(wallet);
let tx = await contractWithSigner.set(10);
await tx.wait();
//get the value back.
let val = contractWithSigner.get();
console.log(val);
alert("Welcome!. Your Contract Invoked Successfully." + val);
}
</script>

When you open the index.html file your code will run and you can see the result in
console.log
Open in app & alert box. Get unlimited access

Search Medium

Smart Contracts Ethereum Blockchain Ethereum Development Blockchain

Blockchain Technology

https://medium.com/@sundar.sat84/interact-with-smart-contracts-via-etherjs-44f49dcee7b0 4/4
2/13/23, 1:48 AM What is Infura. In this article I would like to… | by BlueSmoke | What is Infura | Medium

Published in What is Infura

BlueSmoke Follow

Sep 11, 2020 · 4 min read · Listen

Save

What is Infura
In this article I would like to introduce to the community what Infura is and how it
works. Since most beginners and experienced “Players for Keep” do not know what it is
and what it is for, I decided to figure it out. The article turned out to be quite difficult to
understand from a technical point of view, but I tried to simplify it for general
understanding.

Infura is a kind of node storage (cluster). A set of tools that provides its services for
integrating your application with the Ethereum network.

With its help, we successfully remove one of the most difficult barriers to blockchain
adoption. Running a node requires a decent level of technical knowledge, patience,
processing power, and memory. Using an app like Infura makes it unnecessary for us.

https://medium.com/what-is-infura/what-is-infura-59dbdd778455#:~:text=Infura is a kind of,difficult barriers to blockchain adoption. 1/5


2/13/23, 1:48 AM What is Infura. In this article I would like to… | by BlueSmoke | What is Infura | Medium

Infura aims to make life easier for developers. Some of the major network problems
include:

• Storing data in Ethereum is expensive.

• It is difficult to connect on your own to the Ethereum blockchain.

• Blockchain synchronization is slow.

• Ethereum blockchain takes up a lot of space.

By eliminating the need for developers and companies to maintain the nodes
themselves, Infura offers certain benefits:

• Access to the Ethereum blockchain is getting much faster.

• By managing nodes, developers don’t need to worry about infrastructure constraints.

• Instead of keeping everything in a chain, data can be stored separately, keeping only
the hash in the blockchain.

And here’s what the developers say about the project:

• Mainnet and Testnet support with client-compatible JSON-RPC request over HTTPS
and WSS.

• Support for standard IPFS libraries for storing and retrieving data on the network.

• Connecting an application with one line of code. No need for synchronization and
complex settings.

• 99.9% uptime guaranteed with the latest network updates.

• Customize, monitor and analyze your applications with Infura.

• 24/7 access to support specialists and our community of experienced developers.

But on the other hand, since Infura is a centralized service, it creates additional
potential threats and therefore it is vulnerable to attacks from hackers that can limit its

https://medium.com/what-is-infura/what-is-infura-59dbdd778455#:~:text=Infura is a kind of,difficult barriers to blockchain adoption. 2/5


2/13/23, 1:48 AM What is Infura. In this article I would like to… | by BlueSmoke | What is Infura | Medium

functionality, and it can also be used to censor transactions by third persons.


Consequently, all applications that use Infura are inherently centralized, which in turn
breaks the concept of the entire blockchain — decentralization and anonymity.

Basic project information


Some numbers about Infura’s growth:

• Over 40,000 registered developers.

• Serving over 10 billion API requests per day.

• Transferring approximately 1.6 petabytes of data per month.

• In 2017, there were broadcasted transactions that moved more than 7 million Ethers,
in 2018 there were almost 9 million.

Infura essentially provides the necessary tools for any application to start developing
anything on Ethereum, without having to run complex infrastructure by your own.
Infura provides connectivity for all developers using the Ethereum blockchain.

The most famous part of Infura’s infrastructure is the Ethereum hosted client network,
which spans four Ethereum networks:

• Mainnet

• Ropsten

• Rinkeby

• Kovan

These are load-balanced groups of nodes that can be easily scaled to meet demand and
kept up to date and secure.

Ether nodes are only one part of the Infura stack. They also host the Inter Planetary
File System (IPFS) nodes and the IPFS public gateway. The project is in the process of
creating additional decentralized storage products based on both IFP and Swarm,
which the developers will review in detail in the near future.
https://medium.com/what-is-infura/what-is-infura-59dbdd778455#:~:text=Infura is a kind of,difficult barriers to blockchain adoption. 3/5
2/13/23, 1:48 AM What is Infura. In this article I would like to… | by BlueSmoke | What is Infura | Medium

One of the central elements of the Infura architecture is the middle tier called
Ferryman.

Ferryman is the inner layer of Infura middleware that provides intelligent routing that
allows requests to be sent to different ends of the Infura infrastructure based on RPC
and other factors. This provides the ability to scale and customize part of the
infrastructure depending on the traffic needs. Intelligent routing can ensure that
incoming requests do not need to be removed across the site in real time, and response
times are greatly reduced.

Infura’s modular scaling solutions open up significant network bandwidth for any
project expected to drive large volumes of traffic across the Ethereum network.

Infura does not store accounts and therefore you cannot use Infura to sign
transactions. Instead this, use Infura for one-time access and gas calculations. You will
have to use your own middleware to process the actual signature, as this will require
your private key.

Mission and goals


There are worthy alternatives right now. Developers tend to stress the need for more
people to run their own nodes, and that nodes are a relatively affordable solution for
most users. Own nodes do not require the same processing power and memory as full
node synchronization.

Infura is designed for:

• DApps of users.

• DApp developers.

• The Ethereum community in general.

So what are the benefits of Infura? Infura provides:

• Ethereum and IPFS (Inter-Planetary File System).

• Server infrastructure for automatic CI / CD deployment.

https://medium.com/what-is-infura/what-is-infura-59dbdd778455#:~:text=Infura is a kind of,difficult barriers to blockchain adoption. 4/5


2/13/23, 1:48 AM What is Infura. In this article I would like to… | by BlueSmoke | What is Infura | Medium

• Improvements to Ethereum server products.

• Improvements to IPFS server products.

The main goal of the project is to facilitate access to Ethereum and the opportunities
that it provides.

“The huge potential of Etnerium can only be fully realized through large-scale
implementation. Over the past two years, this has put us in a privileged position to
witness the growth of the Ethereum ecosystem, and this growth has been explosive for
both Ethereum and us. ” — said Nicola Cocchiaro, lead developer of Infura.

Сollaborating projects

Open in app Get unlimited access

Search Medium

Most of the most valuable blockchain projects such as Metamask, CryptoKitties, UJO,
Radar Relay, Cipher Browser, uPort and others use the Infura API to connect their
applications to the Ethereum network.

Blockchain Ethereum Keep Network

https://medium.com/what-is-infura/what-is-infura-59dbdd778455#:~:text=Infura is a kind of,difficult barriers to blockchain adoption. 5/5


2/13/23, 1:50 AM Getting Started With Infura. A step-by-step tutorial to help you get… | by Michael Wuehler | Medium

Michael Wuehler Follow

Sep 6, 2016 · 6 min read · Listen

Save

Getting Started With Infura


A step-by-step tutorial to help you get set-up with Infura and start
using the Infura Ethereum API.
Updated 01/14/2020

Hey there, welcome to Infura! If you’ve never heard of us before, Infura provides
developers and enterprises with simple, reliable access to Web3 tools and
infrastructure. Our Ethereum and IPFS API suite serves and supports thousands of
decentralized applications every day.

In this post, we’ll walk you through how to get started with Infura so you can connect
to the Ethereum blockchain and start building awesome software.

We’ll cover:

Signing up for an account;

Creating a new project;

Security features like whitelisting and how to protect your project credentials;

Making requests.

Step One: Register


The first thing to do is to head to Infura.io and create an account. Protecting user
information is one of our core values. That’s why you’ll notice that the only bit of info

https://medium.com/@wuehler/getting-started-with-infura-28e41844cc89 1/10
2/13/23, 1:50 AM Getting Started With Infura. A step-by-step tutorial to help you get… | by Michael Wuehler | Medium

required to register an account is an email address. You can add your name if you like,
but it’s not necessary.

Infura only uses your email address to communicate with you about critical service
updates that may impact your usage. New product and features releases, offers,
industry, company and event news are communicated through our newsletter. Our
newsletter is opt-in so we strongly recommend you subscribe to keep up to-date with
the latest Infura product news, tips and tricks.

You need to verify your email address, by clicking the link sent to your inbox, before
your account can be activated.

Step Two: Create a Project


Once verified, you’ll be taken to your Infura Dashboard. From here, you can take a
product tour (strongly recommend), or create your first project:

https://medium.com/@wuehler/getting-started-with-infura-28e41844cc89 2/10
2/13/23, 1:50 AM Getting Started With Infura. A step-by-step tutorial to help you get… | by Michael Wuehler | Medium

You can test your new API credentials by sending a curl request inside terminal or
command prompt where your Project ID is appended to the end of your request URL:

https://<network>.infura.io/v3/YOUR-PROJECT-ID

Be sure to replace YOUR-PROJECT-ID with a Project ID from your Infura Dashboard


and <network> with the network you are trying to connect to, e.g. mainnet or rinkeby.
You can view a full list of networks we support here, or check your project settings.

Authenticating using a Project ID and Project Secret


In addition to a Project ID, each project also has a Project Secret for sending requests.
As additional protection for your request traffic, you should use HTTP Basic
Authentication to securely send requests with your project secret.

Your Project ID doesn’t need to be kept secret, but, your Project Secret should never be
human readable in your application — be sure to keep it confidential! If you are
concerned that your ID and secret have been compromised, you can easily create a
new project and generate a new pair.

Remember, never expose your PROJECT_SECRET in client-side code such as Javascript


imported into a webpage or iOS or Android apps. Use the other options for securing
public project IDs instead:

curl — user :YOUR-PROJECT-SECRET \

https://medium.com/@wuehler/getting-started-with-infura-28e41844cc89 3/10
2/13/23, 1:50 AM Getting Started With Infura. A step-by-step tutorial to help you get… | by Michael Wuehler | Medium

https://<network>.infura.io/v3/YOUR-PROJECT-ID

Step Three: Copy Your Keys and Select Your Endpoint


Next, select which Ethereum endpoint you want to connect to. This could be the
Ethereum mainnet, or it could be to a test network, like Kovan, Goerli, Rinkeby, or
Ropsten.

Copy the endpoint URL. This is the URL that your app will use to send API requests
from your decentralized applications. It is your main connection point to the
Ethereum blockchain.

Using these endpoint URLs removes any need for you to set up and run your own
infrastructure.

https://medium.com/@wuehler/getting-started-with-infura-28e41844cc89 4/10
2/13/23, 1:50 AM Getting Started With Infura. A step-by-step tutorial to help you get… | by Michael Wuehler | Medium

Step Four: Control How Your API Can Be Used — Enable Your Custom
Security Settings.
If you are sending API requests from a web browser, or other client-side application
that does not have the ability to secure your Project Secret, whitelisting can be used to
prevent a third party from using your Project ID on another website.

https://medium.com/@wuehler/getting-started-with-infura-28e41844cc89 5/10
2/13/23, 1:50 AM Getting Started With Infura. A step-by-step tutorial to help you get… | by Michael Wuehler | Medium

Understanding Whitelist Behavior


If a project has no whitelists enabled, any request will be accepted;

As soon as any whitelist entries are added, all requests must pass each whitelist
type;

Each whitelist type is “AND”ed together;

Multiple entries of the same type are “OR”ed;

Protecting a client-side credential can be simple or complex depending on the


scenario. Use the whitelist features that best fit your application. Don’t just use the
User-Agent or Origin whitelist, use both whenever possible.

Step Five: You’re Set Up— Now, Start Making Requests!

https://medium.com/@wuehler/getting-started-with-infura-28e41844cc89 6/10
2/13/23, 1:50 AM Getting Started With Infura. A step-by-step tutorial to help you get… | by Michael Wuehler | Medium

Start interacting with Ethereum data by sending data requests using HTTP or
Websockets. To get you started, here’s an example of how to send requests for two
common use cases — and the data that will be returned returned:

(i) Retrieve the Current Block Number


Below is a simple command you can run to retrieve the current block number.
Remember, you need to use your own unique project ID in place of YOUR-PROJECT-ID:

curl https://mainnet.infura.io/v3/YOUR-PROJECT-ID \
-X POST
-H “Content-Type: application/json”
-d ‘{“jsonrpc”:”2.0",”method”:”eth_blockNumber”,”params”: [],”id”:1}’

The response you receive back will look like this:

{“jsonrpc”:”2.0",”id”:1,”result”:”0x8d8abf”}

The data returned is in hexadecimal, prefixed with 0x. If you convert 8d8abf to
decimal, using a tool like RapidTables, the resulting number is 9276095 representing
the block number at the time the query was made.

(ii) Check the Ether Balance For a Given Contract

https://medium.com/@wuehler/getting-started-with-infura-28e41844cc89 7/10
2/13/23, 1:50 AM Getting Started With Infura. A step-by-step tutorial to help you get… | by Michael Wuehler | Medium

For this example, we’ll need a contract address to check. Let’s pick TheDAO Withdraw
contract: 0xBf4eD7b27F1d666546E30D74d50d173d20bca754

curl https://mainnet.infura.io/v3/YOUR-PROJECT-ID \

-X POST \

-H “Content-Type: application/json” \

-d ‘{“jsonrpc”:”2.0",”method”:”eth_getBalance”,”params”:
[“0xBf4eD7b27F1d666546E30D74d50d173d20bca754”, “latest”],”id”:1}’

The response you receive back will look like this:

{“jsonrpc”:”2.0",”id”:1,”result”:”0x1887fd3c2b394d81a33d”}

Once again, by converting the hexadecimal 1887fd3c2b394d81a33d to decimal, you’ll


get back 115845353546137586475837. What does this string of numbers mean? This the
balance of Ether in that contract in wei. You may want to convert this to Ether. If 1
Ether equals 10¹⁸ wei, simply move the decimal eighteen places to the left. Voila! Now
we know there’s a balance of 115845.353546137586475837 Ether in TheDAO Withdraw
contract.

There are more sample queries in our documentation, so head to https://infura.io/docs


and try them out.

Step Six: Use the Infura Dashboard to Gain Insight Into Your Application
Now that you’ve started issuing requests, your dashboard will start populating with
insights on performance and API usage.

Jump into your dashboard regularly to drill down into specific request methods,
bandwidth usage and most active usage times to optimize your app and better
understand your users.

https://medium.com/@wuehler/getting-started-with-infura-28e41844cc89 8/10
2/13/23, 1:50 AM Getting Started With Infura. A step-by-step tutorial to help you get… | by Michael Wuehler | Medium

Open in app Get unlimited access

We’ll be creating more tutorials to help you build with Infura. You can keep up-to-date by
Search Medium
following the Infura blog or subscribing to our newsletter.

https://medium.com/@wuehler/getting-started-with-infura-28e41844cc89 9/10
2/13/23, 1:50 AM Getting Started With Infura. A step-by-step tutorial to help you get… | by Michael Wuehler | Medium

Ethereum Blockchain Java Script Web Development

https://medium.com/@wuehler/getting-started-with-infura-28e41844cc89 10/10
2/13/23, 1:53 AM How to get current block number of Ethereum blockchain | by Hideyoshi Moriya | Medium

Open in app Get unlimited access

Search Medium

Hideyoshi Moriya Follow

May 26, 2018 · 1 min read · Listen

Save

How to get current block number of Ethereum


blockchain
Using web3, you can get the latest block number of Ethereum blockchain by
following code.

const Web3 = require('Web3');


var web3 = new Web3('https://mainnet.infura.io');
web3.eth.getBlockNumber()
.then(console.log);

Ethereum Blockchain Web 3

40

https://piyopiyo.medium.com/how-to-get-current-block-number-of-ethereum-blockchain-a4405f77e1b1 1/2
2/13/23, 1:53 AM How to get current block number of Ethereum blockchain | by Hideyoshi Moriya | Medium

https://piyopiyo.medium.com/how-to-get-current-block-number-of-ethereum-blockchain-a4405f77e1b1 2/2
2/13/23, 1:55 AM Block-STM: How We Execute Over 160k Transactions Per Second on the Aptos Blockchain | by Aptos | Aptos | Medium

Published in Aptos

Aptos Follow

Apr 13, 2022 · 9 min read · Listen

Save

Block-STM: How We Execute Over 160k


Transactions Per Second on the Aptos
Blockchain
World-class engineering meets cutting-edge research at Aptos. For more details please
refer to the Block-STM paper and the Aptos codebase.

By Alexander Spiegelman and Rati Gelashvili

TL;DR: We designed and implemented a highly efficient, multi-threaded, in-memory


parallel execution engine that can execute over 160k non-trivial Move transactions
per second by leveraging the preset order of transactions and combining Software
Transactional Memory techniques with a novel collaborative schedule.

The Challenge
Smart contract execution is a major throughput bottleneck for blockchains. After
proposing blocks and agreeing on their order, validators have to execute the
transactions in the ordered blocks. Crucially, validators must arrive at the same final
state, which must correspond to some sequential execution of the transactions. Due to
the lack of a foundational solution, current blockchains either execute sequentially or
require an embarrassingly parallel workload (i.e. no inner conflicts) for improved
performance. Sequential execution does not scale well, and assuming that all

https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba 1/8
2/13/23, 1:55 AM Block-STM: How We Execute Over 160k Transactions Per Second on the Aptos Blockchain | by Aptos | Aptos | Medium

transactions are commutative is unrealistic when considering a broad range of smart


contracts. In fact, transactions in a blockchain can have a significant number of access
conflicts due to potential performance attacks, accessing popular contracts (e.g. due to
economic opportunities such as auctions and arbitrage).

The Goal
Design a parallel execution engine that extracts the maximum inherent speedup that is
possible, given the actual access conflicts in the workload. For the best programming
and user experience, the algorithm should be transparent to the users. An alternative
approach taken by some blockchain parallel execution engines is to force the user to
declare the dependencies upfront, which severely limits what a transaction can do and
may require a transaction to be broken up or retried. Instead, to avoid incurring such
costs and programming annoyances, a system design goal for our parallel execution
engine is to manage all conflicts internally and automatically adapt to the workload.

The STM Approach


An academic approach pioneered by Software Transactional Memory (STM) libraries is
to instrument memory accesses to detect and manage conflicts. STM libraries with
optimistic concurrency control record memory accesses during execution, validate
every transaction post execution and abort and re-execute transactions when
validation surfaces a conflict. However, due to required conflict bookkeeping and
aborts, STM libraries often suffer from performance limitations compared to custom-
tailored solutions and thus are rarely deployed in production.

The Blockchain Use-Case


It was shown in the past that STM performance can be dramatically increased when
they are applied to specific use-cases. Indeed, three important observations that hold
for the blockchain use-case guide the design of Block-STM.

No need to commit transactions individually: In contrast to general-purpose STMs


(where each thread has an infinite stream of transactions to commit based on
queries that may arrive at arbitrary times), in blockchains, the state is typically
updated per block. This allows Block-STM to avoid the synchronization cost of
committing transactions individually. Instead, Block-STM lazily commits all

https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba 2/8
2/13/23, 1:55 AM Block-STM: How We Execute Over 160k Transactions Per Second on the Aptos Blockchain | by Aptos | Aptos | Medium

transactions in a block with light synchronization. Moreover, garbage collection is


straightforward as the memory can be cleaned up in between the blocks.

VM provides safety for optimistic memory access: Transactions are specified in


smart contract languages, such as Move and Solidity, and run in a virtual machine
that encapsulates their execution and ensures safe behavior. This separates the
abstractions nicely and allows Block-STM to avoid handling the aftermath of
inconsistent states during the parallel speculative execution (a property known as
Opacity).

Pre-defined order reduces synchronization: In general, STM libraries target non-


determinism and view determinism as a limitation in the system, hindering
performance. This makes them unsuitable for the Blockchain use case because
validators executing the same block could result in different final states. However,
in Block-STM, determinism is considered a performance blessing. In fact, the final
outcome is guaranteed to match a sequential execution of transactions in a fixed,
preset order, and this constraint is used to the system’s advantage. This is possible,
as previously noted in the Bohm paper in the context of databases, because
agreeing on a specific serialization reduces the amount of synchronization
required during execution. For example, if there is a conflict between transaction
tx5 and transaction tx9, then tx9 will wait for tx5 — otherwise, without order, the
threads executing these transactions would need to break the tie. Thus, on an
intuitive level, where a general-purpose STM would solve a harder problem (i.e., a
form of consensus), Block-STM targets a simpler problem (i.e., it only needs to
execute transactions).

Core Techniques
Block-STM combines known techniques with novel ideas:

Optimistic concurrency control: Transactions are executed optimistically in


parallel and validated post execution. Unsuccessful validations lead to re-
executions. Due to the preset order, validations are not independent of each other
and must logically occur in a sequence. Unlike prior work, a successful validation
does not imply that the transaction can be committed. On the contrary, a failed

https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba 3/8
2/13/23, 1:55 AM Block-STM: How We Execute Over 160k Transactions Per Second on the Aptos Blockchain | by Aptos | Aptos | Medium

validation of a transaction implies that all higher transactions can be committed


only if they get successfully validated afterward.

Multi-version data structure: Block-STM uses a multi-version data structure to


avoid write-write conflicts. All writes to the same location are stored along with
their versions, which contain their transaction IDs and the number of times the
writing transaction was optimistically re-executed. When transaction tx reads a
memory location, it obtains from the multi-version data structure the value written
to this location by the highest transaction that appears before tx in the preset
order, along with the associated version.

Validation: During an execution, transactions record a read-set and a write-set.


During a validation, all the memory locations in the read-set are read and the
returned versions are compared to the corresponding versions stored in the read-
set.

Collaborative schedule: Block-STM introduces a collaborative scheduler to


coordinate the validation and execution tasks among threads. Since the preset
order dictates that the transactions must be committed in order, successful
validation of a transaction execution does not guarantee that it can be committed.
This is because an abort and re-execution of an earlier transaction in the block
might invalidate the read-set and necessitate re-execution. Therefore, a static
mapping between transactions and executing threads does not work. Instead, the
collaborative scheduler prioritizes execution and validation tasks of lower
transactions. However, ordered sets and priority queues are notoriously
challenging to scale in multi-core environments. Block-STM sidesteps this problem
using a counting-based approach, which is made possible by preset ordering and
the compact indexation of transactions.

Dynamic dependency estimation: Block-STM leverages the preset order to


dramatically avoid aborts, which is the name of the performance game for STM
systems as aborts can cascade and lead to an excessive amount of wasted work.
When a validation fails, the write-set of the transaction’s last execution is used to
estimate dependencies by marking all its writes in the multi-version data structure
as an ESTIMATION. When another transaction reads an ESTIMATION value from
the multi-valued data structure it can then wait for the dependency to be resolved

https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba 4/8
2/13/23, 1:55 AM Block-STM: How We Execute Over 160k Transactions Per Second on the Aptos Blockchain | by Aptos | Aptos | Medium

— while without the estimation, it would have proceeded but be likely (if the
transaction that wrote ESTIMATION does indeed write to the same location in the
next re-execution) to later fail validation and be aborted. Compared to the textbook
approach of generating write estimates by pre-executing all transactions
embarrassingly in parallel from the pre-block state, our approach has two benefits:
(a) estimates are generated only when needed (not for every transaction), and (b)
the estimates are generally based on a state much fresher than at the beginning of
the block.

Evaluation
We Implemented Block-STM in safe Rust in the Aptos open source codebase, relying
on Rayon, Dashmap, and ArcSwap crates for concurrency. We evaluated the system
with non-trivial peer-to-peer Move transactions (8 reads and 5 writes). In the graph
below we compare Block-STM against a sequential execution of the block. Every block
contains 10k transactions and the number of accounts determines the level of conflicts
and contention. Under low contention Block STM achieves 16x speedup over
sequential execution with 32 threads, while under high contention Block-STM achieves
over 8x speedup. Importantly, Block-STM incurs a small overhead when the workload
is inherently sequential. Overall, Block-STM is able to dynamically and transparently
(without any hints from the user) extract the inherent parallelism from a workload.
Detailed comparisons to related work can be found in the paper.

Block STM performance with different contention levels

https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba 5/8
2/13/23, 1:55 AM Block-STM: How We Execute Over 160k Transactions Per Second on the Aptos Blockchain | by Aptos | Aptos | Medium

So How Do We Get This Performance?


The collaborative scheduler together with the multi-versioning technique allows Block-
STM to leverage the preset order of transactions in order to estimate dependencies and
dramatically reduce the amount of wasted work. The collaborative scheduler is the key
piece of the algorithm and contains most of the performance-critical logic. Among
other things, it ensures that:

Every aborted transaction is re-executed, but the same transaction is never


executed concurrently by more than one thread.

If a transaction is re-executed, then all higher transactions must be revalidated. As


a result, the same transaction execution might be validated concurrently by
different threads, but at most one can abort it.

A transaction that encounters a dependency is resumed after the dependency is


resolved.

All transactions are eventually committed.

The challenge is to ensure the above with as little synchronization overhead as


possible. A naive but costly way to keep track of execution and validation tasks is to
have two priority queues (or ordered sets to avoid duplicates). Once a dependency is
resolved or a validation is aborted, an execution task for the corresponding transaction
is added to the execution queue. Similarly, once a transaction is executed, validation
tasks are created for all higher transactions in the preset order and added to the
validation queue.

Efficient concurrent ordered set


Instead, Block-STM leverages the preset order of transactions and uses two atomic
counters.

These counters track a lower bound index for any transaction that needs to be
executed or validated. Combined with a way to know the status of each transaction,
these indices can be used to efficiently emulate the ordered set semantics from the
naive approach. Threads repeatedly try to grab a task by fetch-and-incrementing the
counter with a lower index, and read the status to check if the corresponding
transaction is ready for execution (or validation, depending on the counter). Fetch-and-
https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba 6/8
2/13/23, 1:55 AM Block-STM: How We Execute Over 160k Transactions Per Second on the Aptos Blockchain | by Aptos | Aptos | Medium

increment also naturally disperses threads to different indices, ensuring that the status
information is not heavily contended, which allows us to use mutexes and simplify the
implementation (a lock-free implementation is possible, but benchmarking does not
reveal significant improvements).

The possible statuses of a transaction are given in the diagram below. The parameter i
in the following diagram is the number of times the transaction was re-executed.

We also use locks to synchronize the list of dependencies, but, without care, some
subtle races are still possible that the collaborative scheduler has to avoid — the
glorious details are in the paper.

Lazy commit mechanism


Block-STM commits the entire block to eliminate the synchronization cost of tracking
when individual transactions can safely be committed. In a nutshell, the entire block
can be committed when all of the following conditions hold:

1. Both execution and validation indices reach the block size.

2. There are no ongoing validation and execution tasks.

3. The statuses of all transactions are EXECUTED.

As we prove in our #way-too-rigorous-for-a-systems-result proof, the first two conditions


in the Block-STM algorithm imply the third one. To atomically verify (1) and (2), we
introduced two additional counters. The first counter tracks the number of ongoing
tasks. It is too easy to increment or decrement this counter at a wrong place in the

https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba 7/8
2/13/23, 1:55 AM Block-STM: How We Execute Over 160k Transactions Per Second on the Aptos Blockchain | by Aptos | Aptos | Medium

code and never observe (2). To avoid such bugs we used the Resource Acquisition Is
Initialization (RAII) pattern to couple the counter with task guards, ensuring it is
increased and decreased before the task is dispatched and after it is completed,
respectively.

To atomically read this counter together with the counters that track the execution and
validation indices, we use the double collect technique. This requires introducing a
fourth atomic counter to track the number of times the execution and validation
counters were decreased. Then, we collect the values of all counters twice (order is
important!) and if in both cases conditions (1) and (2) are satisfied, then (as we prove),
at some time in between, conditions (1) and (2) were indeed simultaneously satisfied.
In this case, the entire block is safely committed, as no more validation and no
execution tasks are either needed or will be created.

If you are, like us, passionate about designing algorithms, putting them in practice, and
making a real impact on the future of Web3, please reach out — we are hiring at Aptos.
Open in app Get unlimited access

Search Medium

https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba 8/8
2/13/23, 1:58 AM UTXO vs Account/Balance Model. Two types of record-keeping models are… | by Flora Sun | Medium

Flora Sun Follow

Apr 15, 2018 · 5 min read · Listen

Save

UTXO vs Account/Balance Model

Two types of record-keeping models are popular in today’s blockchain networks. The
first method is called the UTXO (Unspent Transaction Output) Model and the second
one is the Account/Balance Model. The UTXO model is employed by Bitcoin, and
Ethereum uses the Account/Balance Model. In this article, we will lay out a basic
understanding of how these two models work, how they differ, and briefly touch on
pros and cons of the two.

https://medium.com/@sunflora98/utxo-vs-account-balance-model-5e6470f4e0cf 1/6
2/13/23, 1:58 AM UTXO vs Account/Balance Model. Two types of record-keeping models are… | by Flora Sun | Medium

In Bitcoin, each transaction spends output from prior transactions and generates new
outputs that can be spent by transactions in the future. All of the unspent transactions
are kept in each fully-synchronized node, and therefore this model is named “UTXO”.
A user’s wallet keeps track of a list of unspent transactions associated with all
addresses owned by the user, and the balance of the wallet is calculated as the sum of
those unspent transactions.

image source: https://bitcoin.org

Let’s take a look at a simplified example of how the UTXO model works in Bitcoin
transactions:

1. Alice gains 12.5 bitcoins through mining. Alice’s wallet is associated with one UTXO
record of 12.5 bitcoins.

https://medium.com/@sunflora98/utxo-vs-account-balance-model-5e6470f4e0cf 2/6
2/13/23, 1:58 AM UTXO vs Account/Balance Model. Two types of record-keeping models are… | by Flora Sun | Medium

2. Alice wants to give Bob 1 bitcoin. Alice’s wallet first unlocks her UTXO of 12.5
bitcoins and uses this whole 12.5 bitcoins as input to the transaction. This transaction
sends 1 bitcoin to Bob’s address and the reminder of 11.5 bitcoins is sent back to Alice
in the form of a new UTXO to a newly-created address (owned by Alice).

3. Say there was another UTXO of 2 bitcoins associated with Bob prior to step 2, Bob’s
wallet now shows that his balance is 3 bitcoins. Bob’s wallet now keeps track of two
UTXOs: one from before and another from the transaction in step 2. Each UTXO needs
to be unlocked if Bob wishes to spend them.

The Account/Balance Model, on the other hand, keeps track of the balance of each
account as a global state. The balance of an account is checked to make sure it is larger
than or equal to the spending transaction amount.

Here is a simplified example of how this model works in Ethereum:

1. Alice gains 5 ethers through mining. It is recorded in the system that Alice has 5
ethers.

2. Alice wants to give Bob 1 ether, so the system will first deduct 1 ether from Alice’s
account, so Alice now has 4 ethers.

3. The system then increases Bob’s account by 1 ether. The system knows that Bob has
2 ethers to begin with, therefore Bob’s balance is increased to 3 ethers.

https://medium.com/@sunflora98/utxo-vs-account-balance-model-5e6470f4e0cf 3/6
2/13/23, 1:58 AM UTXO vs Account/Balance Model. Two types of record-keeping models are… | by Flora Sun | Medium

One analogy for the transactions in the UTXO model is paper bills (banknotes). Each
account keeps track of how much money it has by adding up the amount of bills
(UTXOs) in the purse (associated with this address/wallet). When we want to spend
money, we use one or more bills (existing UTXOs), enough to cover the cost and maybe
receive some change back (new UTXO). Each bill can only be spent once since, once
spent, the UTXO is removed from the pool.

https://medium.com/@sunflora98/utxo-vs-account-balance-model-5e6470f4e0cf 4/6
2/13/23, 1:58 AM UTXO vs Account/Balance Model. Two types of record-keeping models are… | by Flora Sun | Medium

On the other hand, the record-keeping for Ethereum is just like that in a bank. An
analogy is using an ATM/debit card. The bank tracks how much money each debit card
has, and when we need to spend money, the bank checks its record to make sure we
have enough balance before approving the transaction.

Both models achieve the same goal of keeping track of account balances in a
consensus system.

The benefits of the UTXO Model are:

Scalability — Since it is possible to process multiple UTXOs at the same time, it


enables parallel transactions and encourages scalability innovation.

Privacy — Even Bitcoin is not a completely anonymous system, but UTXO provides
a higher level of privacy, as long as the users use new addresses for each
transaction. If there is a need for enhanced privacy, more complex schemes, such
as ring signatures, can be considered.

The benefits of the Account/Balance Model are:

https://medium.com/@sunflora98/utxo-vs-account-balance-model-5e6470f4e0cf 5/6
2/13/23, 1:58 AM UTXO vs Account/Balance Model. Two types of record-keeping models are… | by Flora Sun | Medium

Simplicity — Ethereum opted for a more intuitive model for the benefit of
developers of complex smart contracts, especially those that require state
information or involve multiple parties. An example is a smart contract that keeps
track of states to perform different tasks based on them. UTXO’s stateless model
would force transactions to include state information, and this unnecessarily
complicates the design of the contracts.

OpenEfficiency
in app — In addition to simplicity, the Account/Balance Model isGet unlimited access
more
efficient, as each transaction only needs to validate that the sending account has
Search Medium
enough balance to pay for the transaction.

One drawback for the Account/Balance Model is the exposure to double spending
attacks. An incrementing nonce can be implemented to counteract this type of attack.
In Ethereum, every account has a public viewable nonce and every time a transaction
is made, the nonce is increased by one. This can prevent the same transaction being
submitted more than once. (Note, this nonce is different from the Ethereum proof of
work nonce, which is a random value.)

Like most things in computer architecture, both models have trade-offs. Some
blockchains, notably Hyperledger, adopt UTXO because they can benefit from the
innovation derived from the Bitcoin blockchain. We will look into more technologies
that are built on top of these two record-keeping models.

Bitcoin Utxo

https://medium.com/@sunflora98/utxo-vs-account-balance-model-5e6470f4e0cf 6/6
2/13/23, 2:00 AM Verify Ethereum Account Balance with State Proof | by Leo Zhang | Medium

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

Leo Zhang Follow

Jun 19, 2022 · 7 min read · · Listen

Save

Verify Ethereum Account Balance with State


Proof
How to check the balance of your Ethereum account?

You could use etherscan.io, or any other web API.

But how to convince yourself the balance shown on the site is correct?

You could download the entire blockchain history data and then check the latest state
of your account. But that requires tons of data and can be time-consuming.

One great feature of Ethereum is that, a full node can provide proof for anyone,
especially light clients, to verify the balance of any account.

Full nodes are those who have stored the entire blockchain data.

Light clients are clients who don’t have access to the entire blockchain data, but rely on
full nodes to query that.

In order for full node to provide proof, Ethereum uses a data structure called Merkle
Patricia Trie to store the state of accounts and their storage.

We’ve previously introduced this data structure — Merkle Patricia Trie.

https://medium.com/@chiqing/verify-ethereum-account-balance-with-state-proof-83b51ceb15cf 1/10
2/13/23, 2:00 AM Verify Ethereum Account Balance with State Proof | by Leo Zhang | Medium

In this blog, I will:

Talk about how Merkle Patricia Trie is used to structure and store the account
state. And how Merkle proof is created to verify the state of any account.

Walk through an example that queries the balance of an account and the Merkle
Proof of it from a full node, and verify the Proof using a simple Merkle Patricia Trie
implementation that I made for demo purpose.

This blog is also part of the series that explain how Ethereum Storage works.

The full series of blog posts include:

Merkle Patricia Trie Explained (posted)

Verify Ethereum Account Balance with State Proof (this post)

EIP 1186 — the standard for getting account proof (posted)

Verify Ethereum Smart Contract State with Proof (posted)

StorageTrie — Verify your ERC token Balance with Storage Proof (future post)

If you are interested in more details about Ethereum storage and proof, please follow
and subscribe.

Let’s get started.

Ethereum World State


How is Ethereum World State look like? Are there a bunch of tables like in relation
database?

No.

Ethereum World State is essentially key-value pairs, with key being account address,
and value being AccountState. Account state includes 4 piece of data: Nonce , Balance ,

StorageHash , CodeHash .

https://medium.com/@chiqing/verify-ethereum-account-balance-with-state-proof-83b51ceb15cf 2/10
2/13/23, 2:00 AM Verify Ethereum Account Balance with State Proof | by Leo Zhang | Medium

WorldState = [(address, AccountState)]


AccountState = [Nonce, Balance, StorageHash, CodeHash]

Instead of using the naive map to store the key-value pairs of WorldState , Ethereum
uses Merkle Patricia Trie structure.

Why? Because Merkle Patricia Trie not only can be used as a map to store key-value
pairs, but also, more importantly, it can generate Merkle Proof to prove a certain key
value pair exists in the trie.

In other words, it can generate Merkle Proof to prove a certain account address has a
certain account state.

This allows a light client to be able to verify account state without the access to the
entire blockchain data.

In order to verify account state, what a light client needs are:

1. StateRoot, from the block header that they trust

2. Merkle Proof for the account, received from an untrusted full node

With the above data, a light client can verify the untrusted Merkle Proof against the
trusted StateRoot.

If the Merkle Proof is invalid, then the account state response should not be trusted.

If the Merkle Proof is valid, then they can trust the account state, which includes
Nonce , Balance , StorageHash and CodeHash .

Account State
There are two types of accounts: smart contract account and user account (or external
owned account, which means account has no contract).

Both of them have Nonce and Balance . But only smart contract account has code and
extra storage for storing data.

https://medium.com/@chiqing/verify-ethereum-account-balance-with-state-proof-83b51ceb15cf 3/10
2/13/23, 2:00 AM Verify Ethereum Account Balance with State Proof | by Leo Zhang | Medium

The CodeHash is the hash for the smart contract code. For user account, it’s always a
constant string 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 ,

which is keccak256 hash of an empty string.

The StorageHash is the Merkle Root Hash of the storage state. Since smart contract’s
data is also key-value pairs, it can also use Merkle Patricia Trie to store the data. We
will explain how smart contract stores data in future posts.

For now, we just need to know the StorageHash is Merkle Root Hash of the smart
contract’s storage data.

For user account, StorageHash is always


0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421 , which is
keccak256 hash of an empty trie.

Example
Let’s go through a simple code example to explain how Merkle Patricia Trie stores the
World State, and how the Merkle Proof looks like.

Let’s say the world state contains the following 2 user accounts - account1 and
account2 :

24264ae01b1abbc9a91e18926818ad5cbf39017b, {Nonce: 1, Balance: 1ETH}


3a844bb6252b584f76febb40c941ec898df9bc23, {Nonce: 0, Balance: 2ETH}

Then the key value pair for account1 to be stored in the merkle trie for the world state
is (account1Hash, accountState1) , calculated as below:

// 1ee3017a85544556ea847c203623a9c84efdb77fa4951a5b01296d9aacefc5f7
account1Hash :=
crypto.Keccak256(common.HexToAddress("0x24264ae01b1abbc9a91e18926818ad
5cbf39017b").Bytes())
accountState1, err := rlp.EncodeToBytes([]interface{}{
uint64(1), // Nonce
(new(big.Int)).SetInt64(1e18), // 1 ETH
https://medium.com/@chiqing/verify-ethereum-account-balance-with-state-proof-83b51ceb15cf 4/10
2/13/23, 2:00 AM Verify Ethereum Account Balance with State Proof | by Leo Zhang | Medium

EmptyNodeHash, // Empty StorageHash


crypto.Keccak256([]byte("")), // Empty CodeHash
})
require.NoError(t, err)

The key is the keccak256 hash of account address, the value is the RLP encoding of the
account state, which includes Nonce , Balance , CodeHash and StorageHash .

Likewise, the key value pair for account2 is (account2Hash, accountState2) :

// 1eeced8d7a011c27d9aed60517c8e596509852f1d208a8a6d6f16d17ea5da204
account2Hash :=
crypto.Keccak256(common.HexToAddress("0x3a844bb6252b584f76febb40c941ec
898df9bc23").Bytes())
accountState2, err := rlp.EncodeToBytes([]interface{}{
uint64(3), // Nonce
(new(big.Int)).SetInt64(2e18), // 2 ETH
EmptyNodeHash, // Empty StorageHash
crypto.Keccak256([]byte("")), // Empty CodeHash
})

Note, the two addresses are selected carefully, so that the hash of them have common
prefix "1ee" , which will create an extension node in the trie.

Next, let’s create a world state trie with the above 2 key-value pairs, and compute the
root hash of the trie as the StateRoot hash:

// create a world state with the two accounts


worldStateTrie := NewTrie()
worldStateTrie.Put(account1Hash, accountState1)
worldStateTrie.Put(account2Hash, accountState2)
// compute the state root hash
stateRoot := worldStateTrie.Hash()

At this point, if we visualize the merkle trie for the world state, and what is stored in
key-value database, it will look like this:

https://medium.com/@chiqing/verify-ethereum-account-balance-with-state-proof-83b51ceb15cf 5/10
2/13/23, 2:00 AM Verify Ethereum Account Balance with State Proof | by Leo Zhang | Medium

Merkle Trie backed World State

OK, now as a full node, we have the world state stored in the database.

Next, as a full node, how to prove to a light client that, for instance, account1

( 0x24264ae01b1abbc9a91e18926818ad5cbf39017b ) has 1ETH ?

We can call the Prove method of the Merkle Trie to generate the proof for account1 :

accountState1Proof, ok := worldStateTrie.Prove(account1Hash)

The Prove method creates a Merkle Proof, which is essentially all the trie nodes along
the path from the root node to the LeafNode that stores the account state of account1 .

They are the ExtensionNode , the BranchNode and the LeafNode1 .

[
RLP(133, hash3),
RLP(null, null, null, hash1, null, null, null, null, null, null,
null, hash2, null, null, null, null),

https://medium.com/@chiqing/verify-ethereum-account-balance-with-state-proof-83b51ceb15cf 6/10
2/13/23, 2:00 AM Verify Ethereum Account Balance with State Proof | by Leo Zhang | Medium

RLP(017a85544556ea847c203623a9c84efdb77fa4951a5b01296d9aacefc5f7,
RLP(1, 1ETH, emptyStorageHash, emptyCodeHash)),
]

Which is computed to be a list of hex string:

[
"e48211eea0a97a6826ce3f3f0baa07899c0502c387bf24eae2b6f6a9561169a59e0c1
0f9d2",

"f851808080a007c9a6fda8ffe9dbc9fb3ecc78460caef3c4659cfc8e4e865a6121d91
375557d8080808080808080a03ce63212850c9a256f4cbb1a7ba7cb576549222339f2b
4124621ea4a991fe6eb80808080",

"f8709f20017a85544556ea847c203623a9c84efdb77fa4951a5b01296d9aacefc5f7b
84ef84c01880de0b6b3a7640000a056e81f171bcc55a6ff8345e692c0f86e5b48e01b9
96cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca822
73b7bfad8045d85a470",
]

Note, the full node doesn’t need to send the hashes of the trie nodes to the client, but
only the RLP encoding of the trie nodes. That’s because the light client can compute
the hash themselves.

To verify this merkle proof, the light client will create another merkle trie with the
above nodes:

// full node serialize the account state proof


serialized := accountState1Proof.Serialize()
// create a proof trie, and add each node from the serialized proof
proofTrie := NewProofDB()
for _, node := range serialized {
// store each node under its hash
proofTrie.Put(crypto.Keccak256(node), node)
}

Let’s visualize the above steps again:

https://medium.com/@chiqing/verify-ethereum-account-balance-with-state-proof-83b51ceb15cf 7/10
2/13/23, 2:00 AM Verify Ethereum Account Balance with State Proof | by Leo Zhang | Medium

Light Client builds a proof trie with the proof generated by Full node

Note, hash1 , hash3 , hash4 are computed by the light client.

https://medium.com/@chiqing/verify-ethereum-account-balance-with-state-proof-83b51ceb15cf 8/10
2/13/23, 2:00 AM Verify Ethereum Account Balance with State Proof | by Leo Zhang | Medium

And then, the light client will start with the state root hash it gets from a trusted
source, which is hash4 , and use account1Hash as the path to walk through the trie.

If the light client is able to arrive at a LeafNode , which is hash1 . And then it can decode
the value of the LeafNode , and get the balance as 1ETH , and be convinced that this
balance is valid.

However, if the light client is not able to arrive at a LeafNode , then it means the full
node is sending an invalid proof.

Malicious full node


What if a malicious full node tries to use 1000ETH as the account balance in the merkle
proof? How can a light client find out the merkle Proof is invalid, and reject the invalid
account balance?

Since all the hashes of the trie nodes are computed by the light client themselves, the
light client will compute a different hash for the LeafNode . And since hash1 is
supposed to be included in the BranchNode , which is also included in the
ExtensionNode , the hash for the ExtensionNode will be different from the original
hash4 . This means, when walking through the trie with the StateRoot hash4 , the light
client won’t be able to find the ExtensionNode under the key hash4 . So the light client
can conclude that the merkle proof is invalid.

Summary
In this blog post, we explained how Ethereuem structures the world state. And walked
through an example to show how a full node can prove to a light client, who doesn’t
have access to the entire blockchain data, the state of any account, so that the light
client can verify the proof themselves without needing to trust.

The source code of the example is available here.

In the next post, I will introduce EIP1186 — the standard for querying proof from a full
node to verify account state for any account.

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

https://medium.com/@chiqing/verify-ethereum-account-balance-with-state-proof-83b51ceb15cf 9/10
2/13/23, 2:00 AM Verify Ethereum Account Balance with State Proof | by Leo Zhang | Medium

Merkle Patricia Trie Explained

Verify Ethereum Account Balance with State Proof

EIP 1186 — the standard for getting account proof

Verify Ethereum Smart Contract State with Proof

Verify USDC Balance and NFT Meta Data with Proof

Blockchain Cryptocurrency Ethereum Crypto Web 3

Open in app Sign up Sign In

Search Medium

About Help Terms Privacy

Get the Medium app

https://medium.com/@chiqing/verify-ethereum-account-balance-with-state-proof-83b51ceb15cf 10/10
2/13/23, 2:02 AM A note on numbers in Ethereum and Javascript | by Alex Miller | HackerNoon.com | Medium

Published in HackerNoon.com

Alex Miller Follow

Apr 26, 2017 · 4 min read · Listen

Save

A note on numbers in Ethereum and Javascript


Being at ConsenSys, I get to work with some of the best developers in the space. I
recently published this article as a “Getting Started” guide for new developers who
have stumbled into this magical Ethereum ecosystem and don’t want to leave. It was
not long until Joseph Chow raised issue with my neglecting to mention BigNumber s and
not longer after that until Jim Berry dropped a wonderful description of the danger at
hand. So props to both of them and also thanks to Aakil Fernandes for explaining how
BigNumber works to me.

It turns out I’ve been doing things the wrong way. I updated my previous article and
felt compelled to write this one so that I could A) unburden my soul and B) show how

https://medium.com/hackernoon/a-note-on-numbers-in-ethereum-and-javascript-3e6ac3b2fad9 1/7
2/13/23, 2:02 AM A note on numbers in Ethereum and Javascript | by Alex Miller | HackerNoon.com | Medium

you may currently be mathing wrong between Javascript and Ethereum.

This is important because if you math wrong in Ethereum, you can lose money.

Numbers in Ethereum
Much to the pain and suffering of many developers, Ethereum does not support
floating point numbers at all. We are forced like barbarians to settle for int s and
uint s (I suggest you use the latter unless you have a very good reason to use the
former) instead. There are probably valid technical reasons (I don’t know what they
are) for this, but it’s fine because we can represent everything as integers and just keep
track of decimals (recall that 1 ether = 10**18 wei).

Numbers in Javascript
Javascript is weird. Because it’s a dynamically typed language, you can run into all sorts
of interesting interpretation scenarios. The relevant problem here is that default
division behavior in JS is floating point division (more specifically, double floating point
division). This is incompatible with Ethereum, which (obviously) uses integer division.

How to lose money


Have you spotted the problem yet? Oh yes, Javascript’s [double] floating point numbers
only go up to 16 decimals, but 1 ether = 10**18 wei. And all ether values in transactions
must be denominated in wei.

To see the problem in action, consider this:

var my_money = 10*Math.pow(10, 18);


my_money/3
> 3333333333333333500

Uh… whoops. You just gave me 167 wei.

You may be saying “I don’t care about 167 wei.” And that’s a perfectly reasonable
reaction. I don’t care about 167 wei either. But what happens when every one of the 1B
daily state pushes that your swarm of IoT devices makes to Raiden is off by 167 wei?
Your problems start adding up fast.
https://medium.com/hackernoon/a-note-on-numbers-in-ethereum-and-javascript-3e6ac3b2fad9 2/7
2/13/23, 2:02 AM A note on numbers in Ethereum and Javascript | by Alex Miller | HackerNoon.com | Medium

BigNumber — A [really annoying] solution


Contrary to popular belief, the built in toPrecision() function does absolutely nothing
for you. So we need to parse our number using some abstracted layer (I recommend
bignumber.js, mostly because that’s what web3.js returns you anyway) and then
operate on that.

So now our math looks like this:

var my_money = 10*Math.pow(10, 18);


var my_safe_money = new BigNumber(my_money);
// Still wrong
my_safe_money/3
> 3333333333333333500
// This is how you do it
var less_money = my_safe_money.div(3);

So what do you do with this weird BigNumber thing?

{
[String: '3333333333333333333.333333333333333333']
s: 1,
e: 18,
c: [ 33333, 33333333333333, 33333333333333, 33330000000000 ]
}

Well, you have to pass it around and keep operating on it with div() or times() or
whatever. Look here for the full list of functions. Unfortunately, if you ever pull out the
value:

var free_at_last = less_money.toNumber();

You will be sad about the result:

https://medium.com/hackernoon/a-note-on-numbers-in-ethereum-and-javascript-3e6ac3b2fad9 3/7
2/13/23, 2:02 AM A note on numbers in Ethereum and Javascript | by Alex Miller | HackerNoon.com | Medium

free_at_last
> 3333333333333333500

So yeah… you have to keep doing BigNumber operations. If you want a glimpse of what
the number is, you can do this:

less_money.toString()
> '3333333333333333333.333333333333333333'

Also remember that if you’re forming transactions yourself, you have to provide
Ethereum with hex numbers, so you would need to do the following before putting it
in a transaction:

less_money.floor().toString(16)
> '2e426101834d5555'

Of course if you’re abstracting that logic into web3, that will convert your numbers for
you.

Always Be Careful
It’s hard out there for an Ethereum application developer (although not nearly as hard
as it is for a Bitcoin application developer — I think those still exist?). We need to watch
out for each other and be careful with what we’re doing. Always remember that there
is (probably) money being moved by your application and take the necessary
precautions.

And, of course, if you find out about a pro tip or catch some dangerous behavior,
report it!

If you like my articles, follow me on twitter or check out my company, ConsenSys,


because we do awesome stuff.

https://medium.com/hackernoon/a-note-on-numbers-in-ethereum-and-javascript-3e6ac3b2fad9 4/7
2/13/23, 2:02 AM A note on numbers in Ethereum and Javascript | by Alex Miller | HackerNoon.com | Medium

And, as always, there is an open invitation to join the Ethereum community and help
us conquer the world.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are
now accepting submissions and happy to discuss advertising & sponsorship opportunities.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech
stories. Until next time, don’t take the realities of the world for granted!

https://medium.com/hackernoon/a-note-on-numbers-in-ethereum-and-javascript-3e6ac3b2fad9 5/7
2/13/23, 2:02 AM A note on numbers in Ethereum and Javascript | by Alex Miller | HackerNoon.com | Medium

Open in app Get unlimited access

Search Medium
Hackernoon Newsletter curates
great stories by real tech
professionals
Get solid gold sent to your inbox. Every week!

Email

First Name Last Name

Sign Up

If you are ok with us sending you updates via email, please


tick the box. Unsubscribe whenever you want. 

Terms of Service

Powered by Upscribe
I agree to leave medium.com and submit this information,
which will be collected and used according to Upscribe's

Ethereum Blockchain

201 3

https://medium.com/hackernoon/a-note-on-numbers-in-ethereum-and-javascript-3e6ac3b2fad9 6/7
2/13/23, 2:02 AM A note on numbers in Ethereum and Javascript | by Alex Miller | HackerNoon.com | Medium

Sign up for Get Better Tech Emails via HackerNoon.com


By HackerNoon.com

how hackers start their afternoons. the real shit is on hackernoon.com. Take a look.

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

Get this newsletter

https://medium.com/hackernoon/a-note-on-numbers-in-ethereum-and-javascript-3e6ac3b2fad9 7/7
2/13/23, 2:04 AM Big Numbers in JavaScript with math.js | by Chris Webb | Explorations in JavaScript | Medium

Published in Explorations in JavaScript

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

Chris Webb Follow

Aug 29, 2021 · 5 min read · · Listen

Save

Big Numbers in JavaScript with math.js

Image: Pixabay

JavaScript’s 64 bit Number type is perfectly adequate for most purposes but if you need
very large numbers or more decimal places than it can represent then the math.js
library’s BigNumber type can come to your rescue. In this article I’ll show the BigNumber

type in action.

https://medium.com/explorations-in-javascript/big-numbers-in-javascript-with-math-js-e2139b95811b 1/10
2/13/23, 2:04 AM Big Numbers in JavaScript with math.js | by Chris Webb | Explorations in JavaScript | Medium

This project consists of an HTML file, a JavaScript file and a CSS file which are in the
itHub repository. I have also included the minimized version of the math.js library,
math.min.js.

The Limitations of the JavaScript Number Type


The JavaScript Number type is fine for most purposes both in terms of highest and
lowest numbers, and maximum number of decimal places. However, it is restricted by
how much you can squeeze into 64 bits so before looking at the main topic of this
article, the math.js BigNumber , I’ll briefly look at just what the JavaScript Number type’s
limits are.

JavaScript provides us with a couple of constants, Number.MAX_SAFE_INTEGER and


Number.MIN_SAFE_INTEGER , as well as a method called Number.isSafeInteger which allows
us to check if we think we might be stumbling into dangerous territory with very large
numbers.

The first part of the JavaScript code that goes with this article shows these constants
and method in use.

https://medium.com/explorations-in-javascript/big-numbers-in-javascript-with-math-js-e2139b95811b 2/10
2/13/23, 2:04 AM Big Numbers in JavaScript with math.js | by Chris Webb | Explorations in JavaScript | Medium

1 "use strict"
2
3
4 window.onload = function()
5 {
6 safeIntegers();
7
8 // BigInts();
9
10 // BigNumbers();
11 }
12
13
14 function output(text)
15 {
16 const p = document.createElement("p");
17 p.innerHTML = text;
18 document.body.appendChild(p);
19 }
20
21
22 function safeIntegers()
23 {
24 output("Safe Integers<br>-------------<br><br>");
25
26 output(`Number.MAX_SAFE_INTEGER = ${Number.MAX_SAFE_INTEGER}`);
27 output(`Number.MIN_SAFE_INTEGER = ${Number.MIN_SAFE_INTEGER}`);
28
29 const safePos = Math.pow(2, 53) - 1;
30 const unsafePos = Math.pow(2, 53);
31 const safeNeg = -(Math.pow(2, 53) - 1);
32 const unsafeNeg = -(Math.pow(2, 53));
33
34 output("<br>");
35
36 output(`safePos = ${safePos}`);
37 output(`Number.isSafeInteger(safePos) = ${Number.isSafeInteger(safePos)}`);
38
39 output("<br>");
40
41 output(`unsafePos = ${unsafePos}`);
42 output(`Number.isSafeInteger(unsafePos) = ${Number.isSafeInteger(unsafePos)}`);
43
44 output("<br>");
45
https://medium.com/explorations-in-javascript/big-numbers-in-javascript-with-math-js-e2139b95811b 3/10
2/13/23, 2:04 AM Big Numbers in JavaScript with math.js | by Chris Webb | Explorations in JavaScript | Medium
45
In46 onloadoutput(`safeNeg
there are three function calls, the second and third being commented out
= ${safeNeg}`);
for
47 the time being. After onload is a short= function
output(`Number.isSafeInteger(safeNeg) which writes text directly to the
${Number.isSafeInteger(safeNeg)}`);
48
web page.
49 output("<br>");
50
In safeIntegers we simply output Number.MAX_SAFE_INTEGER and
51 output(`unsafeNeg = ${unsafeNeg}`);
Number.MIN_SAFE_INTEGER
52 before creating a =few
output(`Number.isSafeInteger(unsafeNeg) consts to test for safety. Each
${Number.isSafeInteger(unsafeNeg)}`); of these is
then
53 output,
} followed by the result of calling Number.isSafeInteger with it. If you open
mathjsbignumber.htm in your
mathjsbignumber1.js hosted with browser you’ll see this.
❤ by GitHub view raw

The JavaScript BigInt Type


JavaScript has its own partial solution to the problem of Number limits, the BigInt type.
As its name implies it is an integer, not real or floating point type, and is not
compatible with Math methods. It is therefore of limited usefulness but in the next
method I’ll briefly show it in use.

https://medium.com/explorations-in-javascript/big-numbers-in-javascript-with-math-js-e2139b95811b 4/10
2/13/23, 2:04 AM Big Numbers in JavaScript with math.js | by Chris Webb | Explorations in JavaScript | Medium

1 function BigInts()
2 {
3 output("BigInt<br>------<br><br>");
4
5 const big1 = 9007199254740992n; // 9,007,199,254,740,992
6 const big2 = 9007199254740993n; // 9,007,199,254,740,993
7
8 output(`typeof(big1) = ${typeof(big1)}`);
9
10 output(`<br>big1 = ${big1}`);
11 output(`big2 = ${big2}`);
12
13 const r = 3n / 2n;
14 output(`<br>3n / 2n = ${3n / 2n}`);
15
16 try
17 {
18 output("<br>Math.min(3n, 5n, 7n, 9n)");
19 output(Math.min(3n, 5n, 7n, 9n));
20 }
21 catch (e)
22 {
23 output(e);
24 }
25
26 try
27 {
28 output("<br>Math.sign(64n)");
29 output(Math.sign(64n));
30 }
31 catch (e)
32 {
33 output(e);
34 }
35 }

mathjsbignumber.js hosted with ❤ by GitHub view raw

https://medium.com/explorations-in-javascript/big-numbers-in-javascript-with-math-js-e2139b95811b 5/10
2/13/23, 2:04 AM Big Numbers in JavaScript with math.js | by Chris Webb | Explorations in JavaScript | Medium

Firstly we create a couple of BigInts — this is done here by suffixing the number with
n but you can also call the BigInt constructor, for example:

const bigNo = BigInt(9007199254740992);

Calling typeof on a BigInt returns bigint , and then the two consts are printed. Next
we divide 3n by 2n just to demonstrate that this is an integer type; the result will be 1
with the decimal part being lost. Finally, just as a reminder that the Math methods
don’t work on BigInts I have tried it out with Math.min and Math.sign . These will both
throw errors so these bits of code are in try/catch blocks.

If you scroll up to the onload function, comment out safeIntegers(); , uncomment


BigInts(); and refresh the web page you’ll see this output.

It’s interesting to see the error messages: the Math methods are attempting to convert
the arguments to Number types but failing. This is just as well as they would lose
precision if they were to do so.

I have to say I am not impressed with the BigInt type at all. It’s a pretty lame effort
with too many limitations to be taken seriously.

https://medium.com/explorations-in-javascript/big-numbers-in-javascript-with-math-js-e2139b95811b 6/10
2/13/23, 2:04 AM Big Numbers in JavaScript with math.js | by Chris Webb | Explorations in JavaScript | Medium

The Main Feature: the math.js BigNumber Type


The math.js library’s BigNumber type can represent real or floating point numbers, and
can be used with the library’s methods. In the final function I will show it in use.

1 function BigNumbers()
2 {
3 output("MathJS Big Numbers<br>==================<br><br>");
4
5 output(`Size of observable universe in kilometres:
6 ${math.format(math.bignumber(880000000000000000000000000),
7 {notation: 'fixed'})}
8 (880,000,000,000,000,000,000,000,000)`);
9
10 output(`<br>math.add(math.bignumber(10), math.bignumber(13)) = ${math.add(math.bignumber(10),
11 output(`math.abs(math.bignumber(-128)) = ${math.abs(math.bignumber(-128))}`);
12 output(`math.floor(math.bignumber(12.5589)) = ${math.floor(math.bignumber(12.5589))}`);
13 output(`math.ceil(math.bignumber(12.5589)) = ${math.ceil(math.bignumber(12.5589))}`);
14 output(`math.mod(math.bignumber(22), math.bignumber(10)) = ${math.mod(math.bignumber(22), math
15
16 output(`<br>math.sqrt(math.bignumber(2)) [default precision 64] = ${math.sqrt(math.bignumber(2
17 math.config({ precision: 32 });
18 output(`math.sqrt(math.bignumber(2)) [precision 32] = ${math.sqrt(math.bignumber(2))}`);
19 math.config({ precision: 128 });
20 output(`math.sqrt(math.bignumber(2)) [precision 128] = ${math.sqrt(math.bignumber(2))}`);
21
22 const PlanckLength = math.bignumber(0.000000000000000000000000000000000016);
23 output("<br>Planck Length<br>-------------");
24 output(PlanckLength);
25 output(math.format(PlanckLength, {notation: 'fixed'}));
26
27 const atomsInUniverse = math.bignumber(1e+80);
28 output("<br>Atoms in universe<br>-----------------");
29 output(atomsInUniverse);
30 output(math.format(atomsInUniverse, {notation: 'fixed'}));
31 }

mathjsbignumber.js hosted with ❤ by GitHub view raw

https://medium.com/explorations-in-javascript/big-numbers-in-javascript-with-math-js-e2139b95811b 7/10
2/13/23, 2:04 AM Big Numbers in JavaScript with math.js | by Chris Webb | Explorations in JavaScript | Medium

Firstly I have created a BigNumber with the size of observable universe in kilometres,
and output the value with notation set to fixed; this will format the output in full rather
than 8.8e+26 . (Obviously light years would be a more sensible unit but this is just for
demonstration purposes.)

Next we carry out a few operations on BigNumbers using math.js methods, something
which you cannot do with JavaScript BigInts and Math methods, as we have just seen.

The next few lines of code demonstrate how to change the precision of BigNumbers , in
this case with the square root of 2 which is an irrational number. The default is 64
significant digits but here I also use 32 and 128. Using BigNumbers is significantly
slower than the Number type, becoming slower the more digits there are, so it’s
important to use only the precision you need. Note that even when set to 32 we still
have about twice as many accurate decimal places than the Number type.

Finally I have created a couple of constants for actual very small and very large
numbers. The first is the Planck length (in metres) which I won’t attempt to describe
here but you might like to read the Wikipedia article. Suffice to say it’s very very very
small!

The second number is the number of atoms in the Universe. The 1e+80 notation
means 10^80 and is an approximation. Obviously!

Comment out BigInts(); in onload , uncomment BigNumbers(); and reload the page.
This is the result, somewhat cropped. The very long numbers go a lot further over to
the right.

https://medium.com/explorations-in-javascript/big-numbers-in-javascript-with-math-js-e2139b95811b 8/10
2/13/23, 2:04 AM Big Numbers in JavaScript with math.js | by Chris Webb | Explorations in JavaScript | Medium

This article and source code has only provided an introduction to the topic with a few
examples, but should get you up and running. This is a summary of using the math.js
library’s BigNumber type.

Create a BigNumber with math.bignumber(880000000000000000000000000) or


math.bignumber(1e+80)

Set the number of significant digits to the lowest you need for optimum efficiency

Use any of the math.js library’s methods with BigNumbers : they will recognize when
you pass BigNumber arguments and will return a BigNumber

https://medium.com/explorations-in-javascript/big-numbers-in-javascript-with-math-js-e2139b95811b 9/10
2/13/23, 2:04 AM Big Numbers in JavaScript with math.js | by Chris Webb | Explorations in JavaScript | Medium

Use math.format . . . {notation: ‘fixed’} if you want to see all the digits rather
than something like 8.8e+26

This article was previously published on my site CodeDrome

Java Script Webdev Web Development Mathematics

Open in app Sign up Sign In

Search Medium

About Help Terms Privacy

Get the Medium app

https://medium.com/explorations-in-javascript/big-numbers-in-javascript-with-math-js-e2139b95811b 10/10
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium

Published in Alchemy

Elan Halpern Follow

Apr 6, 2021 · 6 min read · Listen

Save

💻 Interacting with a Smart Contract


How to interact with a deployed Ethereum smart contract by sending a
transaction, for beginners. Part 2 of a series.

Before starting this tutorial on interacting with a smart contract, you should have
completed Part 1: Creating and Deploying a Smart Contract. In Part 3: Submitting Your

https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 1/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium
Smart Contract to Etherscan, we’ll go over submitting our contract to Etherscan so
anyone can understand how to interact with it!

Now that you’ve successfully deployed a smart contract to the Ropsten network, let’s
test out our web3 skills and interact with it!

UPDATE: We now have a video tutorial covering this article by our rockstar developer
ALBERT!

Read and Update a Smart Contract on Ethereum - Hello World Pt 2

If you have questions at any point feel free to reach out in the Alchemy Discord!

Still haven’t written and deployed your own smart contract? Check out this tutorial. Don’t
have an Alchemy account yet? Sign up for free.

Step 1: Install web3 library‌


Web3.js is a library used to make requests to the Ethereum chain much easier. There
are a handful of web3 providers you can choose from, however in this tutorial we’ll be
using Alchemy Web3, which is an enhanced web3 library that offers automatic retries
and robust WebSocket support.‌

In your project home directory run:


https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 2/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium

npm install @alch/alchemy-web3

Step 2: Create a contract-interact.js file‌


Inside the scripts/ folder for your Hello World project, create a file named contract-

interact.js and add the following lines of code:

require('dotenv').config();
const API_URL = process.env.API_URL;
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3 = createAlchemyWeb3(API_URL);

Step 3: Grab your contract ABI‌


Our contract ABI (Application Binary Interface) is the interface to interact with our
smart contract. You can learn more about Contract ABIs here. Hardhat automatically
generates an ABI for us when we deploy our smart contract, and saves it in the
HelloWorld.json file. In order to use this we’ll need to parse out the contents by adding
the following lines of code to our contract-interact.js file:

require('dotenv').config();
const API_URL = process.env.API_URL;
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3 = createAlchemyWeb3(API_URL);
const contract =
require("../artifacts/contracts/HelloWorld.sol/HelloWorld.json");

If you want to see the ABI you can print it to your console by adding this line to the
bottom of your contract-interact.js file:

console.log(JSON.stringify(contract.abi));

To run contract-interact.js and see your ABI printed to the console navigate to your
terminal and run:
https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 3/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium

node scripts/contract-interact.js

Step 4: Create an instance of your contract


In order to interact with our contract we need to create an instance of it in our code. To
do so, we’ll need our contract address which we can get from the deployment or from
Etherscan by looking up the address you used to deploy the contract. In the above
example our contract address is 0x70c86b8d660eBd0adef24E9ACcb389BFb6611B2b .

‌Next we will use the web3 contract method to create our contract using the ABI and
address:

const contractAddress = "0x70c86b8d660eBd0adef24E9ACcb389BFb6611B2b";


const helloWorldContract = new web3.eth.Contract(contract.abi,
contractAddress);

Step 5: Read the init message


Remember when we deployed our contract with the initMessage = "Hello world!" ? We

are now going to read that message stored in our smart contract and print it to the
console.

In JavaScript we use asynchronous functions to interact with networks. Check out this
article to learn more about this.‌

Use the code below to call the message function in our smart contract and read the init
message:

async function main() {


const message = await helloWorldContract.methods.message().call();
console.log("The message is: " + message);
}
main();

https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 4/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium
After running the file using node scripts/contract-interact.js in the terminal we
should see this response:

The message is: Hello world!

Congrats! You’ve just successfully read smart contract data from the Ethereum
blockchain, way to go! 🎉

Step 6: Update the message‌


Now instead of just reading the message, we’ll update the messaged saved in our smart
contract using the update function. ‌

In order to do so we’ll need to create a transaction, sign it, and send it inside another
async function that we’ll call updateMessage(newMessage) . This can be pretty confusing
when you first get started so we'll split it up into multiple steps.

Step 7: Update the .env file‌


Currently, our .env file contains our private key and our Alchemy API key. In this step,
we’ll add our public Ethereum account address which we’ll use to get the account
nonce (will explain what this means later).

Your public key is the hex address at the top of your Metamask wallet, simply click on
it to copy it:

https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 5/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium

https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 6/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium
Metamask public key

Your .env should now look like this:

API_URL = "https://eth-ropsten.alchemyapi.io/v2/your-api-key"
PRIVATE_KEY = "your-metamask-private-key"
PUBLIC_KEY = "your-metamask-public-key"

Step 8: Create the transaction‌


Define updateMessage(newMessage) and create our transaction.

1. First grab your PUBLIC_KEY and PRIVATE_KEY from the .env file.

2. Next, we’ll need to grab the account nonce . The nonce specification is used to keep
track of the number of transactions sent from your address. We need this for
security purposes and to prevent replay attacks. To get the number of transactions
sent from your address we use getTransactionCount.

3. Next, we’ll use eth_estimateGas to figure out the right amount of gas to include in
order to complete our transaction. This avoids the risk of a failed transaction due to
insufficient gas.

4. Finally we’ll create our transaction with the following info:‌

'from': PUBLIC_KEY : The origin of our transaction is our public address

'to': contractAddress : The contract we wish to interact with and send the
transaction

'nonce': nonce : The account nonce with the number of transactions send from
our address

'gas': estimatedGas : The estimated gas needed to complete the transaction

'data': helloWorldContract.methods.update("<new message>").encodeABI() : The


computation we wish to perform in this transaction (updating the contract
message)‌

https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 7/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium
Your contract-interact.js file should look like this now:

1 require('dotenv').config();
2 const API_URL = process.env.API_URL;
3 const PUBLIC_KEY = process.env.PUBLIC_KEY;
4 const PRIVATE_KEY = process.env.PRIVATE_KEY;
5
6 const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
7 const web3 = createAlchemyWeb3(API_URL);
8
9 const contract = require("../artifacts/contracts/HelloWorld.sol/HelloWorld.json");
10 const contractAddress = "0x0d6261a5D3102b565B75Fc680B64093820a17612";
11 const helloWorldContract = new web3.eth.Contract(contract.abi, contractAddress);
12
13 async function updateMessage(newMessage) {
14 const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); // get latest nonce
15 const gasEstimate = await helloWorldContract.methods.update(newMessage).estimateGas(); // esti
16
17 // Create the transaction
18 const tx = {
19 'from': PUBLIC_KEY,
20 'to': contractAddress,
21 'nonce': nonce,
22 'gas': gasEstimate,
23 'data': helloWorldContract.methods.update(newMessage).encodeABI()
24 };
25 }
26
27 async function main() {
28 const message = await helloWorldContract.methods.message().call();
29 console.log("The message is: " + message);
30 }
31
32 main();

contract-interact.js hosted with ❤ by GitHub view raw

contract-interact.js

https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 8/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium
Step 9: Sign the transaction
Now that we’ve created our transaction, we need to sign it in order to send it off. Here
is where we’ll use our private key.

web3.eth.sendSignedTransaction will give us the transaction hash, which we can use to


make sure our transaction was mined and didn't get dropped by the network.

1 require('dotenv').config();
2 const API_URL = process.env.API_URL;
3 const PUBLIC_KEY = process.env.PUBLIC_KEY;
4 const PRIVATE_KEY = process.env.PRIVATE_KEY;
5
6 const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
7 const web3 = createAlchemyWeb3(API_URL);
8
9 const contract = require("../artifacts/contracts/HelloWorld.sol/HelloWorld.json");
10 const contractAddress = "0x0d6261a5D3102b565B75Fc680B64093820a17612";
11 const helloWorldContract = new web3.eth.Contract(contract.abi, contractAddress);
12
13 async function updateMessage(newMessage) {
14 const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); // get latest nonce
15 const gasEstimate = await helloWorldContract.methods.update(newMessage).estimateGas(); // esti
16
17 // Create the transaction
18 const tx = {
19 'from': PUBLIC_KEY,
20 'to': contractAddress,
21 'nonce': nonce,
22 'gas': gasEstimate,
23 'data': helloWorldContract.methods.update(newMessage).encodeABI()
24 };
25
26 // Sign the transaction
27 const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY);
28 signPromise.then((signedTx) => {
29 web3.eth.sendSignedTransaction(signedTx.rawTransaction, function(err, hash) {
30 if (!err) {
31 console.log("The hash of your transaction is: ", hash, "\n Check Alchemy's Mempool to vi
32 } else {
33 console.log("Something went wrong when submitting your transaction:", err)
34 }
35 });
36 }).catch((err) => {
https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 9/13
2/13/23, 2:07 AM
}) (( ) { 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium

37 console.log("Promise failed:", contract-interact.js


err);
38 });
39 }
Step
40
10: Call updateMessage and run contract-interact.js

Finally,
41 wefunction
async can callmain()
updateMessage
{ with our new message by making an await call in
42
main for const message = await helloWorldContract.methods.message().call();
updateMessage with your newMessage.
43 console.log("The message is: " + message);
44 }
Then run node scripts/contract-interact.js from your command line.
45
46 main();

1 require('dotenv').config();
2 const API_URL = process.env.API_URL;
contract-interact-signed.js hosted with ❤ by GitHub view raw
3 const PUBLIC_KEY = process.env.PUBLIC_KEY;
4 const PRIVATE_KEY = process.env.PRIVATE_KEY;
5
6 const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
7 const web3 = createAlchemyWeb3(API_URL);
8
9 const contract = require("../artifacts/contracts/HelloWorld.sol/HelloWorld.json"); // for Hardhat
10 const contractAddress = "0x0d6261a5D3102b565B75Fc680B64093820a17612";
11 const helloWorldContract = new web3.eth.Contract(contract.abi, contractAddress);
12
13 async function updateMessage(newMessage) {
14 const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); // get latest nonce
15 const gasEstimate = await helloWorldContract.methods.update(newMessage).estimateGas(); // esti
16
17 // Create the transaction
18 const tx = {
19 'from': PUBLIC_KEY,
20 'to': contractAddress,
21 'nonce': nonce,
22 'gas': gasEstimate,
23 'data': helloWorldContract.methods.update(newMessage).encodeABI()
24 };
25
26 // Sign the transaction
27 const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY);
28 signPromise.then((signedTx) => {
29 web3.eth.sendSignedTransaction(signedTx.rawTransaction, function(err, hash) {
30 if (!err) {
31 console.log("The hash of your transaction is: ", hash, "\n Check Alchemy's Mempool to vi
32 } else {
33 console.log("Something went wrong when submitting your transaction:", err)
34 }

https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 10/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium
35 }); contract-interact.js
36 }).catch((err) => {
37 console.log("Promise failed:", err);
You should see a response that looks like:
38 });
39 }
40
41Theasync
message
functionis: Hello
main() { world!
42 const message = await helloWorldContract.methods.message().call();
The hash of your transaction is:
430xd6b89d1e31d53b732afc461e04ed0cebc451cfe6e8470519fe06eb4295f5b504
console.log("The message is: " + message);
44 await updateMessage("Hello Drupe!");
Check Alchemy's Mempool to view the status of your transaction!
45 }
46
47 main();
Next visit your Alchemy mempool to see the status of your transaction (whether it’s
pending, mined, or got dropped by the network). If your transaction got dropped,
contract-interact-update.js hosted with ❤ by GitHub
it’s
view raw
also helpful to check Ropsten Etherscan and search for your transaction hash.

‌Once your transaction gets mined, comment out the await updateMessage("Hello

Drupe!"); line in main() and re-run node scripts/contract-interact.js to print out the
new message.‌

Your main() should look like (everything else in your contract-interact.js should stay
the same):

async function main() {


const message = await helloWorldContract.methods.message().call();
console.log("The message is: " + message);
// await updateMessage("Hello Drupe!");
}

After running node scripts/contract-interact.js you should now see the new message
printed to your console:

The message is: Hello Drupe!

And that’s it! You’ve now deployed AND interacted with an Ethereum smart contract. If
you’d like to publish your contract to Etherscan so that anyone will know how to

https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 11/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium
interact with it, stay tuned for part 3: submitted your smart contract to Etherscan! 🎉

Alchemy provides the leading blockchain development platform powering millions of users for
99% of countries worldwide. Our mission is to provide developers with the fundamental
building blocks they need to create the future of technology, and lower the barrier to entry for
developers to build blockchain applications. Alchemy currently powers 70% of the top
Ethereum applications and over $15 billion in on-chain transactions, and have been featured
on TechCrunch, Wired, Bloomberg and numerous other media outlets. The Alchemy team
draws from decades of deep expertise in massively scalable infrastructure, AI, and blockchain
from leadership roles at technology pioneers like Google, Microsoft, Facebook, Stanford, and
MIT.

Never want to miss an update? Subscribe to our newsletter here! Be sure to also
follow our Twitter and join our Discord.

https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 12/13
2/13/23, 2:07 AM 💻 Interacting with a Smart Contract | by Elan Halpern | Alchemy | Medium

Alchemy Smart Contracts Ethereum Metamask Web 3


Open in app Get unlimited access

Search Medium

https://medium.com/alchemy-api/interacting-with-a-smart-contract-4a6bad3bc30 13/13
2/13/23, 2:09 AM Interacting with an Ethereum Smart Contract | by Kerala Blockchain Academy | Blockchain Stories | Medium

Published in Blockchain Stories

Kerala Blockchain Academy Follow

Jun 29, 2022 · 5 min read · Listen

Save

Interacting with an Ethereum Smart Contract


By Sumi Maria Abraham, Research & Development Engineer
Kerala Blockchain Academy.

Do you remember discussing on how programmability went into practical in the


Ethereum Blockchain?? If you have missed reading the early piece of information,
kindly refer here. We saw there a simple, smart contract deployed on a test network.
Moving on, in this feature, we’ll discuss on how to interact with that smart contract.

Image Courtesy: https://iconscout.com/, https://www.shutterstock.com/

Please note that in the previous article we deployed the smart contract in Ropsten test
network. Since Ropsten test network is expected to be shut down later this year, we have used

https://medium.com/blockchain-stories/interacting-with-an-ethereum-smart-contract-aa14401c30a0 1/10
2/13/23, 2:09 AM Interacting with an Ethereum Smart Contract | by Kerala Blockchain Academy | Blockchain Stories | Medium

a similar smart contract deployed in Goerli testnet here.

Contract Address (Goerli): 0x44E84A10341BF772906c37fFc30CDbb132eA35f2

We can interact with an already deployed smart contract by using its contract address
and the ABI. For that, we first need to connect to the blockchain network. Wallets are
simple applications allowing users to connect with a blockchain network. They act as
account managers who manage the user’s keys and transactions. We will be using a
MetaMask wallet to connect with the Goerli test network, which got our smart
contract. MetaMask installation is already described in our previous blog on HD
Wallets. Kindly follow those instructions to install MetaMask.

Connecting to Blockchain network

The wallet will be connected to Ethereum Network (mainnet) by default. You can
switch to a test network, as shown in the figure.

https://medium.com/blockchain-stories/interacting-with-an-ethereum-smart-contract-aa14401c30a0 2/10
2/13/23, 2:09 AM Interacting with an Ethereum Smart Contract | by Kerala Blockchain Academy | Blockchain Stories | Medium

Click on the network name, and enable visibility of test networks. Now switch to Goerli
test network.

To interact with the contract using the wallet, it should have some ether balance.
Goerli is a test network, and its cryptocurrency (Goerli ETH) is available for free from
certain sources called faucets. You can go to any of the below links and request Goerli
ETH by sharing your account address.

Faucets: https://goerli-faucet.slock.it/, https://faucet.goerli.mudit.blog/. Remember,


these are test ethers which do not have any monetary value.

Interacting with Smart Contract

Now we need a tool to interact with our smart contract. We will use Remix IDE for this
purpose. Remix IDE is an open-source web and desktop application. You can directly
access it from your web browser; just go to https://remix.ethereum.org.

Open a new file and copy the ABI from


https://goerli.etherscan.io/address/0x44E84A10341BF772906c37fFc30CDbb132eA35f2#c
ode. Save it as filename.abi

https://medium.com/blockchain-stories/interacting-with-an-ethereum-smart-contract-aa14401c30a0 3/10
2/13/23, 2:09 AM Interacting with an Ethereum Smart Contract | by Kerala Blockchain Academy | Blockchain Stories | Medium

Switch to the deploy and run transaction tab from the menu on the left side. Select the
environment as Injected Web3 to connect with the MetaMask. Make sure you are
logged into MetaMask and connected to the Goerli testnet. Enter the contract address
(0x44E84A10341BF772906c37fFc30CDbb132eA35f2) at the designated place and click on
At Address as shown in the figure. Remix IDE will ask you for confirmation before
loading the contract instance. An instance of the contract will be available under the
heading deployed contracts. You can expand it to interact with it.

CALL vs TRANSACTION

Try to invoke the getMessage function by clicking on it. At the console below the editor
space, you will get the status of the method call.

https://medium.com/blockchain-stories/interacting-with-an-ethereum-smart-contract-aa14401c30a0 4/10
2/13/23, 2:09 AM Interacting with an Ethereum Smart Contract | by Kerala Blockchain Academy | Blockchain Stories | Medium

The getMessage function of our contract performs a simple read-only operation (CALL),
which returns the current value of the message stored on the blockchain. You will be
able to view the present value of the message in the log and below the function under
deployed contracts.

Now, try to invoke the setMessage function. This function writes a value to the message
and stores it on the blockchain. Give a string in the textbox and click on the setMessage.

https://medium.com/blockchain-stories/interacting-with-an-ethereum-smart-contract-aa14401c30a0 5/10
2/13/23, 2:09 AM Interacting with an Ethereum Smart Contract | by Kerala Blockchain Academy | Blockchain Stories | Medium

Since it performs a write operation on the blockchain state, the method invocation is a
transaction. The MetaMask will pop up and ask you for transaction confirmation. This
operation carries a fee, as displayed in the wallet notification, and it will be deducted
from your account. The cost depends upon the requested operation and also some
dynamic network parameters. The same function may require a different fee at a later
time.

Click on confirm. MetaMask will use your private key to sign the transaction and send
it across the network. Once it gets verified by the network and added to the block, you

https://medium.com/blockchain-stories/interacting-with-an-ethereum-smart-contract-aa14401c30a0 6/10
2/13/23, 2:09 AM Interacting with an Ethereum Smart Contract | by Kerala Blockchain Academy | Blockchain Stories | Medium

will get a confirmation from MetaMask (it may take approximately 10–15 seconds). The
transaction details can be seen in the Remix IDE console also.

Click on the view on etherscan option to view transaction in etherscan. The transaction
input data will be in a default encoded format. Click on decode input data to view it in
text format.

https://medium.com/blockchain-stories/interacting-with-an-ethereum-smart-contract-aa14401c30a0 7/10
2/13/23, 2:09 AM Interacting with an Ethereum Smart Contract | by Kerala Blockchain Academy | Blockchain Stories | Medium

You can call the getMessage function again to confirm the new value of the message. Did
you get the message you wrote ?. Congratulations !!.

Deploy your own Smart Contract

Do you wish to deploy the smart contract independently?. It’s simple, just copy the
contract source code of the smart contract and save it in a .sol file in Remix IDE. Now
go to the solidity compiler tab and compile the smart contract. Make sure you see a tick
on the compilation icon.

https://medium.com/blockchain-stories/interacting-with-an-ethereum-smart-contract-aa14401c30a0 8/10
2/13/23, 2:09 AM Interacting with an Ethereum Smart Contract | by Kerala Blockchain Academy | Blockchain Stories | Medium

Next, go to the deploy and run transactions tab. Make sure that your MetaMask is
active and connected to the test network.

Open in app Get unlimited access

Search Medium

Select deployment environment as Injected Web3 to connect to MetaMask. Deploy the


contract. Confirm the MetaMask transaction notification and wait until your contract
deployment transaction is confirmed. Now you can interact with the newly deployed
smart contract.

Images from: https://iconscout.com/, https://www.shutterstock.com/.

https://medium.com/blockchain-stories/interacting-with-an-ethereum-smart-contract-aa14401c30a0 9/10
2/13/23, 2:09 AM Interacting with an Ethereum Smart Contract | by Kerala Blockchain Academy | Blockchain Stories | Medium

Ethereum Smart Contracts Metamask Dapps Blockchain

https://medium.com/blockchain-stories/interacting-with-an-ethereum-smart-contract-aa14401c30a0 10/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - GeeksforGeeks

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

Smart Contracts in Blockchain


Difficulty Level : Medium ● Last Updated : 30 Sep, 2022

Read Discuss

A Smar t Contract (or cr yptocontract) is a computer program that directly and

automatically controls the transfer of digital assets between the par ties under cer tain

conditions. A smar t contract works in the same way as a traditional contract while also

automatically enforcing the contract. Smar t contracts are programs that execute exactly

as they are set up(coded, programmed) by their creators. Just like a traditional contract

is enforceable by law, smar t contracts are enforceable by code. 

The bitcoin network was the first to use some sor t of smar t contract by using them to

transfer value from one person to another. 

The smar t contract involved employs basic conditions like checking if the amount of

value to transfer is actually available in the sender account. 

L ater, the Ethereum platform emerged which was considered more power ful,

precisely because the developers/programmers could make custom contracts in a

Turing-complete language. 

It is to be noted that the contracts written in the case of the bitcoin network were

written in a Turing-incomplete language, restricting the potential of smar t contracts

implementation in the bitcoin network. 

There are some common smar t contract platforms like Ethereum, Solana, Polkadot,

Hyperledger fabric, etc.

Histor y:

In 1994, Nick Szabo, a legal scholar, and a cr yptographer recognized the application of a

decentralized ledger for smar t contracts. He theorized that these contracts could be

Start Your Coding Journey Now! Login


written in code which can be stored and replicated on the system and super vised by the
Register
https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 1/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - GeeksforGeeks

network of computers that constitute the blockchain. These smar t contracts could also

help in transferring digital assets between the par ties under cer tain conditions. 

Features of Smar t Contracts

The following are some essential characteristic s of a smar t contract:

QuickNode -
Learn.Build.Scale
A Full Suite of Blockchain APIs. Build the
Future of Web3 with the Ease of Web2

1. Distributed: Ever yone on the network is guaranteed to have a copy of all the

conditions of the smar t contract and they cannot be changed by one of the par ties. A

smar t contract is replicated and distributed by all the nodes connected to the

network.

2. Deterministic : Smar t contracts can only per form functions for which they are

designed only when the required conditions are met. The final outcome will not var y,

no matter who executes the smar t contract.

3. Immutable : Once deployed smar t contract cannot be changed, it can only be removed

as long as the functionality is implemented previously.

4. Autonomy: There is no third par ty involved. The contract is made by you and shared

between the par ties. No intermediaries are involved which minimizes bullying and

grants full authority to the dealing par ties. Also, the smar t contract is maintained and

executed by all the nodes on the network, thus removing all the controlling power

from any one par ty ’s hand.

5. Customizable : Smar t contracts have the ability for modification or we can say

customization before being launched to do what the user wants it to do. 

Start Your Coding Journey Now!


6. Transparent : Smar t contracts are always stored on a public distributed ledger called

blockchain due to which the code is visible to ever yone, whether or not they are

https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 2/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - GeeksforGeeks

par ticipants in the smar t contract.

7. Trustless : These are not required by third par ties to verif y the integrity of the process

or to check whether the required conditions are met.

8. Self-verif ying : These are self-verif ying due to automated possibilities.

9. Self-enforcing : These are self-enforcing when the conditions and rules are met at all

stages.

Capabilities of Smar t Contracts

1. Accuracy: Smar t contracts are accurate to the limit a programmer has accurately

coded them for execution.

2. Automation: Smar t contracts can automate the tasks/ processes that are done

manually.

3. Speed: Smar t contracts use sof tware code to automate tasks, thereby reducing the

time it takes to maneuver through all the human interaction-related processes.

Because ever ything is coded, the time taken to do all the work is the time taken for

the code in the smar t contract to execute.

4. Backup: Ever y node in the blockchain maintains the shared ledger, providing

probably the best backup facility.

5. Security: Cr yptography can make sure that the assets are safe and sound. Even if

someone breaks the encr yption, the hacker will have to modif y all the blocks that

come af ter the block which has been modified. Please note that this is a highly

difficult and computation-intensive task and is practically impossible for a small or

medium-sized organization to do.

6. Savings : Smar t contracts save money as they eliminate the presence of

intermediaries in the process. Also, the money spent on the paper work is minimal to

zero.

7. Manages information: Smar t contract manages users’ agreement, and stores

information about an application like domain registration, membership records, etc.

8. Multi-signature accounts : Smar t contracts suppor t multi-signature accounts to

distribute funds as soon as all the par ties involved confirm the agreement.

How Do Smar t Contracts Work?

Start Your Coding Journey Now!


A smar t contract is just a digital contract with the security coding of the blockchain.

https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 3/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - GeeksforGeeks

It has details and permissions written in code that require an exact sequence of

events to take place to trigger the agreement of the terms mentioned in the smar t

contract. 

It can also include the time constraints that can introduce deadlines in the contract. 

Ever y smar t contract has its address in the blockchain. The contract can be

interacted with by using its address presuming the contract has been broadcasted on

the network. 

The idea behind smar t contracts is pretty simple. They are executed on a basis of simple

logic, IF-THEN for example: 

IF you send object A , THEN the sum (of money, in cr yptocurrency) will be transferred

to you.

IF you transfer a cer tain amount of digital assets (cr yptocurrency, for example, ether,

bitcoin), THEN the A object will be transferred to you.

IF I finish the work, THEN the digital assets mentioned in the contract will be

transferred to me.

Note : The WHEN constraint can be added to include the time factor in the smar t

contracts. It can be seen that these smar t contracts help set conditions that have to be

fulfilled for the terms of the contract agreement to be executed. There is no limit on how

much IF or THEN you can include in your intelligent contract. 

Smar t Contract Working

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 4/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - GeeksforGeeks

Identif y Agreement : Multiple par ties identif y the cooperative oppor tunity and

desired outcomes and agreements could include business processes, asset swaps,

etc.

Set conditions : Smar t contracts could be initiated by par ties themselves or when

cer tain conditions are met like financial market indices, events like GPS locations,

etc.

Code business logic : A computer program is written that will be executed

automatically when the conditional parameters are met.

Encr yption and blockchain technology: Encr yption provides secure authentication

and transfer of messages between par ties relating to smar t contracts.

Execution and processing : In blockchain iteration, whenever consensus is reached

between the par ties regarding authentication and verification then the code is

executed and the outcomes are memorialized for compliance and verification.

Network updates : Af ter smar t contracts are executed, all the nodes on the network

update their ledger to reflect the new state. Once the record is posted and verified on

the blockchain network, it cannot be modified, it is in append mode only.

Applications of Smar t Contracts

1. Real Estate : Reduce money paid to the middleman and distribute between the

Start Your Coding Journey Now!


par ties actually involved. For example, a smar t contract to transfer ownership of an

https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 5/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - GeeksforGeeks

apar tment once a cer tain amount of resources have been transferred to the seller ’s

account(or wallet).

2. Vehicle ownership: A smar t contract can be deployed in a blockchain that keeps track

of vehicle maintenance and ownership. The smar t contract can, for example, enforce

vehicle maintenance ser vice ever y six months; failure of which will lead to

suspension of driving license.

3. Music Industr y: The music industr y could record the ownership of music in a

blockchain. A smar t contract can be embedded in the blockchain and royalties can be

credited to the owner ’s account when the song is used for commercial purposes. It

can also work in resolving ownership disputes.

4. Government elections : Once the votes are logged in the blockchain, it would be ver y

hard to decr ypt the voter address and modif y the vote leading to more confidence

against the ill practices.

5. Management : The blockchain application in management can streamline and

automate many decisions that are taken late or deferred. Ever y decision is

transparent and available to any par ty who has the authority(an application on the

private blockchain). For example, a smar t contract can be deployed to trigger the

supply of raw materials when 10 tonnes of plastic bags are produced.

6. Healthcare : Automating healthcare payment processes using smar t contracts can

prevent fraud. Ever y treatment is registered on the ledger and in the end, the smar t

contract can calculate the sum of all the transactions. The patient can’t be discharged

from the hospital until the bill has been paid and can be coded in the smar t contract.

Example Use cases :  

1. Smar t contracts provide utility to other contracts. For example, consider a smar t

contract that transfers funds to par ty A af ter 10 days. Af ter 10 days, the above-

mentioned smar t contract will execute another smar t contract which checks if the

required funds are available at the source account(let ’s say par ty B).

2. They facilitate the implementation of ‘multi-signature’ accounts, in which the assets

are transferred only when a cer tain percentage of people agree to do so

3. Smar t contracts can map legal obligations into an automated process.

4. If smar t contracts are implemented correctly, can provide a greater degree of

contractual security.

Start Your Coding Journey Now!


Advantages of Smar t Contracts

https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 6/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - GeeksforGeeks

1. Recordkeeping : All contract transactions are stored in chronological order in the

blockchain and can be accessed along with the complete audit trail. However, the

par ties involved can be secured cr yptographically for full privacy.

2. Autonomy: There are direct dealings between par ties. Smar t contracts remove the

need for intermediaries and allow for transparent, direct relationships with

customers.

3. Reduce fraud: Fraudulent activity detection and reduction. Smar t contracts are

stored in the blockchain. Forcefully modif ying the blockchain is ver y difficult as it ’s

computation-intensive. Also, a violation of the smar t contract can be detected by the

nodes in the network and such a violation attempt is marked invalid and not stored in

the blockchain.

4. Fault-tolerance : Since no single person or entity is in control of the digital assets,

one-par ty domination and situation of one par t backing out do not happen as the

platform is decentralized and so even if one node detaches itself from the network,

the contract remains intact.

5. Enhanced trust : Business agreements are automatically executed and enforced.

Plus, these agreements are immutable and therefore unbreakable and undeniable.

6. Cost-efficiency: The application of smar t contracts eliminates the need for

intermediaries(brokers, law yers, notaries, witnesses, etc.) leading to reduced costs.

Also eliminates paper work leading to paper saving and money-saving.

Challenges of Smar t Contracts

1. No regulations : A lack of international regulations focusing on blockchain

technology(and related technology like smar t contracts, mining, and use cases like

cr yptocurrency) makes these technologies difficult to oversee.

2. Difficult to implement : Smar t contracts are also complicated to implement because

it ’s still a relatively new concept and research is still going on to understand the

smar t contract and its implications fully.

3. Immutable : They are practically immutable. Whenever there is a change that has to

be incorporated into the contract, a new contract has to be made and implemented in

the blockchain.

4. Alignment : Smar t contracts can speed the execution of the process that span

multiple par ties irrespective of the fact whether the smar t contracts are in alignment

Start Your Coding Journey Now!


with all the par ties’ intention and understanding.

https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 7/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - GeeksforGeeks

Like 15

Previous Next

Related Articles

1. Difference Between Dapps, Crypto Wallets and Smart Contracts

2. Smart Contracts and IoT

3. Timestamp Dependency in Smart Contracts

4. Overflow and Underflow Attacks on Smart Contracts

5. Reentrancy Attack in Smart Contracts

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

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


(Blockchain)?

8. Solidity - Basics of Contracts


Start Your Coding Journey Now!
https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 8/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - GeeksforGeeks

9. Creating Ownable Contracts in Solidity

10. Steps to Execute Solidity Smart Contract using Remix IDE

Ar ticle Contributed By :

Parikshit Hooda
@Parikshit Hooda

Vote for difficulty

Current difficulty : Medium

Easy Normal Medium Hard Expert

Improved By : mcaarts, kashishsoda, rkbhola5, rashi_garg

Article Tags : Blockchain, Technical Scripter

Improve Article Report Issue

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


Sector-136, Noida, Uttar Pradesh - 201305
[email protected]

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 9/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - 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

Web Development Contribute


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

@geeksforgeeks , Some rights reserved

Start Your Coding Journey Now!


https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 10/10
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

ABHISHEK KUMAR Follow

Apr 30, 2018 · 11 min read · Listen

Save

Smart Contracts On The Blockchain: A deep dive


in to Smart Contracts
It is becoming difficult for the ordinary person to avoid the Blockchain buzz, and
Businesses cannot shy away from blockchain either.

Many multinational companies have already jumped onto the blockchain bandwagon
and are working on their own projects to stay ahead of the competition.

According to Accenture research published at the start of 2017, investment banks alone
could save up to $12 billion per year by adopting blockchain and smart contracts,
effectively a program code that automatically performs some actions when pre-
defined conditions occur (i.e. if X does Y, then execute Z).

Gartner has estimated that by 2022, smart contracts will be in use by more than 25% of
global organizations.

Major technology providers like IBM ,Microsoft ,TCS ,Accenture are offering
blockchain solutions to enterprise clients. Tech start-ups too are aggressively
capitalizing on the boom by building new products and services that depend on the
technology.

For other businesses, however, the big question is how blockchain adoption can
benefit them. There is no question that modern business environments require
companies to make technology integral to their strategy.

https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 1/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

Cost Reduction & Efficiencies: Cutting out middleman means savings for the business.
According to a McKinsey report it is estimated that blockchain could save businesses at
least $50 billion in B2B transactions by 2021.

So what are Smart Contracts

A smart contract is a computer protocol intended to digitally facilitate, verify, or


enforce the negotiation or performance of a contract. Smart contracts allow the
performance of credible transactions without third parties. These transactions are
trackable and irreversible.Smart contracts were first proposed by Nick Szabo, who
coined the term, in 1994.

Proponents of smart contracts claim that many kinds of contractual clauses may be
made partially or fully self-executing, self-enforcing, or both. The aim of smart
contracts is to provide security that is superior to traditional contract law and to reduce
other transaction costs associated with contracting. Various cryptocurrencies have
implemented types of smart contracts.

‘Smart contracts’, are programs that are written on the underlying distributed ledger
and are executed automatically by nodes on the network. Smart contract have to be
verifiable by each node on the network, it means that all nodes on the network must
see the same data. Smart contracts are complex and their potential goes beyond the
simple transfer of assets, being able to execute transactions in a wide range of fields.
Such as insurance, crowdfunding , logistics, medicine, gaming industry, entertainment
industry, etc.

https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 2/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

Blockchain was initially designed for P2P money only. But it soon showed the potential
to be used for any kind of P2P value transaction on top of the Internet. The Ethereum
project thus introduced the idea of decoupling the contract layer from the blockchain
layer, where the ledger itself is used by smart contracts that trigger transactions
automatically when certain pre-defined conditions are met. By decoupling the smart
contract layer from the blockchain layer, Blockchains like Ethereum aim to provide a
more flexible development environment than the Bitcoin Blockchain.

A smart contract is a computer code running on top of a blockchain containing a set of


rules under which the parties to that smart contract agree to interact with each other.
If and when the pre-defined rules are met, the agreement is automatically enforced.
The smart contract code facilitates, verifies, and enforces the negotiation or
performance of an agreement or transaction. It is the simplest form of decentralized
automation.

It is a mechanism involving digital assets and two or more parties, where some or all of
the parties deposit assets into the smart contract and the assets automatically get
redistributed among those parties according to a formula based on certain data, which
is not known at the time of contract initiation.

If and when all parties to the smart contract fulfill the pre-defined arbitrary rules, the
smart contract will auto execute the transaction. These smart contracts aim to provide
transaction security superior to traditional contract law and reduce transaction costs of
coordination and enforcement.

The term smart contract is a bit unfortunate since a smart contract is neither smart
nor are they to be confused with a legal contract.

•A smart contract can only be as smart as the people coding taking into account all
available information at the time of coding.

•While smart contracts have the potential to become legal contracts if certain
conditions are met, they should not be confused with legal contracts accepted by
courts and or law enforcement. However, we will probably see a fusion of legal
contracts and smart contracts emerge over the next few years as the technology
becomes more mature and widespread and legal standards are adopted.

https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 3/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

Many people are critical of the name “smart contract”. One reason being that a smart
contract is not necessarily smart. It is just a set of instructions that anyone can write,
and people are very capable of creating some pretty dumb smart contracts.

The name smart contract is also misleading because it is not really a contract, at least
not in the sense that it’s anything that needs to be complied with or upheld. A normal
contract has legal consequences in the ‘real world’. If the counterparty of a contract
does not uphold their part of the agreement, the legal system can be used to hold them
accountable. On the contrary, a smart contract does not have to be upheld by anyone,
it’s a set of instructions that self-executes. A smart contact does not have much
precedence in the ‘real world’. It is only able to send transactions to other accounts on
the blockchain, any other precedence must be acquired by creating a legal wrapper
around the blockchain agreement.

Smart Contract Code is a Law

A smart contract essentially consists of two elements which you need to


understand/trust:

The code and how this is interpreted

The immutability of the blockchain

Just like with normal contracts, it´s important to understand the actual content of a
smart contract when interacting with it. But unlike a normal contract, which is written
in legalese and interpreted by the legal system, the content of the smart contract is
written in computer code and interpreted by computers. So what does smart contract
code actually look like.

Below is an example, an extract of a smart contract (don’t worry if you are not a
technical person you’re not expected to understand it):

function payOut(address _recipient, uint _amount) returns (bool) {

if (msg.sender != owner || msg.value > 0 || (payOwnerOnly && _recipient != owner))

throw;

https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 4/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

if (_recipient.call.value(_amount)()) {

PayOut(_recipient, _amount);

return true;

} else {

return false;

The smart contract code is the terms and conditions that you are signing up for when
interacting with a smart contract. As long as you trust the blockchain that the smart
contract resides on, you know that the code will execute exactly as programmed — so
no breach of agreement can exist. It is important to note however, that working as
programmed does not mean that it will work as intended if there are errors in the
code.

Smart contracts can be used for simple economic transactions like sending money
from A to B. They can also be used for registering any kind of ownership and property
rights like land registries and intellectual property, or managing smart access control
for the sharing economy, just to name a few. Furthermore, smart contracts can be used
for more complex transactions like governing a group of people that share the same
interests and goals. Decentralized Autonomous Organizations (DAOs) , are such an
example for more complex smart contracts.

How to create a Smart Contract?

To create a smart contract you need:

a) Subject of the contract:The program must have access to goods or services under
contract to lock and unlock them automatically.

b) Digital signatures: All the participants initiate an agreement by signing the contract
with their private keys.
https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 5/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

c) Contract terms: Terms of a smart contract take the form of an exact sequence of
operations. All participants must sign these terms.

d) Decentralized platform: The smart contract is deployed to the Blockchain of this


platform and distributed among the nodes of the platform.

Benefits of a Smart Contract

Smart contracts use all the benefits of Blockchain technology & provide:

a) Security: The smart contract is encrypted and distributed among nodes. This
guarantees that it will not be lost or changed without your permission.

b) Economy and speed:Most processes are automated, and most intermediaries are
eliminated.

c) Standardization: There is a wide range of different types of smart contracts


nowadays. You can choose one and change it according to your needs.

d) Radically reduce transaction costs (bureaucracy) through machine consensus and


auto-enforceable code.

e) Bypass the traditional principal-agent dilemmas of organizations, thus providing an


operating system for what some refer to as “trustless trust”.

This means that you don’t have to trust people and organizations, you trust code, which
is open source and provides transparent processes.

With blockchains and smart contracts we can now imagine a world in which contracts
are embedded in digital code and stored in transparent, shared databases, where they
are protected from deletion, tampering, and revision.

In this world every agreement, every process, task and payment would have a digital
record and signature that could be identified, validated, stored, and shared
Intermediaries like lawyers, brokers, and bankers, and public administrators might no
longer be necessary. Individuals, organizations, machines, and algorithms would
freely transact and interact with one another with little friction and a fraction of
current transaction costs.
https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 6/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

A smart contract can formalize the relationships between people, institutions and the
assets they own.

The transaction rulesets (agreement) of the smart contract define the conditions —
rights and obligations to which the parties of a protocol or smart contract consent.

Although the concept of smart contracts is not new, blockchain technologies seem to
be the catalyst for smart contract implementation.

Below Diagram explains the working of a SmartContract

Example of a Smart contract Explained Below

If A and B don’t know and don’t trust each other, they usually need a trusted third party
to serve as an intermediary to verify transactions and enforce them. With smart
contracts & blockchains, you don’t need those trusted intermediaries anymore for
clearing or settlement of your transactions. Take the example of buying and selling a
car:

Below Diagram explains the working a Traditional Contract for the Smart Contract
Example

https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 7/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

On the Blockchain, once all involved authorities and companies are on a blockchain, a
smart contract couldbe used to define all the rules of a valid care sale. If Alice wanted
to buy the car from Bob usinga smart contract on the blockchain, the transaction
would be verified by each node in the BlockchainNetwork to see if Bob is the owner of
the car and if Alice has enough money to pay Bob.

Below Diagram explains the working of the Smart Contract Example

https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 8/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

If the network agrees that both conditions are true, Alice automatically gets the access
code to the smart lock for the garage. The blockchain registers Alice as the new owner
of the car. Bob has € 20,000 more on his account, and Alice € 20,000 less. No
middlemen required. On the Blockchain, who owns what is transparent and at the
same time anonymous or pseudonymous. This means that every computer running the
blockchain protocol could check whether a certain person is the rightful owner of the
car or not.Stealing cars won’t be as easy as today, especially once we have smart keys
granting access control verified on the blockchain, to unlock our future vehicles. As
the owner of the car, you could authorize other people to drive it (stating the public key
of the respective individual). In such cases opening the car would only be possible with
a smart key on the Blockchain.

https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 9/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

Usecases of Smartcontracts can be across many industries

Blockchain and smart contracts have the potential to disrupt many industries. Use
cases can be found in banking, insurance, energy, e-government, telecommunication,
music & film industry, art world, mobility, education and many more. Smart contract
use cases range from simple to complex.

Time-stamping services like ascribe (art registry) or governmental and semi-


governmental registries (land titles, birth certificates, birth certificates, school and
university degrees) are examples for simpler technological use cases (the regulatory
aspects might be more complex). Decentralized autonomous organizations, on the
other hand, are the most complex form of a smart contract. TheDAO in 2016 was an
example for such a complex smart contract.

Below are the list of usecases where Blockchain & Smartcontracts can disrupt the the
industries

Types of Smart Contracts

Below diagram explains the various types of Smart contracts

https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 10/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

Given the fact that Blockchain is still a new technology, some industries might adopt
smart contracts later than others, especially if they are subject to heavy government
regulation or if the uses cases require high network effects — like widespread
technology adoption along the supply chain, standardization, etc. In general, it’s
advisable to start out with a small pilot project of a less complex use case to build
expertize and understand the technology better and move on to more complex use
case at a later stage.

Furthe reading

http://internetofagreements.com/files/WorldGovernmentSummit-Dubai2017.pdf

Smart legal Contracts, Florian Glatz

OpenLaw, Consensys

Smart Contract Coding

Solidity is a smart contract programming language. The syntax is similar to that of


JavaScript, and it is designed to compile to code for the Ethereum Virtual Machine, to
create contracts for voting, crowdfunding, blind auctions, multi-signature wallets and
more.

Below are the various links related to Smartcontract coding

1) Official Solidity Documentation, by Ethereum Foundation

https://solidity.readthedocs.io/en/latest/

2) Solidity Tutorial
https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 11/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

https://medium.com/@ConsenSys/solidity-integration-with-visual-studio-8bdab2ff8a74

3) Standardized_Contract_APIs

https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs

4) Interacting with smart contracts

http://ethdocs.org/en/latest/contracts-and-transactions/accessing-contracts-and-
transactions.html#interacting-with-smart-contracts

5) Remix Ethereum

https://github.com/ethereum/remix

6) The Hitchhiker’s Guide to Smart Contracts in Ethereum

https://blog.zeppelin.solutions/the-hitchhikers-guide-to-smart-contracts-in-ethereum-
848f08001f05

7) trufflesuite/truffle

https://github.com/trufflesuite/truffle

Sources:

1.https://bitcoinmagazine.com/articles/smart-contracts-described-by-nick-szabo-years-
ago-now-becoming-reality-1461693751/

2.https://en.wikipedia.org/wiki/Smart_contract

3.https://blockgeeks.com/guides/smart-contracts/

4.https://www.ethereum.org/token

5) PWC

6) Forbes

7) BlockchainHub
https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 12/13
2/13/23, 2:12 AM Smart Contracts On The Blockchain: A deep dive in to Smart Contracts | by ABHISHEK KUMAR | Medium

Please note: The material has been reproduced from various sources & is strictly for
educational ,illustrative purposes & for promotion of Blockchain Technology.

Blockchain Smart Contracts Solidity Ethereum Blockchain Ethereum


Open in app Get unlimited access

Search Medium

https://abhibvp003.medium.com/smart-contracts-on-the-blockchain-a-deep-dive-in-to-smart-contracts-9616ad26428c 13/13
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

Published in Coinmonks

Ayuba Muazu Follow

May 28, 2018 · 13 min read · Listen

Save

A really simple smart contract on how to insert


value into the ethereum blockchain and display it
on a webpage
In this tutorial, I am going to walk you through the steps of creating and deploying
smart contracts on the ethereum blockchain.

The aim of this tutorial is to teach you

i. Tools needed to create a smart contract

ii. How to create a basic smart contract

iii. How to deploy your smart contract to the ethereum blockchain

iv. How to interact with a smart contract via a webpage

v. How to call a function to store value to the blockchain from a webpage via a smart
contract

vi. How to call a function to display value stored on a blockchain via a smart contract

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 1/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

Discover and review best Ethereum development


tools
By the end of this tutorial we shall a web interface that looks like this.

you can find the complete source code on my github page here
https://github.com/yubzee/SimpleStorage

Assumption

It is assumed you know about blockchain and smart contract and also you know the
basics of html and javascript.

So let’s get our hands dirty

Tools Needed to create a smart contract


Remix IDE :- Remix is Ethereum IDE for the smart contract programming language
called Solidity and has an integrated debugger and testing environment. An up to
date online version is available at [remix.ethereum.org]
(http://remix.ethereum.org).

Remix is a good solution if you intend to

a. Develop smart contracts (remix integrates a solidity editor).

b. Debug a smart contract’s execution.

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 2/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

c. Access the state and properties of already deployed smart contract.

d. Debug already committed transaction.

e. Analyze solidity code to reduce coding mistakes and to enforce best practices

f. Together with Mist or Metamask (or any tool which inject web3), Remix can be used
to test and debug a dApp

MetaMask :- Metamask is a bridge that allows you to visit the distributed web of
tomorrow in your browser today. It allows you to run Ethereum dApps right in your
browser without running a full Ethereum node. MetaMask includes a secure
identity vault, providing a user interface to manage your identities on different
sites and sign blockchain transactions. You can install the MetaMask add-on in
Chrome, Firefox, Opera, and the new Brave browser. If you’re a developer, you can
start developing with MetaMask today.

Install Metamask add-on from here and follow the steps to create an account . Make
sure to save the 12 word passphrase because it’s the only way to recover your account if
you forget your password or private key. You should have something that looks like this

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 3/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

You now have an account on metamask and you can use it for interacting with dApps
and Smart Contracts.

Make sure you switch the account to Ropsten Test Network (Ethers on the Ropsten Test
Network are worthless and we are going to need them for development purposes).

Click on the buy button > Ropsten Test Faucet and request for as many faucet ethers
that you can get.

How to create a basic smart contract


We are going to create a really simple but very powerful dApp. Our dApp would enable
users to modify the state of an integer value in the blockchain. Users of our dApp
would interact with our smart contract via a simple html page and Metamask.

Now go to http://remix.ethereum.org to launch your remix IDE. Remember to use


Chrome,Firefox,Opera or Brave browser.

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 4/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

The RemixIDE creates a sample voting contract for you called Ballot.sol. But we want
to create a simple contract of our own from scratch. Click on the +(plus) button at the
top left corner to create a new file.

Note: files created using the RemixIDE are stored in your browser’s internal storage

Give the file the name SimpleStorage.sol

Copy and Paste the following Code in the IDE

pragma solidity ^0.4.4;


contract SimpleStorage{
uint storeddata;
function set(uint x) public{
storeddata = x;
}
https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 5/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

function get() public view returns(uint){


return storeddata;
}
}

Let me explain each line of code.

The first line simply tells that the source code is written for Solidity version 0.4.0 or
anything newer that does not break functionality (up to, but not including, version
0.5.0). This is to ensure that the contract does not suddenly behave differently with
a new compiler version. The keyword pragma is called that way because, in
general, pragmas are instructions for the compiler about how to treat the source
code (e.g. pragma once).

The second line contract SimpleStorage tells the solidity compiler we are creating
a new contract called SimpleStorage. To create a new contract in solidity, we use
the keyword contract. A contract in the sense of Solidity is a collection of code (its
functions) and data (its state) that resides at a specific address(yes every contract
must reside at a specific address) on the Ethereum blockchain.

The line uint storedData; declares a state variable called storedData of type uint
(unsigned integer of 256 bits). You can think of it as a single slot in a database that
can be queried and altered by calling functions of the code that manages the
database. In the case of Ethereum, this is always the owning contract(which of
course has an address). And in this case, the functions set and get can be used to
modify or retrieve the value of the variable.

This contract does not do much yet (due to the infrastructure built by Ethereum) apart
from allowing anyone to store a single number that is accessible by anyone in the
world without a (feasible) way to prevent you from publishing this number. Of course,
anyone could just call set again with a different value and overwrite your number, but
the number will still be stored in the history of the blockchain forever.

Later, In the next coming lesson, I will show you how you can impose access
restrictions so that only you can alter the number.

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 6/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

Everything should look like this

How to deploy your smart contract to the ethereum blockchain


To deploy our smart contract to the ethereum blockchain, we need to deploy through
metamask via the injected web3 and in our case running on the Ropsten TestNetwork.

So let’s compile our smart contract. Click on the compile tab at the top right corner
and then click on the button start to compile to compile the smart contract.

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 7/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

Hopefully it would compile without any error.

Next click on the Run tab to deploy the smart contract to the ethereum blockchain.

Let me explain what is happening here

The first line called Environment shows the network node we are connected to.
Since we are using Metamask, select Injected Web3 from the list and remember on
your metamask make sure you are on the Ropsten Test Network and your account
has enough ether to pay for gas.

The next line called Account displays your ethereum address and your ether
balance. This kind of account is called Externally owned Account (EOS)

The remaining two lines shows the Gas limit and the value we are willing to pay for
the deployment of the smart contract. Skip these lines and proceed to deploy the
contract.

Click on the Deploy button to deploy the contract to the blockchain.


https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 8/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

This action would invoke metamask via the injected web3

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 9/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

You can increase the Gas Price to maybe 3 or 4 GWEI for faster transaction mining.

Finally click on the submit button to add the contract to the blockchain.

After that click the sent tab on metamask to view your contract status

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 10/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

Then click on the newly created contract to view you contract information on
Etherscan

Copy the contract Address and save it somewhere we are going to need it later.

Congratulations you have successful created and deployed a smart contract unto the
ethereum blockchain.

Take a deep breath if you have made it this far. You are now a Solidity smart contract
developer.
https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 11/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

How to interact with a smart contract via a webpage


For users to interact with our smart contract, they need an interface. We are going to
build a simple webpage that enable users to call our smart contract and access its
public functions.

Copy and paste the following HTML code into your favorite code editor

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset=”utf-8" />
</head>
<body>
<center>
<div id=”metamask”></div>
<h3>Insert and retrieve value on the blockchain</h3>
<br />
<table>
<tr>
https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 12/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

<td></td>
<td>
<div id=”xbalance”></div>
</td>
</tr>
<tr>
<td>Insert a new value :</td>
<td>
<input id=”xvalue” type=”text” />
<input id=”Button1" type=”button” onclick=”setvalue()” value=”Add to
Blockchain” />
</td>
</tr>
</table>
</center>
</body>
</html>

The html code here is pretty straight forward

Now add the following javascript code just below the body tag and before the center
tag of your HTML page.

<script>
window.onload = function () {
// check to see if user has metamask addon installed on his browser.
check to make sure web3 is defined
if (typeof web3 === ‘undefined’) {
document.getElementById(‘metamask’).innerHTML = ‘You need <a
href=”https://metamask.io/">MetaMask</a> browser plugin to run this
example’
}

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 13/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

// call the getvalue function here


getvalue();
}
</script>

we communicate with ethereum blockchain from our metamask through web3. the
piece of javascript above checks to see if metamask addon is installed on the user’s
browser and if not, a message instructing him to install metamask

How to call a function to display value stored on a blockchain via a smart


contract
from the script above just below the comment line

//call the getvalue function here

we call the get function of our smart contract to retrieve the last integer value inserted
on the blockchain via our smart contract.

now lets create the get value function.

add the following piece of code after the last closing braces }

//function to retrieve the last inserted value on the blockchain


function getvalue() {
try {
// contract Abi defines all the variables,constants and functions of
the smart contract. replace with your own abi
var abi = [
{
“constant”: false,
“inputs”: [

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 14/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

{
“name”: “x”,
“type”: “uint256”
}
],
“name”: “set”,
“outputs”: [],
“payable”: false,
“stateMutability”: “nonpayable”,
“type”: “function”
},
{
“constant”: true,
“inputs”: [],
“name”: “get”,
“outputs”: [
{
“name”: “”,
“type”: “uint256”
}
],
“payable”: false,
“stateMutability”: “view”,
“type”: “function”
}
]
//contract address. please change the address to your own
var contractaddress = ‘0x9b5bb96009bf3562a53bbbc491fe1e12338778a7’;
//instantiate and connect to contract address via Abi
var myAbi = web3.eth.contract(abi);
var myfunction = myAbi.at(contractaddress);
https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 15/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

//call the get function of our SimpleStorage contract


myfunction.get.call(function (err, xname) {
if (err) { console.log(err) }
if (xname) {
//display value on the webpage
document.getElementById(“xbalance”).innerHTML = “last inserted value
into the blockchain is : “ + xname;
}
});
}
catch (err) {
document.getElementById(“xbalance”).innerHTML = err;
}
}

notice the line

var abi=(“our abi here… please replace with your own”)

ABI stands for application binary interface.

In general, an ABI is basically how you call functions in a contract and get data back

An Ethereum smart contract is bytecode deployed on the Ethereum blockchain. There


could be several functions in a contract. An ABI is necessary so that you can specify
which function in the contract to invoke, as well as get a guarantee that the function
will return data in the format you are expecting.

to get your contract ABI, switch back to the remix IDE and click the compile tab at the
top right corner, then click details button

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 16/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

copy the ABI code(you need to scroll down to see it)

and replace it on the line

var abi=(“replce with your abi here…”)

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 17/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

switch back to your HTML page and also replace the contract address with your own.

var contractaddress = ‘replace with your own here..’;

when you are done, you can preview the HTML page to view the last integer value that
was stored on the blockchain via your smart contract.

if this is the first time, the value would return zero(0)

How to call a function to store value to the blockchain from a webpage via a
smart contract
calling the set function on our smart contract to add value to the blockchain is also
quite easy and similar to the procedures of the get function

copy and paste the following line of code after the last closing braces of your getvalue
function in your HTML page

// function to add a new integer value to the blockchain


function setvalue() {
try {
// contract Abi defines all the variables,constants and functions of
the smart contract. replace with your own abi
var abi = [
{

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 18/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

“constant”: false,
“inputs”: [
{
“name”: “x”,
“type”: “uint256”
}
],
“name”: “set”,
“outputs”: [],
“payable”: false,
“stateMutability”: “nonpayable”,
“type”: “function”
},
{
“constant”: true,
“inputs”: [],
“name”: “get”,
“outputs”: [
{
“name”: “”,
“type”: “uint256”
}
],
“payable”: false,
“stateMutability”: “view”,
“type”: “function”
}
]
//contract address. please change the address to your own
var contractaddress = ‘0x9b5bb96009bf3562a53bbbc491fe1e12338778a7’;
//instantiate and connect to contract address via Abi
https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 19/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

var myAbi = web3.eth.contract(abi);


var myFunction= myAbi.at(contractaddress);
//call the set function of our SimpleStorage contract
myFunction.set.sendTransaction(document.getElementById(“xvalue”).value
, { from: web3.eth.accounts[0], gas: 4000000 }, function (error,
result) {
if (!error) {
console.log(result);
} else {
console.log(error);
}
})
} catch (err) {
document.getElementById(“xvalue”).innerHTML = err;
}
}

remember to change the contract ABI to your own.

here is the complete code you could just copy and paste

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<script>

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 20/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

window.onload = function () {
// check to see if user has metamask addon installed on his browser.
check to make sure web3 is defined
if (typeof web3 === 'undefined') {
document.getElementById('metamask').innerHTML = 'You need <a
href="https://metamask.io/">MetaMask</a> browser plugin to run this
example'
}
// call the getvalue function here
getvalue();
}
//function to retrieve the last inserted value on the blockchain
function getvalue() {
try {
// contract Abi defines all the variables,constants and functions of
the smart contract. replace with your own abi
var abi = [
{
"constant": false,
"inputs": [
{
"name": "x",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 21/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

"constant": true,
"inputs": [],
"name": "get",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]
//contract address. please change the address to your own
var contractaddress = '0xc80cae7c51f27bc25b3862d072d56fa84965f5c1';
//instantiate and connect to contract address via Abi
var myAbi = web3.eth.contract(abi);
var myfunction = myAbi.at(contractaddress);
//call the get function of our SimpleStorage contract
myfunction.get.call(function (err, xname) {
if (err) { console.log(err) }
if (xname) {
//display value on the webpage
document.getElementById("xbalance").innerHTML = "last inserted value
into the blockchain is : " + xname;
}
});
}
catch (err) {
document.getElementById("xbalance").innerHTML = err;

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 22/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

}
}
// function to add a new integer value to the blockchain
function setvalue() {
try {
// contract Abi defines all the variables,constants and functions of
the smart contract. replace with your own abi
var abi = [
{

"constant": false,
"inputs": [
{
"name": "x",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "get",
"outputs": [
{
"name": "",
"type": "uint256"
}

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 23/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]
//contract address. please change the address to your own
var contractaddress = '0xc80cae7c51f27bc25b3862d072d56fa84965f5c1';
//instantiate and connect to contract address via Abi
var myAbi = web3.eth.contract(abi);
var myfunction = myAbi.at(contractaddress);
//call the set function of our SimpleStorage contract
myfunction.set.sendTransaction(document.getElementById("xvalue").value
, { from: web3.eth.accounts[0], gas: 4000000 }, function (error,
result) {
if (!error) {
console.log(result);
} else {
console.log(error);
}
})
} catch (err) {
document.getElementById("xvalue").innerHTML = err;
}
}
</script>
<center>
<div id="metamask"></div>
<h3>Insert and retrieve value on the blockchain</h3>
<br />
<table>

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 24/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

<tr>
<td></td>
<td>
<div id="xbalance"></div>
</td>
</tr>
<tr>
<td>Insert a new value :</td>
<td>
<input id="xvalue" type="text" />
<input id="Button1" type="button" onclick="setvalue()" value="Add to
Blockchain" />
</td>
</tr>
</table>
</center>
</body>
</html>

Testing our dAPP


whenever we are adding value to the ethereum blockchain,we need to pay for gas.

so enter an integer value in the textbox and click the add to blockchain button.

pay for the gas amount and wait for your transation to be processed and mined.

refresh the browser to retrieve the new value you have added.

If you have made it this far, then congratulation on being a dApp developer.

Im open to questions if you face any challenges or recommendations

goodluck

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 25/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

Donations are always appreciated

Ethereum Address: 0xf98AB27F68136133eba36B6c92753496173cBf02

Join Coinmonks Telegram Channel and Youtube


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

Grid Trading | Crypto Hardware Wallet

Crypto Telegram Signals | Crypto Trading Bot

What are the Trading Signals? | Bitstamp vs Coinbase

ProfitFarmers Review | How to use Cornix Trading Bot

How to Buy Domain Name on Unstoppable Domains?

Crypto Tax in India | altFINS Review | Prokey Review

Best Crypto Exchange | Best Crypto Exchange in India

Best Crypto APIs for Developers

Best Crypto Lending Platform

An ultimate guide to Leveraged Token

Ethereum Solidity Smart Contracts Dapps Tutorial

Sign up for Coinmonks 390 24


https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 26/27
2/13/23, 2:17 AM A really simple smart contract on how to insert value into the ethereum blockchain and display it on a webpage | by Ayuba Muazu |…

By Coinmonks

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

Open
Emails in
willapp
be sent to [email protected]. Not you? Get unlimited access

Get this newsletter


Search Medium

https://medium.com/coinmonks/a-really-simple-smart-contract-on-how-to-insert-value-into-the-ethereum-blockchain-and-display-it-62c455610e98 27/27
2/13/23, 2:19 AM Solidity — transfer vs send vs call function | by Zuhaib Mohammed | Coinmonks | Medium

Published in Coinmonks

Zuhaib Mohammed Follow

Dec 31, 2021 · 2 min read · Listen

Save

Solidity — transfer vs send vs call function

In Solidity, there are three ways in which one can send ether. Namely transfer(),
send() and call(). In this article, let us discuss how each function call works
and which is the best one to use.

transfer vs send vs call

https://medium.com/coinmonks/solidity-transfer-vs-send-vs-call-function-64c92cfc878a 1/4
2/13/23, 2:19 AM Solidity — transfer vs send vs call function | by Zuhaib Mohammed | Coinmonks | Medium

1. transfer -> the receiving smart contract should have a fallback function defined or
else the transfer call will throw an error. There is a gas limit of 2300 gas, which is
enough to complete the transfer operation. It is hardcoded to prevent reentrancy
attacks.

transfer() function

2. send -> It works in a similar way as to transfer call and has a gas limit of 2300 gas as
well. It returns the status as a boolean.

send() function

3. call ->It is the recommended way of sending ETH to a smart contract. The empty
argument triggers the fallback function of the receiving address.

(bool sent,memory data) = _to.call{value: msg.value}("");

using call, one can also trigger other functions defined in the contract and send a fixed
amount of gas to execute the function. The transaction status is sent as a boolean and
the return value is sent in the data variable.

(bool sent, bytes memory data) = _to.call{gas :10000, value:


msg.value}("func_signature(uint256 args)");

https://medium.com/coinmonks/solidity-transfer-vs-send-vs-call-function-64c92cfc878a 2/4
2/13/23, 2:19 AM Solidity — transfer vs send vs call function | by Zuhaib Mohammed | Coinmonks | Medium

call() function

Hope this article helped in understating the transfer, send and call functions.

Thanks for Reading!

Join Coinmonks Telegram Channel and Youtube


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

Grid Trading | Crypto Hardware Wallet

Crypto Telegram Signals | Crypto Trading Bot

BlockFi vs Celsius | Hodlnaut Review | KuCoin Review

Bitsgap review | Quadency Review | Bitbns Review


Open in app Get unlimited access

Crypto Copy Trading Platforms | Coinmama Review


Search Medium

Best Crypto Exchange | Best Crypto Exchange in India

Best Crypto APIs for Developers

Best Crypto Lending Platform

An ultimate guide to Leveraged Token

Solidity Web 3 Smart Contracts Ethereum Ethernaut

https://medium.com/coinmonks/solidity-transfer-vs-send-vs-call-function-64c92cfc878a 3/4
2/13/23, 2:19 AM Solidity — transfer vs send vs call function | by Zuhaib Mohammed | Coinmonks | Medium

Sign up for Coinmonks


By Coinmonks

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

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

Get this newsletter

https://medium.com/coinmonks/solidity-transfer-vs-send-vs-call-function-64c92cfc878a 4/4
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

Tom Lehman (middlemarch.eth) Follow

Oct 14, 2022 · 7 min read · Listen

Save

How to send ETH from a smart contract using


Solidity (Oct 2022)
Hint: think twice before using recipient.call{value: amount}("") .

You’re writing a smart contract that auctions off an NFT. The highest bidder gets the
NFT and all other bidders get their money back as soon as they are outbid. What’s the
best way to do this?

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 1/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

How should one refund auction bidders in the same transaction they are outbid?

Sending ETH from a contract: A deceptively tricky problem


Why? Because you must account for the case in which you’re sending ETH to another
contract, and when a contract receives ETH it can immediately execute any code it
wants.

This is quite scary when you think about it. You would never go to a random web page,
connect your wallet, and interact with an unverified smart contract you had never seen
before. And yet this is what happens whenever your contract sends ETH to a contract!

What’s the worst that can happen? Reentrancy and The DAO Hack
In 2015 an attacker stole 3.6M ETH from The DAO using what’s called a “reentrancy
attack.” Here’s an example of reentrancy-vulnerable code:

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 2/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

How to lose 3.6M ether with a reentrancy vulnerability.

The ETH is sent in the line msg.sender.call{value: amount}("") . This code sends amount

worth of ETH to msg.sender and then lets msg.sender whatever it wants.

The code works by calling a function with no name on msg.sender . Because all real
functions have names, this call will not hit any actual function, but rather trigger
msg.sender ’s “fallback function” that executes when no valid function is called. (If
msg.sender is not a contract, none of this happens and they just receive the ETH).

Reentrancy occurs when the fallback function calls withdraw() again. This causes
withdraw() to be executed from the top, which pulls the same amount out of balanceOf
and sends it to msg.sender .

The recursive aspect of reentrancy makes it a bit tricky to understand, but you can
think of it iteratively as well: reentrancy basically surrounds all code up to and
including the call() with a for loop:

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 3/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

Reentrancy visualized as a for loop

The result of course is that msg.sender can withdraw as much as it wants.

How do we prevent reentrancy?


The “easy” answer is to zero-out the attacker’s balance before we let them run arbitrary
code:

Fixing reentrancy by updating internal storage before interacting with foreign contracts

Now, the withdrawal is already marked “complete” when the attacker tries to re-
execute the withdrawal and the duplicate withdrawal fails.

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 4/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

This fix looks simple because it only requires changing one line of code. But looking at
it today we have the benefit of hindsight as well as many many Medium articles
describing how this kind of attack works.

How can we approach this problem prospectively and fix this type of vulnerability before
someone has already lost billions of dollars teaching us the easy one-line changes we
need to make?

A better approach: stop giving ETH recipients unlimited gas


Though we cannot anticipate or control what an attacker will do when they receive
ETH, we can control how much they can do by limiting the amount of gas they can use.
This is a powerful tool because reentrancy attacks require a lot of gas.

In the code above we allow recipients to use all the gas available to the sending
contract:

By default call() forwards all available gas to the callee

What if we set the gas parameter to a smaller number?

In the wake of The DAO hack a new function called transfer() was added to Solidity
that is basically the equivalent of msg.sender.call{value: amount, gas: 2_300}("") .

2,300 was thought to be the absolute minimum required to receive ETH, thus
disallowing recipients from executing an attack (or doing anything at all).

Unfortunately 2,300 is too low to do very reasonable and necessary things. And even if
it’s sufficient today, gas costs are subject to change, and so your contract might break
in the future if you rely on 2,300 gas being enough.

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 5/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

Famously this is an issue with Gnosis Safes which cannot receive ETH via transfer().

Because of this you should not use transfer() unless you are certain you are sending
ETH to an EOA. And because you can’t be certain, you should just never use it.

Forwarding all gas is bad. Limiting gas to 2,300 is bad. What do we do?
Oddly the consensus answer here is to just go back to forwarding all the gas.

OpenZeppelin, one of the most respected voices in the space and the creator of one of
the most respected Solidity libraries enshrines this belief in their library for sending
ETH via the sendValue() function:

OpenZeppelin’s Address.sendValue(). Think twice before using it!

The problem with this function and the advice in the comment is that it implies that
reentrancy vulnerabilities are the only thing to worry about when you hand over
control to the ETH recipient.

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 6/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

However, care must be taken to do more than just “not introduce reentrancy
vulnerabilities”

Gas Griefing: Why OpenZeppelin’s Address.sendValue() is risky even if your code is


reentrancy-safe
If you forward all available gas to another contract, that contract can cause you
problems by simply using all available gas and making it impossible for your contract
to do anything else. For example, it could execute this function when it receives ETH:

An attacker’s contract gas griefs you. Now *your* contract is the one with only 2,300 gas to spend!

In the auction example above, if the highest bidder makes it impossible to send them
ETH without running out of gas, it will be impossible to outbid them as outbidding
requires a successful refund to occur.

If you use Address.sendValue() in an auction contract


you will get rekt.
A path forward: gas limits + fallbacks
A better approach is to combine the wisdom of the gas limit introduced by transfer()

with a fallback that executes if the gas limit is not sufficient, instead of reverting
entirely as transfer() does.

A WETH-based fallback
Consider this code for sending ETH:

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 7/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

safeTransferETHWithFallback

If the ETH transfer fails, we pivot and send something of equal value instead: WETH.
We can even set the gas limit higher than 2,300 if we want to take on incrementally
more risk and give receivers incrementally more functionality.

However, though WETH of equal value, converting ETH to WETH incurs a cost,
particularly if the recipient has a zero WETH balance. Also, the recipient must pay
again to convert their new WETH back to ETH.

Beyond this, the receiving contract must have the functionality to withdraw the WETH
in the first place. Contract-based wallets like Gnosis Safes will be fine, but random
contracts might not be.

For this reason you should consider a higher gas limit for recipients (say 100,000).

A SELFDESTRUCT-based fallback
Ideally our fallback would still send ETH. But how can we do this if our fallback was
triggered by a failure to send ETH? Can we force a contract to accept our ETH, whether
or not its fallback function exceeds our gas limit?

It turns out we can! When you ask a contract to self destruct, you also provide an
address where that contract’s balance will be sent. When a contract sends ETH in this
https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 8/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

manner, the receiving contract’s fallback function is not triggered. They are “forced” to
accept the ETH!

Here’s how this new approach works:

1. Your contract attempts an ETH transfer via call() with a gas limit.

2. If that fails, it deploys a new contract, including the amount you want to transfer in
the call to create the contract.

3. The new contract instantly self destructs in its constructor, sending its balance to
the ETH recipient.

This fascinating approach was pioneered in the Solady Solidity library. As an added
bonus it’s written in assembly which makes it highly gas-efficient and also completely
incomprehensible (to me at least):

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 9/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

Using SELFDESTRUCT to force an ETH transfer.

There is something quite elegant about actually forcing the ETH to transfer instead of
some other substitute asset. However, there is always the chance that forcing ETH into
the contract will make it inaccessible, for example if the receiving contract needs to
update a balances mapping for withdrawals to work.

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 10/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

Deploying a new contract also costs gas, but causing it to self-destruct gives you a gas
refund. I haven’t tested this but I believe this approach nets out to cheaper than the
WETH approach.

In the end it’s a judgment call! Maybe send half via SELFDESTRUCT and half with WETH??
Just kidding! But whatever you do, think twice before using Address.sendValue() !

The end!
Do you have comments on this article? Did I make a mistake?

My Twitter DMs are open!


You can also check out some of my work at

Capsule 21!

Open in app Get unlimited access

Search Medium

Solidity Ethereum Nft

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 11/12
2/13/23, 2:24 AM How to send ETH from a smart contract using Solidity (Oct 2022) | by Tom Lehman (middlemarch.eth) | Medium

https://medium.com/@dumbnamenumbers/how-to-send-eth-from-a-smart-contract-using-solidity-oct-2022-d1225484c3ae 12/12
2/13/23, 2:26 AM How to send Ether with ethers.js. An example code to send Ether from one… | by Hideyoshi Moriya | Medium

Hideyoshi Moriya Follow

Jul 2, 2021 · 1 min read · Listen

Save

How to send Ether with ethers.js


An example code to send Ether from one wallet to another wallet with ethers.js.

In this example code, 0.01 ether is send from


0xb985d345c4bb8121cE2d18583b2a28e98D56d04b to
0xF02c1c8e6114b1Dbe8937a39260b5b0a374432bB.

// import ethers.js
const ethers = require('ethers')
// network: using the Rinkeby testnet
let network = 'rinkeby'
// provider: Infura or Etherscan will be automatically chosen
let provider = ethers.getDefaultProvider(network)
// Sender private key:
// correspondence address 0xb985d345c4bb8121cE2d18583b2a28e98D56d04b
let privateKey =
'0x49723865a8ab41e5e8081839e33dff15ab6b0125ba3acc82c25df64e8a8668f5'
// Create a wallet instance
let wallet = new ethers.Wallet(privateKey, provider)
// Receiver Address which receives Ether
let receiverAddress = '0xF02c1c8e6114b1Dbe8937a39260b5b0a374432bB'
// Ether amount to send
let amountInEther = '0.01'
// Create a transaction object
let tx = {
to: receiverAddress,
// Convert currency unit from ether to wei
https://piyopiyo.medium.com/how-to-send-ether-with-ethers-js-b1bb0b17a855 1/2
2/13/23, 2:26 AM How to send Ether with ethers.js. An example code to send Ether from one… | by Hideyoshi Moriya | Medium

value: ethers.utils.parseEther(amountInEther)
}
// Send a transaction
wallet.sendTransaction(tx)
.then((txObj) => {
console.log('txHash', txObj.hash)
// =>
0x9c172314a693b94853b49dc057cf1cb8e529f29ce0272f451eea8f5741aa9b58
// A transaction result can be checked in a etherscan with a
transaction hash which can be obtained here.
})

Actual transaction sent by the code above:


https://rinkeby.etherscan.io/tx/0x9c172314a693b94853b49dc057cf1cb8e529f29ce0272f45
1eea8f5741aa9b58

Open in app Get unlimited access


Support
If you find this article is helpful, it would be greatly appreciated if you could tip Ether
Search Medium
to the address below. Thank you!

0x0089d53F703f7E0843953D48133f74cE247184c2

Ethereum Ethersjs Blockchain Nodejs

https://piyopiyo.medium.com/how-to-send-ether-with-ethers-js-b1bb0b17a855 2/2
2/13/23, 2:28 AM How to send Ether to 11,440 people | by Nick Johnson | Medium

Nick Johnson Follow

Aug 5, 2016 · 3 min read · Listen

Save

How to send Ether to 11,440 people


If you’ve been following the updates on DAO edge cases, you’ll have heard that ether
from the extraBalance account is being sent to the users who own it not via a
withdrawal contract, but by sending it directly to them — no need for them to take any
action to claim it.

Given that the trustee wallet is a multisig, you may be wondering how this can be
achieved. Are they going to spend a week painstakingly signing 11,440 individual
transactions? Are they going to send the whole amount to an account controlled by a
single individual so they can make the payments? As it happens, neither: thanks to a
brilliant suggestion by Vitalik, it’s possible to make all the transfers trustlessly, in a
manner that requires only a single transfer by the trustees. Read on to find out how.

Transaction Signing in Ethereum


Everyone knows that to create a valid Ethereum transaction, you first have to sign it
using your private key, and that only signed transactions are valid. That’s true, but it’s
not quite the whole truth.

The process by which signatures are validated in Ethereum is called ‘ecrecover’. This is
a function that takes a message and its signature, and returns the public key (and
hence the address) that signed it. In Ethereum, the ‘from’ address of a transaction isn’t
explicitly included in a transaction; instead, ecrecover is called, and the address it
returns is the from address of the transaction. Since only the owner of that address’s

https://weka.medium.com/how-to-send-ether-to-11-440-people-187e332566b7 1/4
2/13/23, 2:28 AM How to send Ether to 11,440 people | by Nick Johnson | Medium

private key can generate signatures that return that address, only they can authorize
the network to spend funds from their account.

What if we ignored the usual signing process, though, and just filled in whatever we
liked for the transaction signature? It turns out that half of all signatures are valid in
the sense that ecrecover returns a public key (and thus an address). Since we have no
control over what address that is, what we’ve just done is to build a transaction that can
spend funds from a seemingly random address. If we create such a transaction, then
fund the generated address with some Ether, the transaction will be able to execute
just like a regular one. We’ve effectively created a “single use address”, where funds can
only be spent by one transaction. If we publish the transaction, and choose values for
the signature field in some predictable fashion, we can prove to anyone that funds sent
to that address will be usable only by that transaction, and nothing else.

Multisends with one-time addresses


The extraBalance multisend is being handled in just such a fashion. First, we generate
a series of transactions that send ether to multiple addresses — 110 of them per
transaction — and generate addresses for them using the process described above. For
the signature fields, we fill in ‘0xDA0DA0DA0…’ — a predictable value so that you can
be certain someone doesn’t actually have a private key for the generated address.

This produces a series of transactions with ‘one time addresses’ that can be used to
fund them. 104 transactions is still a few too many for the trustees to easily sign, so we
repeat the process one more time, building another transaction that sends ether to the
104 transactions we generated in the first step, producing a single transaction with its
own unique address.

https://weka.medium.com/how-to-send-ether-to-11-440-people-187e332566b7 2/4
2/13/23, 2:28 AM How to send Ether to 11,440 people | by Nick Johnson | Medium

Now, anyone can verify the transactions to satisfy themselves that they send the
correct amount of ether to the correct address list, and once satisfied, the trustees can
authorize
Open in app
a payment to the root transaction’s address. After that, anyone can submit
Get unlimited access
the transactions to the network, starting the whole process that will result in sending
ether to everyone on
Search the list — all with only a single signature required, and without
Medium
needing to trust an individual with the funds.

https://weka.medium.com/how-to-send-ether-to-11-440-people-187e332566b7 3/4
2/13/23, 2:28 AM How to send Ether to 11,440 people | by Nick Johnson | Medium

Blockchain Ethereum Ecdsa

https://weka.medium.com/how-to-send-ether-to-11-440-people-187e332566b7 4/4
2/13/23, 2:31 AM The Distinctions between Ethers.js and Web3.js | by Jordan Type | Coinmonks | Medium

Published in Coinmonks

Jordan Type Follow

Dec 2, 2022 · 4 min read · Listen

Save

The Distinctions between Ethers.js and Web3.js

Introduction

You have probably come across ethers.js, more so web3.js as a frontend blockchain
developer or still as a backend smart contract developer while testing your smart
contract. I believe these two libraries are the most important node packages that offer
different ways of interacting with your smart contract and processing transaction in an
EVM-compatible blockchain.

In this article, I will cover the differences between the two and how they interact with
the network.

Prerequisites

To get more out of this article you will need to have:

https://medium.com/coinmonks/the-distinctions-between-ethers-js-and-web3-js-8e51f60083ce#:~:text=Unlike web3.,key and can sign transactions. 1/6


2/13/23, 2:31 AM The Distinctions between Ethers.js and Web3.js | by Jordan Type | Coinmonks | Medium

1. Knowledge of JavaScript, and Node.js

2. Basic understanding of smart contracts, web3 and blockchain technology

What is a library?

A library is a packed, reusable section of code that executes a single function or a


group of closely related functions, to put it simply. So rather than writing the code
from scratch, you may add a library to your program and access it whenever you need
to implement that function.

Suppose that instead of an application, you are building a house. One of the things
you’ll need for that house is a stove, but building one from scratch when you could just
buy one off the shelf won’t be particularly practical. What a library is to a program, a
stove is to a home. There are some libraries and tools that you are already familiar
with.

What is Ethers?

Ethers.js library aims to be a complete and compact library for interacting with the
Ethereum Blockchain and its ecosystem. It was originally designed for use with
ethers.io and has since expanded into a more general-purpose library.

Features of Ethers.js

1. Keep your private keys in your client, safe and sound

2. Import and export JSON wallets (Geth, Parity and crowdsale)

https://medium.com/coinmonks/the-distinctions-between-ethers-js-and-web3-js-8e51f60083ce#:~:text=Unlike web3.,key and can sign transactions. 2/6


2/13/23, 2:31 AM The Distinctions between Ethers.js and Web3.js | by Jordan Type | Coinmonks | Medium

3. Import and export BIP 39 mnemonic phrases (12 word backup phrases) and HD
Wallets (English, Italian, Japanese, Korean, Simplified Chinese, Traditional
Chinese; more coming soon).

4. Meta-classes create JavaScript objects from any contract ABI, including ABIv2 and
Human-Readable ABI.

5. Connect to Ethereum nodes over JSON-RPC, INFURA, Etherscan, Alchemy,


Cloudflare or MetaMask.

6. ENS names are first-class citizens; they can be used anywhere an Ethereum
addresses can be used.

7. Tiny (~88kb compressed; 284kb uncompressed).

8. Complete functionality for all your Ethereum needs

9. Extensive documentation.

10. Large collection of test cases which are maintained and added to.

11. Fully TypeScript ready, with definition files and full TypeScript source.

12. MIT License (including ALL dependencies); completely open source to do with as
you please

What is Web3.js?

Web3.js is a collection of libraries that allow developers to interact with a remote or


local Ethereum node using HTTP, IPC, or WebSocket.
https://medium.com/coinmonks/the-distinctions-between-ethers-js-and-web3-js-8e51f60083ce#:~:text=Unlike web3.,key and can sign transactions. 3/6
2/13/23, 2:31 AM The Distinctions between Ethers.js and Web3.js | by Jordan Type | Coinmonks | Medium

You can create websites or clients that communicate with the blockchain using this
library. This can include, among other things, transmitting ether from one user to
another, examining data from smart contracts, and designing smart contracts.

Distinctions between Ethers.js and Web3.js


Unlike web3.js, which provides a single instantiated web3 object with methods for
interacting with the blockchain, ethers.js divides the API into two distinct roles. The
provider is an anonymous connection to the Ethereum network, while the signer has
access to the private key and can sign transactions. The ethers team intended for this
separation of concerns to give developers more flexibility.

Comparisons with examples

The following are some common functions that a developer might include in their
dapp. You’ll notice that they provide the same functionality, with minor API
differences.

Creating a provider with MetaMask wallet

web3

const web3 = new Web3(Web3.givenProvider);

ethers

const provider = new ethers.providers.Web3Provider(window.ethereum)

https://medium.com/coinmonks/the-distinctions-between-ethers-js-and-web3-js-8e51f60083ce#:~:text=Unlike web3.,key and can sign transactions. 4/6


2/13/23, 2:31 AM The Distinctions between Ethers.js and Web3.js | by Jordan Type | Coinmonks | Medium

Obtaining the account balance

web3

const balance = await web3.eth.getBalance(“0x0”)

ethers (supports ENS!)

const balance = await provider.getBalance(“ethers.eth”)

Instantiating contract
web3

const myContract = new web3.eth.Contract(ABI, contractAddress);

ethers

const myContract = new ethers.Contract(contractAddress, ABI, provider.getSigner());

Calling contract method


web3

const balance = await myContract.methods.balanceOf(“0x0”).call()

ethers

const balance = await myContract.balanceOf(“ethers.eth”)

Conclusion

In this read we have learned:

1. what is a web3.js and ethers.js library

2. How both are used to intaract with the smart contract

3. And how they are distict form each other

Links

https://medium.com/coinmonks/the-distinctions-between-ethers-js-and-web3-js-8e51f60083ce#:~:text=Unlike web3.,key and can sign transactions. 5/6


2/13/23, 2:31 AM The Distinctions between Ethers.js and Web3.js | by Jordan Type | Coinmonks | Medium

Docs: https://docs.ethers.io/v5/getting-started/

Docs: https://github.com/web3/web3.js/tree/v1.8.1

Youtube:https://www.youtube.com/watch?v=yk7nVp5HTCk

New to trading? Try crypto trading bots or copy


trading

Web 3 Ethersjs Web 3 J Blockchain Node

Open in app Get unlimited access

Sign up for Coinmonks


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.

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

Get this newsletter

https://medium.com/coinmonks/the-distinctions-between-ethers-js-and-web3-js-8e51f60083ce#:~:text=Unlike web3.,key and can sign transactions. 6/6


2/13/23, 2:34 AM How to send ether from ethers.js - Nate Lapinski - Medium

Nate Lapinski Follow

Jul 17, 2022 · 1 min read · Listen

Save

How to send ether from ethers.js

Photo by Kanchanara on Unsplash

In this quick post, I’ll show how to set msg.value when calling an arbitrary method on
a contract in ethers.js

tl;dr
https://medium.com/@natelapinski/how-to-send-ether-from-ethers-js-4e02f6fa24f2 1/2
2/13/23, 2:34 AM How to send ether from ethers.js - Nate Lapinski - Medium

Follow this pattern, assuming the contract MyContract has a payable method called
myMethod :

// ...ethersjs contract factory setup


const MyContract = new ethers.ContractFactory(
// abi and bytecode and signer vals
);
const myContract = await MyContract.deploy();
await myContract.deployed();
// calls myMethod and send along 1 ether as msg.value
await.myContract.myMethod("some random arg", {value:
ethers.utils.parseEther("1.0")});

Note that in the call to myMethod the very last argument we passed was an object
Open in app Get unlimited access
containing a value property:

Search Medium

{value: ethers.utils.parseEther("1.0")}

You can see that this optional final param is referred to as overrides in the etherjs
documentation. This can be very useful when you need to send along some ether as
part of a contract call.

Thanks for reading!

Solidity Ethereum Ethersjs Blockchain Web 3

https://medium.com/@natelapinski/how-to-send-ether-from-ethers-js-4e02f6fa24f2 2/2

You might also like