Ethers - Js Beginner To Advanced Guides
Ethers - Js Beginner To Advanced Guides
js | Coinmonks
Published in Coinmonks
Save
BLOCKCHAIN SERIES
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
Installation
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.
Credits: Author
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
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
For example, if your ABI contains a balanceOf() function, we can invoke the method as
follows:
Credits: Author
Thank You:)
Search Medium
A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.
Published in Coinmonks
Save
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.
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.
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.
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
As you can see, each of the backing types has its pros and cons. What kind of backing
do you prefer?
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.
data for the exact same dApps using Web3.js and Ethers.js. Thus, any performance
advantage remains to be confirmed.
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.
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
A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.
Search Medium
https://medium.com/coinmonks/web3-js-vs-ethers-js-fully-guide-6ce47abfe43c 11/11
2/12/23, 9:51 PM Introduction to ethers.js - Complete Guide (2022)
codedamn
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.
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.
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.
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.
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)
Sharing is caring
Did you like what Anas Khan wrote? Thank them for their work by sharing it
on social media.
Share
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)
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)
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
Save
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.
If you have already worked through the ‘Hello world voting dapp’, you can skip to Step
3.
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
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
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.
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.
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
Follow the
Voting.sol commands
hosted below to compile the contract.
with ❤ by GitHub view raw
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())
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.
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.
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.
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
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.
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
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
Save
BLOCKCHAIN SERIES
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
Installation
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.
Credits: Author
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
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
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:)
tradingSearch Medium
Ethereum Blockchain
10
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
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
Save
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:
The Github repository for this guide can be found here. If you would like to configure
Metamask, you can refer to a separate guide:
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):
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
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>
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.
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
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
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
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.
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.
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:
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:
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.
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
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
Search Medium
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 :)
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
Save
Blockchain is the solution to the real world problems and Ethers.js is one of our tool to
realize it.
1. Smart Contract
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
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 will now tweet with this address and copy the tweet link to paste it in faucet.
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
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
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.
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
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.
‘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.
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
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
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
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.
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
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] }
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
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
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.
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
Save
The Complete tutorial you can find in Tutorial Wiki → Examples → EtherJs API.
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.
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();
});
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
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
BlueSmoke Follow
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.
Infura aims to make life easier for developers. Some of the major network problems
include:
By eliminating the need for developers and companies to maintain the nodes
themselves, Infura offers certain benefits:
• Instead of keeping everything in a chain, data can be stored separately, keeping only
the hash in the blockchain.
• 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.
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
• 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.
• DApps of users.
• DApp developers.
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
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.
Save
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:
Security features like whitelisting and how to protect your project credentials;
Making requests.
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.
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
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.
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
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
As soon as any whitelist entries are added, all requests must pass each whitelist
type;
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:
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}’
{“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.
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}’
{“jsonrpc”:”2.0",”id”:1,”result”:”0x1887fd3c2b394d81a33d”}
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
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
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
Search Medium
Save
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
Save
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
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.
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
Core Techniques
Block-STM combines known techniques with novel ideas:
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
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.
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
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.
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
Save
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.
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.
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.
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.
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
Save
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.
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
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.
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.
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
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.
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 ,
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.
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 :
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
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 .
// 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:
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
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
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 .
[
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)),
]
[
"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:
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
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.
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.
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
Search Medium
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
Save
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
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.
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
{
[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:
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!
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
Search Medium
Hackernoon Newsletter curates
great stories by real tech
professionals
Get solid gold sent to your inbox. Every week!
Sign Up
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
how hackers start their afternoons. the real shit is on hackernoon.com. Take a look.
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
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Save
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 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
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 }
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:
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.
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
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 }
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.
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
Search Medium
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
Save
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!
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.
require('dotenv').config();
const API_URL = process.env.API_URL;
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3 = createAlchemyWeb3(API_URL);
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
Next we will use the web3 contract method to create our contract using the ABI and
address:
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:
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:
Congrats! You’ve just successfully read smart contract data from the Ethereum
blockchain, way to go! 🎉
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.
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
API_URL = "https://eth-ropsten.alchemyapi.io/v2/your-api-key"
PRIVATE_KEY = "your-metamask-private-key"
PUBLIC_KEY = "your-metamask-public-key"
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.
'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
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
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.
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
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):
After running node scripts/contract-interact.js you should now see the new message
printed to your console:
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
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
Save
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
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.
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.
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.
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 !!.
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.
Search Medium
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
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+
Read Discuss
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
The bitcoin network was the first to use some sor t of smar t contract by using them to
The smar t contract involved employs basic conditions like checking if the amount of
L ater, the Ethereum platform emerged which was considered more power ful,
Turing-complete language.
It is to be noted that the contracts written in the case of the bitcoin network were
There are some common smar t contract platforms like Ethereum, Solana, Polkadot,
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
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.
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,
3. Immutable : Once deployed smar t contract cannot be changed, it can only be removed
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
5. Customizable : Smar t contracts have the ability for modification or we can say
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
7. Trustless : These are not required by third par ties to verif y the integrity of the process
9. Self-enforcing : These are self-enforcing when the conditions and rules are met at all
stages.
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
Because ever ything is coded, the time taken to do all the work is the time taken for
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
intermediaries in the process. Also, the money spent on the paper work is minimal to
zero.
distribute funds as soon as all the par ties involved confirm the agreement.
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
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,
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
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.
Encr yption and blockchain technology: Encr yption provides secure authentication
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
1. Real Estate : Reduce money paid to the middleman and distribute between the
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
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
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
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
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.
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).
contractual security.
https://www.geeksforgeeks.org/smart-contracts-in-blockchain/ 6/10
2/13/23, 2:10 AM Smart Contracts in Blockchain - GeeksforGeeks
blockchain and can be accessed along with the complete audit trail. However, the
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
nodes in the network and such a violation attempt is marked invalid and not stored in
the blockchain.
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,
Plus, these agreements are immutable and therefore unbreakable and undeniable.
technology(and related technology like smar t contracts, mining, and use cases like
it ’s still a relatively new concept and research is still going on to understand the
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
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
Ar ticle Contributed By :
Parikshit Hooda
@Parikshit Hooda
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
Save
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.
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.
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.
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):
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.
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.
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.
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.
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.
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
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.
Below are the list of usecases where Blockchain & Smartcontracts can disrupt the the
industries
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
OpenLaw, Consensys
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
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
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.
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
Save
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 |…
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.
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 |…
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.
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
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 |…
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 |…
Next click on the Run tab to deploy the smart contract to the ethereum blockchain.
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.
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 |…
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>
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 |…
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
we call the get function of our smart contract to retrieve the last integer value inserted
on the blockchain via our smart contract.
add the following piece of code after the last closing braces }
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 |…
In general, an ABI is basically how you call functions in a contract and get data back
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 |…
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.
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.
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
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 |…
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>
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.
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 |…
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
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
Save
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.
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.
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.
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.
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
A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.
https://medium.com/coinmonks/solidity-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
Save
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?
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
The ETH is sent in the line msg.sender.call{value: amount}("") . This code sends amount
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
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?
In the code above we allow recipients to use all the gas available to the sending
contract:
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:
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”
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.
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!
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
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?
Capsule 21!
Search Medium
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
Save
// 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.
})
0x0089d53F703f7E0843953D48133f74cE247184c2
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
Save
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.
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.
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
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
Save
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
What is a library?
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
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.
6. ENS names are first-class citizens; they can be used anywhere an Ethereum
addresses can be used.
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?
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.
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.
web3
ethers
web3
Instantiating contract
web3
ethers
ethers
Conclusion
Links
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
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.
Save
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 :
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.
https://medium.com/@natelapinski/how-to-send-ether-from-ethers-js-4e02f6fa24f2 2/2