<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mikio Oba &#8211; Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/author/mikiooba/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com</link>
	<description></description>
	<lastBuildDate>Wed, 02 Aug 2023 09:37:53 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Mikio Oba &#8211; Be on the Right Side of Change</title>
	<link>https://blog.finxter.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Deploy a Smart Contract to Polygon in Brownie</title>
		<link>https://blog.finxter.com/how-to-deploy-smart-contract-to-polygon-in-brownie/</link>
		
		<dc:creator><![CDATA[Mikio Oba]]></dc:creator>
		<pubDate>Mon, 17 Jan 2022 13:40:08 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=141343</guid>

					<description><![CDATA[This article will look at deploying a smart contract to Polygon using Brownie.&#160; What is Polygon? Polygon is “a protocol and a framework for building and connecting Ethereum-compatible blockchain networks” (https://polygon.technology/). It started as Matic Network in 2017 to solve Ethereum’s scalability and user experience issues by using an ​off/side chain scaling solution. In 2021, ... <a title="How to Deploy a Smart Contract to Polygon in Brownie" class="read-more" href="https://blog.finxter.com/how-to-deploy-smart-contract-to-polygon-in-brownie/" aria-label="Read more about How to Deploy a Smart Contract to Polygon in Brownie">Read more</a>]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="How to Deploy a Smart Contract to Polygon in Brownie" width="937" height="527" src="https://www.youtube.com/embed/kYAeqRWjUwY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="wp-block-paragraph">This article will look at deploying a smart contract to Polygon using Brownie.&nbsp;</p>



<h2 class="wp-block-heading">What is Polygon?</h2>



<p class="wp-block-paragraph">Polygon is <em>“a protocol and a framework for building and connecting Ethereum-compatible blockchain networks”</em> (<a href="https://polygon.technology/" target="_blank" rel="noreferrer noopener"><strong>https://polygon.technology/</strong></a>). </p>



<p class="wp-block-paragraph">It started as <a rel="noreferrer noopener" href="https://github.com/maticnetwork/whitepaper" target="_blank"><strong>Matic Network</strong></a> in 2017 to solve <strong>Ethereum’s scalability</strong> and user experience issues by using an ​<strong>off/side chain scaling</strong> solution. </p>



<p class="wp-block-paragraph">In 2021, it changed the name to <strong><em>Polygon</em></strong> and now focuses on building a full-fledged blockchain platform, where developers can build scalable <a rel="noreferrer noopener" href="https://blog.finxter.com/ethereum-top-10-articles-to-get-started/" data-type="post" data-id="53284" target="_blank">Ethereum</a>-compatible blockchains. </p>



<p class="wp-block-paragraph">Its popularity has rapidly grown as more and more users experience Ethereum’s slow transaction speed and high gas fees and see Polygon as a much cheaper and faster alternative to Ethereum. <a rel="noreferrer noopener" href="https://awesomepolygon.com/" target="_blank"><strong>Many dApps</strong></a> have already been deployed to Polygon with <a rel="noreferrer noopener" href="https://app.uniswap.org/#/vote/2/10" target="_blank"><strong>Uniswap</strong></a> being one of the recent notable examples.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="1024" height="535" src="https://blog.finxter.com/wp-content/uploads/2022/01/image-19-1024x535.png" alt="Polygon Popularity Google Trends" class="wp-image-141350" srcset="https://blog.finxter.com/wp-content/uploads/2022/01/image-19-1024x535.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/01/image-19-300x157.png 300w, https://blog.finxter.com/wp-content/uploads/2022/01/image-19-768x401.png 768w, https://blog.finxter.com/wp-content/uploads/2022/01/image-19-1536x802.png 1536w, https://blog.finxter.com/wp-content/uploads/2022/01/image-19.png 1613w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure></div>



<p class="wp-block-paragraph">For more details about Polygon, you can check the <a href="https://polygon.technology/" target="_blank" rel="noreferrer noopener"><strong>Polygon website</strong></a>.</p>



<h2 class="wp-block-heading">Network Setup</h2>



<p class="wp-block-paragraph">In this article, we will connect to the <strong>Polygon testnet</strong> (Mumbai) using the API provider <a href="https://infura.io/" target="_blank" rel="noreferrer noopener"><strong>Infura</strong></a>.&nbsp;</p>



<p class="wp-block-paragraph">Connecting to Polygon is very straightforward if you already know how to connect to the Ethereum network in Brownie. If you’re not familiar with it, you might also want to check my article below:</p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" target="_blank"><strong>How to Deploy a Smart Contract on the Ropsten Testnet in Brownie</strong></a></li></ul>



<h3 class="wp-block-heading">Set up a Brownie project</h3>



<p class="wp-block-paragraph">Before setting up the network, let’s start by creating an empty Brownie project. On a terminal window, run the command <code>brownie init</code> in a new directory.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~]$ mkdir polygon_test
[~]$ cd polygon_test
[~/polygon_test]$ brownie init
Brownie v1.17.1 - Python development framework for Ethereum

SUCCESS: A new Brownie project has been initialized at /Users/mikio/polygon_test
</pre>



<h3 class="wp-block-heading">Set up Infura</h3>



<p class="wp-block-paragraph">We will use Infura to connect to the Polygon testnet. Let’s go to <a rel="noreferrer noopener" href="https://infura.io/" target="_blank"><strong>https://infura.io/</strong></a> and log on to the website. If you don’t have an account, click on the <code>SIGN UP</code> button in the top right-hand corner instead and follow the instructions to create a free account.</p>



<p class="wp-block-paragraph">After logging in, click on the <code>CREATE NEW PROJECT</code> button on the main screen.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/2XQEkazI8jPCd8t3ZdfrrGe-uxBVB6M5v4rUuJz5p-TkbE9cRbaeOPHa33brydvGHMaQQlC23FlsuN1klSZ1WKK4vH5OJDMf_hy2wNFpW8wsTwAUA9DyoxFtMy3xcVjCGExlTowp" alt=""/></figure></div>



<p class="wp-block-paragraph">Select <code>Ethereum</code> from the <code>PRODUCT</code> drop-down menu and fill in the project name (any name we like).</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/yPhi8cXVysMf01PMrHZKO4NyK0pT8X1Ce9hC5n2XZWFNDaaX0GUDokauXVGr5V2DKN4FxUnbpl7SBIauqedb_l_IY6Mu4TLRQSwxozVSJ4i4YbSvqwbxBO5FCWHQM8AlgF_-P8Gp" alt=""/></figure></div>



<p class="wp-block-paragraph">On the next page, we can find the <code>KEYS</code> section. Copy the project ID.&nbsp;</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh3.googleusercontent.com/cXFpPM8erh9eKxjWXUQJhvE0iWP7fKfJRrT9xl0maNQdzhcEs3GwIjRYTygl9n1ugCqAvzGV3VP3si6Ml4GqZS9nOhTV7HIZqZ4t0VpboeeLc5gIIOdB-9xJIiB7ANR9Qmf5ZwY8" alt=""/></figure></div>



<h3 class="wp-block-heading">Set up the environment variable in Brownie</h3>



<p class="wp-block-paragraph">Go back to the <a href="https://blog.finxter.com/brownie-smart-contracts-in-python/" data-type="post" data-id="49808" target="_blank" rel="noreferrer noopener">Brownie</a> project. Create a file called <code>.env</code> in the project root directory and add the following line (replace the project ID value with your ID):</p>



<p class="wp-block-paragraph"><code>.env</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">WEB3_INFURA_PROJECT_ID=691a20ed16eb439f8006a2b3edb45cdf</pre>



<p class="wp-block-paragraph">Create another file called <code>brownie-config.yaml</code> in the project root directory and add the following line:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dotenv: .env </pre>



<p class="wp-block-paragraph">Ensure that the <code>.gitignore</code> file contains the entry <code>.env</code> to avoid accidentally committing the <code>.env</code> file to the <a href="https://blog.finxter.com/top-cheat-sheets-for-git/" data-type="post" data-id="20843" target="_blank" rel="noreferrer noopener">Git repository</a>.&nbsp;</p>



<h3 class="wp-block-heading">Brownie network configuration</h3>



<p class="wp-block-paragraph">We can find the network settings in Brownie by running the <code>brownie networks list</code> command on the terminal.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/polygon_test]$ brownie networks list
Brownie v1.17.1 - Python development framework for Ethereum

The following networks are declared:

Ethereum
  ├─Mainnet (Infura): mainnet
  ├─Ropsten (Infura): ropsten
  ├─Rinkeby (Infura): rinkeby
  ├─Goerli (Infura): goerli
  └─Kovan (Infura): kovan

Ethereum Classic
  ├─Mainnet: etc
  └─Kotti: kotti

Arbitrum
  └─Mainnet: arbitrum-main

Binance Smart Chain
  ├─Testnet: bsc-test
  └─Mainnet: bsc-main

Fantom Opera
  ├─Testnet: ftm-test
  └─Mainnet: ftm-main

Polygon
  ├─Mainnet (Infura): polygon-main
  └─Mumbai Testnet (Infura): polygon-test

XDai
  ├─Mainnet: xdai-main
  └─Testnet: xdai-test

Development
  ├─Ganache-CLI: development
  ├─Geth Dev: geth-dev
  ├─Hardhat: hardhat
  ├─Hardhat (Mainnet Fork): hardhat-fork
  ├─Ganache-CLI (Mainnet Fork): mainnet-fork
  ├─Ganache-CLI (BSC-Mainnet Fork): bsc-main-fork
  ├─Ganache-CLI (FTM-Mainnet Fork): ftm-main-fork
  ├─Ganache-CLI (Polygon-Mainnet Fork): polygon-main-fork
  └─Ganache-CLI (XDai-Mainnet Fork): xdai-main-fork
</pre>



<p class="wp-block-paragraph">As we can see, Brownie comes with the network settings for Polygon using Infura by default.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Polygon
  ├─Mainnet (Infura): polygon-main
  └─Mumbai Testnet (Infura): polygon-test
</pre>



<p class="wp-block-paragraph">Let’s connect to the Polygon Mumbai testnet from the Brownie console. Run the <code>brownie console</code> command with the <code>--network polygon-test</code> option as shown below.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/polygon_test]$ brownie console --network polygon-test
Brownie v1.17.1 - Python development framework for Ethereum

PolygonTestProject is the active project.
Brownie environment is ready.
>>> network.is_connected()
True
>>> network.show_active()
'polygon-test'
</pre>



<p class="wp-block-paragraph">Now, the network configuration in Brownie is complete.</p>



<h2 class="wp-block-heading">How to Deploy a Smart Contract</h2>



<p class="wp-block-paragraph">To deploy a smart contract, we need an account on the network, so let’s create one.&nbsp;</p>



<h3 class="wp-block-heading">Create a Deployment Account</h3>



<p class="wp-block-paragraph">First, let’s check if there are any local accounts. Run the <code>brownie accounts list</code> command.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/polygon_test]$ brownie accounts list                     
Brownie v1.17.1 - Python development framework for Ethereum

Found 0 accounts:
</pre>



<p class="wp-block-paragraph">In this case, there is no account. Let’s create a new one called <code>deployment_account</code>. When prompted, type a new password. Be sure to remember it because we will need it later.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/polygon_test]$ brownie accounts generate deployment_account
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'xxxxx xxxx xxxx xxxxx xxxx xxxx xxxxx xxxxx xxxxxx xxxx xxxxxx xxxxxx'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0x30e4E6290941A35d6988B52451B32badE7C7CbAC' has been generated with the id 'deployment_account'</pre>



<p class="wp-block-paragraph">The hex-decimal number (<code>0x30e4E6290941A35d6988B52451B32badE7C7CbAC</code>) is the account address.&nbsp;</p>



<p class="wp-block-paragraph">We can check that the account has been created by running the <code>brownie accounts list</code> command again.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/polygon_test]$ brownie accounts list
Brownie v1.17.1 - Python development framework for Ethereum

Found 1 account:
 └─deployment_account: 0x30e4E6290941A35d6988B52451B32badE7C7CbAC
</pre>



<h3 class="wp-block-heading">Get test MATIC token from Polygon Faucet</h3>



<p class="wp-block-paragraph">We need to pay <a href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" data-type="post" data-id="37644" target="_blank" rel="noreferrer noopener">gas</a> when <a href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" data-type="post" data-id="63341" target="_blank" rel="noreferrer noopener">deploying a smart contract</a> because deployment is a transaction. While we use ether (ETH) on Ethereum, we need Polygon’s native token MATIC to pay gas on Polygon. So, let’s get some test MATIC.&nbsp;</p>



<p class="wp-block-paragraph">The easiest way to get a test token is to request some on the <a href="https://faucet.polygon.technology/" target="_blank" rel="noreferrer noopener"><strong>Polygon Faucet</strong></a> website. Select “<code>Mumbai</code>” and “<code>MATIC Token</code>” and copy and paste the account address in the Wallet Address field. </p>



<p class="wp-block-paragraph">Press the “<code>Submit</code>” button.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/1mO8TSFoAA_puXXGQcSpuWJSW7f98Bt6iz0Bq8WddsngNdoMIbFAQxEsn-Ei_6l2j6BgcTCWRIGOKxaFBsmoseUqGA5Z0edXVH-U6i4TPAe628J-7zxC-XkKdOJrHHV3C014kL6L" alt=""/></figure></div>



<p class="wp-block-paragraph">As long as the Faucet is working, we should get some MATIC after a few minutes.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/polygon_test]$ brownie console --network polygon-test
Brownie v1.17.1 - Python development framework for Ethereum

PolygonTestProject is the active project.
Brownie environment is ready.
>>> account = accounts.load('deployment_account')
Enter password for "deployment_account": 
>>> web3.fromWei(account.balance(), 'ether')
Decimal('0.5')
</pre>



<h3 class="wp-block-heading">Deploy a smart contract</h3>



<p class="wp-block-paragraph">This article will use the <code>SimpleStorage</code> smart contract, which I took from the <a href="https://docs.soliditylang.org/en/v0.8.10/introduction-to-smart-contracts.html#storage-example" target="_blank" rel="noreferrer noopener"><strong>Solidity documentation</strong></a>. </p>



<p class="wp-block-paragraph">Save the content below as <code>contracts/storage.sol</code>.</p>



<p class="wp-block-paragraph"><code><strong>contracts/storage.sol</strong></code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 &lt;0.9.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }
}
</pre>



<p class="wp-block-paragraph">Then, create a deployment script. In the <code>scripts</code> directory, create a file called <code>deploy.py</code> with the following content.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from brownie import SimpleStorage, accounts

def main():
    account = accounts.load('deployment_account')
    SimpleStorage.deploy({'from': account})</pre>



<p class="wp-block-paragraph">Now, open a terminal window and run the command <code>brownie run deploy.py --network polygon-test</code> as shown below. </p>



<p class="wp-block-paragraph">When prompted, type the account password.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/polygon_test]$ brownie run deploy.py --network polygon-test
Brownie v1.17.1 - Python development framework for Ethereum

New compatible solc version available: 0.8.10
Compiling contracts...
  Solc version: 0.8.10
  Optimizer: Enabled  Runs: 200
  EVM Version: Istanbul
Generating build data...
 - SimpleStorage

PolygonTestProject is the active project.

Running 'scripts/deploy.py::main'...
Enter password for "deployment_account": 
Transaction sent: 0x818386e241114d7c1c893416cfc154b5bb602571e8f1860305e1772c11db4d9f
  Gas price: 2.0 gwei   Gas limit: 99606   Nonce: 0
  SimpleStorage.constructor confirmed   Block: 23917582   Gas used: 90551 (90.91%)
  SimpleStorage deployed at: 0x68612eDF8f534eB752DD1Ea1aa931C7808CF75D1
</pre>



<p class="wp-block-paragraph">We can check our smart contract on <a href="https://mumbai.polygonscan.com/" target="_blank" rel="noreferrer noopener"><strong>Polygon PoS Chain Testnet Explorer</strong></a>. </p>



<p class="wp-block-paragraph">Copy our smart contract address (<code>0x68612eDF8f534eB752DD1Ea1aa931C7808CF75D1</code>&nbsp;in the example above) and paste it into the search box. </p>



<p class="wp-block-paragraph">It should find our smart contract.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/GAyo_OaLAn-dK1-bvMk92htPkJ3PSzYWNMPbQBbaLYIE_Tdmkan_nf0NWnADVcyA2SLtmlFKPBxc2a_QSMPyS67QvMmQWQkNEoWIvvzS0i0dweR9BmUpRkNNn0F9KON5pahKyFhz" alt=""/></figure></div>



<h3 class="wp-block-heading">Interact with the smart contract</h3>



<p class="wp-block-paragraph">We can interact with the smart contract using the Brownie console. </p>



<p class="wp-block-paragraph">Let’s start the console and connect to the Mumbai testnet.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/polygon_test]$ brownie console --network polygon-test      
Brownie v1.17.1 - Python development framework for Ethereum

PolygonTestProject is the active project.
Brownie environment is ready.
</pre>



<p class="wp-block-paragraph">Load the smart contract by specifying the address. We can find the address in the output of the deployment script. Alternatively, we can see the address in the JSON file name in the <code>build/deployments/80001</code> directory (<code>80001</code> is the network ID of the Polygon Mumbai testnet).&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage = SimpleStorage.at('0x68612eDF8f534eB752DD1Ea1aa931C7808CF75D1')</pre>



<p class="wp-block-paragraph">Then, we can run the function <code>get()</code>, which should return the value 0 because we haven’t set a value yet.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage.get()
0</pre>



<p class="wp-block-paragraph">To update the value, we need to send a transaction. Let’s load the <code>deployment_account</code> account. </p>



<p class="wp-block-paragraph">When prompted, type the account password.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> account = accounts.load('deployment_account')
Enter password for "deployment_account": </pre>



<p class="wp-block-paragraph">Then, run the function <code>set()</code> with the parameter value 5 and the address of <code>deployment_account</code>. It should return a transaction object after a few seconds.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage.set(5, {'from': account})
Transaction sent: 0x73cf90c4c884e13a6dea961c9fcc80bb07d52c69752992a5e4e9279f3be00a82
  Gas price: 1.999999998 gwei   Gas limit: 47843   Nonce: 1
  SimpleStorage.set confirmed   Block: 23917709   Gas used: 43494 (90.91%)

&lt;Transaction '0x73cf90c4c884e13a6dea961c9fcc80bb07d52c69752992a5e4e9279f3be00a82'></pre>



<p class="wp-block-paragraph">We can check the value by running the <code>get()</code> function again, which should now show 5.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage.get()
5</pre>



<p class="wp-block-paragraph">We can also find the transaction on <a href="https://mumbai.polygonscan.com/" target="_blank" rel="noreferrer noopener"><strong>Polygonscan (Mumbai)</strong></a> by searching the transaction hash value, which shows the input value 5.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/WXU3pruK7cy38foLfnNPOCxtuXQ2eoToC9xVuxrXUz-a6qgeuF2geZbjXX3L9YLNupkQjL7Xz5Pi2Lla0W33UatHGFXuQjrf1R8HdluQ4LopZKvADAJ1J2xH89O_EiFSQaEiTZr3" alt=""/></figure></div>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">This article looked at how to <a href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" data-type="post" data-id="63341" target="_blank" rel="noreferrer noopener">deploy a smart contract</a> to the Polygon testnet in <a href="https://blog.finxter.com/brownie-smart-contracts-in-python/" data-type="post" data-id="49808" target="_blank" rel="noreferrer noopener">Brownie</a>.&nbsp;</p>



<p class="wp-block-paragraph">The steps are the same as deploying a smart contract to <a href="https://blog.finxter.com/smart-contracts-and-evm/" data-type="post" data-id="92507" target="_blank" rel="noreferrer noopener">Ethereum</a>. Brownie already has the network settings to connect to Polygon using Infura by default, so all we need to do is to select the correct network (for example, <code>polygon-test</code>).</p>



<p class="wp-block-paragraph">Polygon is compatible with <a href="https://blog.finxter.com/smart-contracts-and-evm/" data-type="post" data-id="92507" target="_blank" rel="noreferrer noopener">Ethereum Virtual Machine</a>. </p>



<p class="wp-block-paragraph">In this article, we deployed a very simple smart contract for Ethereum to Polygon without any modification. </p>



<p class="wp-block-paragraph">We then used the Brownie console to interact with the smart contract and checked the transaction information on <a rel="noreferrer noopener" href="https://polygonscan.com/" target="_blank"><strong>Polygonscan</strong></a>.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Smart Contract Developers Make $120,000 per Year on Upwork" width="937" height="527" src="https://www.youtube.com/embed/45vaWukF564?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="wp-block-paragraph">I hope this article has been helpful to understand how to deploy a smart contract to Polygon in Brownie. You can find more in the following resources:</p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://polygon.technology/" target="_blank"><strong>Polygon website</strong></a></li><li><a rel="noreferrer noopener" href="https://eth-brownie.readthedocs.io/en/stable/deploy.html#" target="_blank"><strong>Brownie &#8211; Deployment Basics</strong></a></li><li><a href="https://blog.finxter.com/solidity/" data-type="post" data-id="37379" target="_blank" rel="noreferrer noopener"><strong>Solidity Tutorial</strong></a></li></ul>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">Learn Solidity Course</a></h2>



<p class="wp-block-paragraph">Solidity is the programming language of the future.</p>



<p class="wp-block-paragraph">It gives you the rare and sought-after superpower to program against the &#8220;Internet Computer&#8221;, i.e., against decentralized Blockchains such as <em>Ethereum</em>, <em>Binance Smart Chain</em>, <em>Ethereum Classic</em>, <em>Tron</em>, and <em>Avalanche </em>&#8211; to mention just a few Blockchain infrastructures that support Solidity.<br><br>In particular, Solidity allows you to<em> create smart contracts</em>, i.e., pieces of code that automatically execute on specific conditions in a completely decentralized environment. For example, smart contracts empower you to create your own <em>decentralized autonomous organizations</em> (DAOs) that run on Blockchains without being subject to centralized control.<br><br>NFTs, DeFi, DAOs, and Blockchain-based games are all based on smart contracts.<br><br><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">This course</a> is a simple, low-friction introduction to creating your first smart contract using the Remix IDE on the Ethereum testnet &#8211; without fluff, significant upfront costs to purchase ETH, or unnecessary complexity.</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png" alt="" class="wp-image-37299" width="491" height="287" srcset="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png 982w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-300x175.png 300w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-768x448.png 768w" sizes="auto, (max-width: 491px) 100vw, 491px" /></a></figure></div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How Do ERC-1155 Tokens Work?</title>
		<link>https://blog.finxter.com/how-do-erc-1155-tokens-work/</link>
		
		<dc:creator><![CDATA[Mikio Oba]]></dc:creator>
		<pubDate>Mon, 10 Jan 2022 15:09:06 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=128685</guid>

					<description><![CDATA[What is an ERC-1155 Token? An ERC-1155 token is a smart contract on Ethereum that implements the methods and events specified in the  EIP-1155: Multi Token Standard. As the name suggests, it is designed to represent any number of fungible and non-fungible token types in a single smart contract.  In the ERC-20 and ERC-721 standards, ... <a title="How Do ERC-1155 Tokens Work?" class="read-more" href="https://blog.finxter.com/how-do-erc-1155-tokens-work/" aria-label="Read more about How Do ERC-1155 Tokens Work?">Read more</a>]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How Do ERC-1155 Tokens Work?" width="937" height="527" src="https://www.youtube.com/embed/GGF3A7aLmgg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">What is an ERC-1155 Token?</h2>



<p class="wp-block-paragraph">An ERC-1155 token is a smart contract on Ethereum that implements the methods and events specified in the <a href="https://eips.ethereum.org/EIPS/eip-1155" target="_blank" rel="noreferrer noopener"><strong> EIP-1155: Multi Token Standard</strong></a>. As the name suggests, it is designed to represent any number of fungible and non-fungible token types in a single smart contract. </p>



<p class="wp-block-paragraph">In the ERC-20 and ERC-721 standards, a smart contract can only represent one token (ERC-20) or collection (ERC-721). So, if there is a requirement to create multiple tokens or collections, it is necessary to create multiple smart contracts, resulting in a lot of duplicates and high operation costs. The ERC-1155 tokens can solve this problem.</p>



<p class="wp-block-paragraph">This article explains the ERC-1155’s functionality by comparing it with ERC-20 and ERC-721. If you’re not familiar with them, you might find it helpful to check my previous articles below.</p>



<p class="wp-block-paragraph">ERC-20:</p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/how-does-the-erc-20-token-work/" target="_blank" rel="noreferrer noopener"><strong>How Does the ERC-20 Token Work?</strong></a></li></ul>



<p class="wp-block-paragraph">ERC-721</p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/how-do-erc-721-tokens-work/" target="_blank" rel="noreferrer noopener"><strong>How Do ERC-721 Tokens Work?</strong></a></li></ul>



<h2 class="wp-block-heading">Overview of a Basic ERC-1155 Token</h2>



<p class="wp-block-paragraph">This article will look at the ERC-1155 token implementation by <a href="https://docs.openzeppelin.com/contracts/4.x/erc1155" target="_blank" rel="noreferrer noopener"><strong>OpenZeppelin</strong></a>. We can find the Solidity code in their <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol" target="_blank" rel="noreferrer noopener"><strong>Github repository</strong></a>. In this article, we use the latest version (v4.4.1) at the time of writing. </p>



<h3 class="wp-block-heading">_balances state variable</h3>



<p class="wp-block-paragraph">The core of an ERC-1155 token is the <code>_balances</code> private variable. It is a map of a map variable, as shown below. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;</pre>



<p class="wp-block-paragraph"><em>(Line 23 &#8211; 24)</em></p>



<p class="wp-block-paragraph">This variable is like merging the <code>_owners</code> variable in ERC-721 and the <code>balances</code> variable in ERC-20. The first mapping (id to address) is the same as the <code>_owners</code> variable in ERC-721, keeping the information about which token ID is owned by which account. The second mapping (address to value) is the same as the balances variable in ERC-20, keeping which account has how many tokens. </p>



<p class="wp-block-paragraph">For example, when Alice has 100 units of the token ID 1 and Bob has 200 units of the same token, the variable would contain the following entries.</p>



<p class="wp-block-paragraph"><code><strong>_balances </strong></code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Token ID</td><td>Address</td><td>value</td></tr><tr><td>1</td><td>Alice</td><td>100</td></tr><tr><td>Bob</td><td>200</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">This token must be fungible because there is more than one same token.&nbsp;</p>



<p class="wp-block-paragraph">When Charlie has a <a href="https://blog.finxter.com/nft-101/" data-type="post" data-id="38160" target="_blank" rel="noreferrer noopener">non-fungible token</a> (ID 2), the variable would contain the following entry:</p>



<p class="wp-block-paragraph"><code><strong>_balances </strong></code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Token ID</td><td>Address</td><td>value</td></tr><tr><td>2</td><td>Charlie</td><td>1</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">When a token is non-fungible, there is always only one token by definition. Therefore, for non-fungible tokens, ERC-1155’s <code>_balances</code> variable always contains the value 1, effectively making it the same as ERC-721’s <code>_owner</code> variable.</p>



<p class="wp-block-paragraph">As we can see, this variable can hold multiple token IDs. Therefore, an ERC-1155 smart contract can represent multiple tokens (hence the name “Multi Token Standard”).</p>



<p class="wp-block-paragraph">The <code>balanceOf()</code> function looks up this variable and returns a corresponding entry for the specified token ID if it finds one.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC1155-balanceOf}.
 *
 * Requirements:
 *
 * - `account` cannot be the zero address.
 */
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
    require(account != address(0), "ERC1155: balance query for the zero address");
    return _balances[id][account];
}
</pre>



<p class="wp-block-paragraph"><em>(Line 63 &#8211; 73)</em></p>



<h3 class="wp-block-heading">Create a new token (minting)</h3>



<p class="wp-block-paragraph">The <code>_mint()</code> internal function creates (or mints) a new token. It updates the <code>_balances</code> variable so that the specified token ID’s address has the specified amount.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
 *
 * Emits a {TransferSingle} event.
 *
 * Requirements:
 *
 * - `to` cannot be the zero address.
 * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
 * acceptance magic value.
 */
function _mint(
    address to,
    uint256 id,
    uint256 amount,
    bytes memory data
) internal virtual {
    require(to != address(0), "ERC1155: mint to the zero address");

    address operator = _msgSender();

    _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);

    _balances[id][to] += amount;
    emit TransferSingle(operator, address(0), to, id, amount);

    _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 249 &#8211; 276)</em></p>



<p class="wp-block-paragraph">It is very similar to ERC-20’s <code>_mint()</code> function, although there is no totalSupply variable to keep track of the amount of the token’s total supply in ERC-1155.</p>



<p class="wp-block-paragraph">The <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol#L252" target="_blank" rel="noreferrer noopener"><code>_mint()</code><strong> function</strong></a> in ERC-20 (Line 252 &#8211; 262)</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">function _mint(address account, uint256 amount) internal virtual {
    require(account != address(0), "ERC20: mint to the zero address");

    _beforeTokenTransfer(address(0), account, amount);

    _totalSupply += amount;
    _balances[account] += amount;
    emit Transfer(address(0), account, amount);

    _afterTokenTransfer(address(0), account, amount);
}
</pre>



<h3 class="wp-block-heading"><strong>&nbsp;Transfer workflow</strong></h3>



<p class="wp-block-paragraph">Like ERC-20 and ERC-721, ERC-1155 has two workflows to transfer tokens from one address to another; one when the owner transfers tokens and the other when a third party transfers tokens. But, like ERC-721, the <code>safeTransferFrom()</code> function handles both workflows in ERC-1155.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC1155-safeTransferFrom}.
 */
function safeTransferFrom(
    address from,
    address to,
    uint256 id,
    uint256 amount,
    bytes memory data
) public virtual override {
    require(
        from == _msgSender() || isApprovedForAll(from, _msgSender()),
        "ERC1155: caller is not owner nor approved"
    );
    _safeTransferFrom(from, to, id, amount, data);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 114 &#8211; 129)</em></p>



<p class="wp-block-paragraph">The <code>safeTransferFrom()</code> function checks if any of the following conditions is true or not:</p>



<ul class="wp-block-list"><li>The <code>msg.sender</code> (who is calling this function) is the <code>from</code> account.</li><li>The <code>from</code> account has approved the <code>msg.sender</code> to transfer all their tokens.</li></ul>



<p class="wp-block-paragraph">The mechanism is very similar to ERC-721, which I looked at in the ERC-721 article below, so I will not repeat it in this article.</p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/how-do-erc-721-tokens-work/" target="_blank" rel="noreferrer noopener"><strong>How Do ERC-721 Tokens Work?</strong></a></li></ul>



<p class="wp-block-paragraph">In addition, like ERC-721, it performs the safe transfer check to ensure that the to account can receive an ERC-1155 token.</p>



<h3 class="wp-block-heading">Batch operations</h3>



<p class="wp-block-paragraph">One of the distinct features of ERC-1155 is to perform batch operations. It makes it efficient and cost-effective to check the balance of multiple tokens or transfer multiple tokens in a single transaction.</p>



<p class="wp-block-paragraph">The following is the <code>balanceOfBatch()</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC1155-balanceOfBatch}.
 *
 * Requirements:
 *
 * - `accounts` and `ids` must have the same length.
 */
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
    public
    view
    virtual
    override
    returns (uint256[] memory)
{
    require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");

    uint256[] memory batchBalances = new uint256[](accounts.length);

    for (uint256 i = 0; i &lt; accounts.length; ++i) {
        batchBalances[i] = balanceOf(accounts[i], ids[i]);
    }

    return batchBalances;
}
</pre>



<p class="wp-block-paragraph"><em>(Line 75 &#8211; 98)</em></p>



<p class="wp-block-paragraph">The function takes an array of accounts as the first parameter and another array of token IDs as the second parameter and returns an array of balances. Internally, it loops through the arrays and runs the <code>balanceOf()</code> function for each element of the arrays.</p>



<p class="wp-block-paragraph">The following is the <code>safeBatchTransferFrom()</code> function. With this function, we can transfer multiple tokens from the from account to the to account.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC1155-safeBatchTransferFrom}.
 */
function safeBatchTransferFrom(
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) public virtual override {
    require(
        from == _msgSender() || isApprovedForAll(from, _msgSender()),
        "ERC1155: transfer caller is not owner nor approved"
    );
    _safeBatchTransferFrom(from, to, ids, amounts, data);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 131 &#8211; 146)</em></p>



<p class="wp-block-paragraph">The <code>_safeBatchTransferFrom()</code> internal function loops through the array of token IDs and the amounts and performs the transfer (i.e. updates the <code>_balances</code> variable) one by one, as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
 *
 * Emits a {TransferBatch} event.
 *
 * Requirements:
 *
 * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
 * acceptance magic value.
 */
function _safeBatchTransferFrom(
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) internal virtual {
    require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
    require(to != address(0), "ERC1155: transfer to the zero address");

    address operator = _msgSender();

    _beforeTokenTransfer(operator, from, to, ids, amounts, data);

    for (uint256 i = 0; i &lt; ids.length; ++i) {
        uint256 id = ids[i];
        uint256 amount = amounts[i];

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }
        _balances[id][to] += amount;
    }

    emit TransferBatch(operator, from, to, ids, amounts);

    _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 185 &#8211; 224)</em></p>



<p class="wp-block-paragraph">The OpenZeppelin’s ERC-1155 token also implements the <code>_mintBatch()</code> and <code>_burnBatch()</code> internal functions in a similar manner, although the ERC-1155 standard does not specify them.</p>



<h2 class="wp-block-heading">ERC-1155 metadata extension</h2>



<p class="wp-block-paragraph">Like ERC-721, the ERC-1155 specification defines the optional metadata extension (ERC1155Metadata), where we can implement the <code>uri()</code> function. It takes the <code>_id</code> parameter (token ID) and returns the URI for the token. </p>



<p class="wp-block-paragraph">The specification states that if the function returns the text string <code>{id}</code> in the URI, clients must replace it with the actual token ID in hexadecimal form padded with zero to 64 hex characters length. </p>



<p class="has-base-background-color has-background wp-block-paragraph"><em>Example of such a URI: </em><code>https://token-cdn-domain/{id}.json</code><em> would be replaced with </em><code>https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json</code><em> if the client is referring to token ID </em><code>314592<em>/</em>0x4CCE0</code><em>.</em></p>



<ul class="wp-block-list"><li><a href="https://eips.ethereum.org/EIPS/eip-1155" target="_blank" rel="noreferrer noopener">https://eips.ethereum.org/EIPS/eip-1155</a></li></ul>



<p class="wp-block-paragraph">OpenZeppelin’s ERC-1155 implements it as follows:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC1155MetadataURI-uri}.
 *
 * This implementation returns the same URI for *all* token types. It relies
 * on the token type ID substitution mechanism
 * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
 *
 * Clients calling this function must replace the `\{id\}` substring with the
 * actual token type ID.
 */
function uri(uint256) public view virtual override returns (string memory) {
    return _uri;
}
</pre>



<p class="wp-block-paragraph"><em>(Line 49 &#8211; 61)</em></p>



<h2 class="wp-block-heading">ERC-1155 Token with Brownie</h2>



<p class="wp-block-paragraph">This section will create an ERC-1155 token using an example in the <a href="https://docs.openzeppelin.com/contracts/4.x/erc1155" target="_blank" rel="noreferrer noopener"><strong>OpenZeppelin documentation</strong></a> and try some functions.</p>



<h3 class="wp-block-heading">Set up the Brownie environment</h3>



<p class="wp-block-paragraph">If you haven’t installed Brownie, you can install it by following the tutorial below:</p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/brownie-smart-contracts-in-python/" target="_blank"><strong>Brownie – Smart Contracts in Python</strong></a></li></ul>



<p class="wp-block-paragraph">After installing Brownie, go to a new directory and run the brownie init command.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc1155_test]$ brownie init
Brownie v1.17.1 - Python development framework for Ethereum
SUCCESS: A new Brownie project has been initialized at /Users/mikio/erc1155_test</pre>



<p class="wp-block-paragraph">Then install the OpenZeppelin library. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc1155_test]$ brownie pm install OpenZeppelin/openzeppelin-contracts@4.4.1                  
Brownie v1.17.1 - Python development framework for Ethereum

1.71MiB [00:00, 11.2MiB/s]
New compatible solc version available: 0.8.10
Compiling contracts...
  Solc version: 0.8.10
  Optimizer: Enabled  Runs: 200
  EVM Version: Istanbul
Generating build data...
 - AccessControl
 - AccessControlEnumerable
...
...
...

SUCCESS: Package 'OpenZeppelin/openzeppelin-contracts@4.4.1' has been installed</pre>



<p class="wp-block-paragraph">Create the configuration file brownie-config.yaml in the current directory and add the following content.</p>



<p class="wp-block-paragraph"><code><strong>brownie-config.yaml</strong></code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dependencies:
  - OpenZeppelin/openzeppelin-contracts@4.4.1
compiler:
    solc:
        remappings:
          - "@openzeppelin=OpenZeppelin/openzeppelin-contracts@4.4.1"
</pre>



<h3 class="wp-block-heading">Set up accounts</h3>



<p class="wp-block-paragraph">In this example, we will use the accounts alice, bob, charlie, which we created in <a href="https://blog.finxter.com/how-does-the-erc-20-token-work/" target="_blank" rel="noreferrer noopener"><strong>my previous article</strong></a>. If you don’t have these accounts, you can create them in Brownie, as shown below. When prompted, type a password. Remember it, as we need it in the later steps.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc1155_test]$ brownie accounts generate alice
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'xxxx xxxx ...'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0x32d506BccD1367e779c53A2887070C611cC40Aa8' has been generated with the id 'alice'
[~/erc1155_test]$ brownie accounts generate bob  
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'yyyy yyyy ....'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0x80b8EFE085A0671931606eB1cF1314cf4dcc9062' has been generated with the id 'bob'
[~/erc1155_test]$ brownie accounts generate charlie
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'zzzz zzzz ....'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0xCa31275A8eF4a16cfaC4f7317aBeeDe31F73558D' has been generated with the id 'charlie'</pre>



<h3 class="wp-block-heading">Deploy smart contract</h3>



<p class="wp-block-paragraph">We use the following example for demonstration purposes, which I took from the <a href="https://docs.openzeppelin.com/contracts/4.x/erc1155" target="_blank" rel="noreferrer noopener"><strong>OpenZeppelin documentation</strong></a>. Save this file as <code>GameItems.sol</code> in the <code>contracts</code> directory.</p>



<p class="wp-block-paragraph"><code><strong>contracts/GameItems.sol</strong></code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// contracts/GameItem.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";

contract GameItems is ERC1155 {
    uint256 public constant GOLD = 0;
    uint256 public constant SILVER = 1;
    uint256 public constant THORS_HAMMER = 2;
    uint256 public constant SWORD = 3;
    uint256 public constant SHIELD = 4;

    constructor() ERC1155("https://game.example/api/item/{id}.json") {
        _mint(msg.sender, GOLD, 10**18, "");
        _mint(msg.sender, SILVER, 10**27, "");
        _mint(msg.sender, THORS_HAMMER, 1, "");
        _mint(msg.sender, SWORD, 10**9, "");
        _mint(msg.sender, SHIELD, 10**9, "");
    }
}
</pre>



<p class="wp-block-paragraph">The smart contract inherits from ERC1155 in the OpenZeppelin library.&nbsp;</p>



<p class="wp-block-paragraph">The constructor creates the following five different tokens;</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Name</td><td>ID</td><td>Amount</td></tr><tr><td>GOLD</td><td>0</td><td>10**18 (one quintillion)</td></tr><tr><td>SILVER</td><td>1</td><td>10**27 (one octillion)</td></tr><tr><td>THORS_HAMMER</td><td>2</td><td>1</td></tr><tr><td>SWORD</td><td>3</td><td>10**9 (one billion)</td></tr><tr><td>SHIELD</td><td>4</td><td>10**9 (one billion)</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">The amount of <code>THORS_HAMMER</code> is 1, which means it is a non-fungible token. The other tokens are fungible.</p>



<p class="wp-block-paragraph">Let’s deploy this <a href="https://blog.finxter.com/smart-contracts-and-evm/" data-type="post" data-id="92507" target="_blank" rel="noreferrer noopener">smart contract</a> in the local development environment to interact with it using the Brownie console. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc1155_test]$ brownie console
Brownie v1.17.1 - Python development framework for Ethereum

New compatible solc version available: 0.8.10
Compiling contracts...
  Solc version: 0.8.10
  Optimizer: Enabled  Runs: 200
  EVM Version: Istanbul
Generating build data...
 - OpenZeppelin/openzeppelin-contracts@4.4.1/ERC1155
 - OpenZeppelin/openzeppelin-contracts@4.4.1/IERC1155
 - OpenZeppelin/openzeppelin-contracts@4.4.1/IERC1155Receiver
 - OpenZeppelin/openzeppelin-contracts@4.4.1/IERC1155MetadataURI
 - OpenZeppelin/openzeppelin-contracts@4.4.1/Address
 - OpenZeppelin/openzeppelin-contracts@4.4.1/Context
 - OpenZeppelin/openzeppelin-contracts@4.4.1/ERC165
 - OpenZeppelin/openzeppelin-contracts@4.4.1/IERC165
 - GameItems

Erc1155TestProject is the active project.

Launching 'ganache-cli --accounts 10 --hardfork istanbul --gasLimit 12000000 --mnemonic brownie --port 8545'...
Brownie environment is ready.
</pre>



<p class="wp-block-paragraph">Then, load the accounts.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> alice = accounts.load('alice')
Enter password for "alice": 
>>> bob = accounts.load('bob')
Enter password for "bob": 
>>> charlie = accounts.load('charlie')
Enter password for "charlie": 
</pre>



<p class="wp-block-paragraph">Now, let’s deploy the smart contract using the <code>alice</code> account.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItems = GameItems.deploy({'from': alice})
Transaction sent: 0x22eb146fc32a1ca83ffeaf0ee5133a203b392f572933da0357ade51845597247
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0
  GameItems.constructor confirmed   Block: 1   Gas used: 1385548 (11.55%)
  GameItems deployed at: 0x37B39bE2E35caA706CF1a80b28Df9FE412008508</pre>



<h3 class="wp-block-heading">check the balances</h3>



<p class="wp-block-paragraph">Let’s check Alice’s balance of the token 1 using the <code>balanceOf()</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItems.balanceOf(alice, 1)
1000000000000000000000000000</pre>



<p class="wp-block-paragraph">We can also check multiple token’s balances using the <code>balanceOfBatch()</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItems.balanceOfBatch([alice]*5, [0, 1, 2, 3, 4])
(1000000000000000000, 1000000000000000000000000000, 1, 1000000000, 1000000000)</pre>



<h3 class="wp-block-heading">Transfer the tokens</h3>



<p class="wp-block-paragraph">We can use the <code>safeTransferFrom()</code> function to transfer the token 2 from Alice to Bob.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> tx1 = gameItems.safeTransferFrom(alice, bob, 2, 1, '', {'from': alice})
Transaction sent: 0x9044fd79b368067f78efc03848ab93e2eb728cfa8e3bbf5e589392405644ea2c
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 1
  GameItems.safeTransferFrom confirmed   Block: 2   Gas used: 39442 (0.33%)

>>> tx1.info()
Transaction was Mined 
---------------------
Tx Hash: 0x9044fd79b368067f78efc03848ab93e2eb728cfa8e3bbf5e589392405644ea2c
From: 0x8023f551705AF01849986a5Ea4625610c4946255
To: 0x37B39bE2E35caA706CF1a80b28Df9FE412008508
Value: 0
Function: GameItems.safeTransferFrom
Block: 2
Gas Used: 39442 / 12000000 (0.3%)

Events In This Transaction
--------------------------
└── GameItems (0x37B39bE2E35caA706CF1a80b28Df9FE412008508)
    └── TransferSingle
        ├── operator: 0x8023f551705AF01849986a5Ea4625610c4946255
        ├── from: 0x8023f551705AF01849986a5Ea4625610c4946255
        ├── to: 0x1271Fa44960382D26168e76ef9bd62a141f0EB38
        ├── id: 2
        └── value: 1

>>> gameItems.balanceOf(alice, 2)
0
>>> gameItems.balanceOf(bob, 2)
1
</pre>



<p class="wp-block-paragraph">We can also batch transfer multiple tokens using the <code>safeBatchTransferFrom()</code> function. The following example transfers fungible tokens (0, 1, 3) from Alice to Charlie.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItems.safeBatchTransferFrom(alice, charlie, [0, 1, 3], [50, 100, 1], '', {'from': alice})

>>> gameItems.balanceOfBatch([charlie]*3, [0, 1, 3])
(50, 100, 1)
</pre>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this article, we looked at the basic functionality of the ERC-1155 token.&nbsp;</p>



<p class="wp-block-paragraph">An ERC-1155 token is a smart contract on Ethereum that implements the methods and events specified in the <a href="https://eips.ethereum.org/EIPS/eip-1155" target="_blank" rel="noreferrer noopener"><strong> EIP-1155: Multi Token Standard</strong></a>. As the name suggests, it is designed to represent any number of fungible and non-fungible token types in a single smart contract. </p>



<p class="wp-block-paragraph">We can say that the ERC-1155 token standard is like a hybrid of the ERC-20 and ERC-721 token standards. Unique IDs identify token types, and the smart contract holds the addresses and the balances for each token.</p>



<p class="wp-block-paragraph">It specifies batch operations to make it possible to transfer multiple tokens in a single transaction efficiently and cost-effectively.&nbsp;</p>



<p class="wp-block-paragraph">I hope this overview has been helpful to understand how ERC-1155 tokens work.&nbsp;</p>



<p class="wp-block-paragraph">You can find more in the following resources.</p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://eips.ethereum.org/EIPS/eip-1155" target="_blank"><strong>EIP-1155: Multi Token Standard</strong></a></li><li><a rel="noreferrer noopener" href="https://enjin.io/erc-1155" target="_blank"><strong>ERC-1155 (enjin.io)</strong></a></li><li><a rel="noreferrer noopener" href="https://ethereum.org/en/developers/docs/standards/tokens/ERC-1155/" target="_blank"><strong>ERC-1155 NON-FUNGIBLE TOKEN STANDARD (ethereum.org)</strong></a></li><li><a rel="noreferrer noopener" href="https://docs.openzeppelin.com/contracts/4.x/api/token/erc1155" target="_blank"><strong>ERC 1155 (OpenZeppelin docs)</strong></a></li></ul>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">Learn Solidity Course</a></h2>



<p class="wp-block-paragraph">Solidity is the programming language of the future.</p>



<p class="wp-block-paragraph">It gives you the rare and sought-after superpower to program against the &#8220;Internet Computer&#8221;, i.e., against decentralized Blockchains such as <em>Ethereum</em>, <em>Binance Smart Chain</em>, <em>Ethereum Classic</em>, <em>Tron</em>, and <em>Avalanche </em>&#8211; to mention just a few Blockchain infrastructures that support Solidity.<br><br>In particular, Solidity allows you to<em> create smart contracts</em>, i.e., pieces of code that automatically execute on specific conditions in a completely decentralized environment. For example, smart contracts empower you to create your own <em>decentralized autonomous organizations</em> (DAOs) that run on Blockchains without being subject to centralized control.<br><br>NFTs, DeFi, DAOs, and Blockchain-based games are all based on smart contracts.<br><br><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">This course</a> is a simple, low-friction introduction to creating your first smart contract using the Remix IDE on the Ethereum testnet &#8211; without fluff, significant upfront costs to purchase ETH, or unnecessary complexity.</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png" alt="" class="wp-image-37299" width="491" height="287" srcset="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png 982w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-300x175.png 300w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-768x448.png 768w" sizes="auto, (max-width: 491px) 100vw, 491px" /></a></figure></div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How Do ERC-721 Tokens Work?</title>
		<link>https://blog.finxter.com/how-do-erc-721-tokens-work/</link>
		
		<dc:creator><![CDATA[Mikio Oba]]></dc:creator>
		<pubDate>Mon, 27 Dec 2021 20:26:02 +0000</pubDate>
				<category><![CDATA[Brownie]]></category>
		<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=106218</guid>

					<description><![CDATA[What is an ERC-721 Token? An ERC-721 token is a smart contract on Ethereum that implements the methods and events specified in the EIP-721: Non-Fungible Token Standard. It is designed to be used as a non-fungible token (NFT), meaning the token&#8217;s instances (or units) are distinct from one another.&#160; The ERC-721 standard is based on ... <a title="How Do ERC-721 Tokens Work?" class="read-more" href="https://blog.finxter.com/how-do-erc-721-tokens-work/" aria-label="Read more about How Do ERC-721 Tokens Work?">Read more</a>]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How Do ERC-721 Tokens Work?" width="937" height="527" src="https://www.youtube.com/embed/DGrqYoEcRiU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">What is an ERC-721 Token?</h2>



<p class="wp-block-paragraph">An ERC-721 token is a smart contract on Ethereum that implements the methods and events specified in the <a href="https://eips.ethereum.org/EIPS/eip-721" target="_blank" rel="noreferrer noopener"><strong>EIP-721: Non-Fungible Token Standard</strong></a>. It is designed to be used as a non-fungible token (NFT), meaning the token&#8217;s instances (or units) are distinct from one another.&nbsp;</p>



<p class="wp-block-paragraph">The ERC-721 standard is based on the fungible token standard (<a href="https://eips.ethereum.org/EIPS/eip-20" target="_blank" rel="noreferrer noopener"><strong>ERC-20</strong></a>), so it would make sense to explore the functionality by comparing it with ERC-20.&nbsp;</p>



<p class="wp-block-paragraph">If you’re not familiar with the ERC-20 standard, you might find it helpful to check my previous article below.</p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-does-the-erc-20-token-work/" target="_blank"><strong>How Does the ERC-20 Token Work?</strong></a></li></ul>



<p class="wp-block-paragraph">Like ERC-20 tokens, ERC-721 tokens provide the following functionality:&nbsp;</p>



<ul class="wp-block-list"><li>Transfer tokens from one account to another</li><li>Get the current token counts of an account</li><li>Approve whether a third-party account can transfer tokens&nbsp;</li></ul>



<p class="wp-block-paragraph">In addition, ERC-721 tokens provide the following functionality, which is unique to NFT:</p>



<ul class="wp-block-list"><li>Get the owner of the specific token</li></ul>



<p class="wp-block-paragraph">We’ll look at them one by one in this article.</p>



<h2 class="wp-block-heading">Overview of a Basic ERC-721 Token</h2>



<p class="wp-block-paragraph">This article will look at the ERC-721 token implementation by <a href="https://docs.openzeppelin.com/contracts/4.x/erc721" target="_blank" rel="noreferrer noopener"><strong>OpenZeppelin</strong></a>. We can find the Solidity code in their <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol" target="_blank" rel="noreferrer noopener"><strong>Github repository</strong></a>. In this article, we use the latest version (v4.4.1) at the time of writing.&nbsp;</p>



<h3 class="wp-block-heading">_owners state variable</h3>



<p class="wp-block-paragraph">The core of an ERC-721 token is the <code>_owners</code> private variable, which is a map of the token ID and its owner address.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;</pre>



<p class="wp-block-paragraph"><em>(Line 29 &#8211; 30)</em></p>



<p class="wp-block-paragraph">The ERC-721&#8217;s non-fungibility is achieved by assigning a unique identifier to each token and keeping the ID and owner information in this variable.&nbsp;</p>



<p class="wp-block-paragraph">For example, when Alice has the NFT (ID = 1) and Bob has the NFT (ID = 2), the <code>_owners</code> variable would contain the following entries.</p>



<p class="wp-block-paragraph"><code>_owners</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Token ID</td><td>Address</td></tr><tr><td>1</td><td>Alice</td></tr><tr><td>2</td><td>Bob</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">So, simply put, when we say we “own” a certain NFT, it just means that its smart contract keeps the token ID and our address in this variable. The token ID and owner address are added to this variable whenever a new NFT is created (or minted).&nbsp;</p>



<p class="wp-block-paragraph">The <code>ownerOf()</code> function looks up this variable and returns a corresponding entry if it finds one.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC721-ownerOf}.
 */
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
    address owner = _owners[tokenId];
    require(owner != address(0), "ERC721: owner query for nonexistent token");
    return owner;
}
</pre>



<p class="wp-block-paragraph"><em>(Line 67 &#8211; 74)</em></p>



<h3 class="wp-block-heading">_balances variable</h3>



<p class="wp-block-paragraph">Similar to ERC-20, ERC-721 has the <code>_balances</code> private variable that keeps track of the holdings of each account.<br></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Mapping owner address to token count
mapping(address => uint256) private _balances;
</pre>



<p class="wp-block-paragraph"><em>(Line 32 &#8211; 33)</em></p>



<p class="wp-block-paragraph">For example, when Alice and Bob have an <a href="https://blog.finxter.com/nft-101/" data-type="post" data-id="38160" target="_blank" rel="noreferrer noopener">NFT</a> each, the variable would contain the entries like below.</p>



<p class="wp-block-paragraph"><code>_balances</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Address</td><td>Token count</td></tr><tr><td>Alice</td><td>1</td></tr><tr><td>Bob</td><td>1</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">The <code>balanceOf()</code> function looks up this variable and returns a corresponding entry if it finds one.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC721-balanceOf}.
 */
function balanceOf(address owner) public view virtual override returns (uint256) {
    require(owner != address(0), "ERC721: balance query for the zero address");
    return _balances[owner];
}
</pre>



<p class="wp-block-paragraph"><em>(Line 59 &#8211; 65)</em></p>



<h3 class="wp-block-heading">Create a new token (minting)</h3>



<p class="wp-block-paragraph">The <code>_mint()</code> internal function creates (or <em>mints</em>) a new token. It updates the owner&#8217;s count in the <code>_balances</code> variable and adds the owner of the token ID in the <code>_owners</code> variable.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev Mints `tokenId` and transfers it to `to`.
 *
 * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
 *
 * Requirements:
 *
 * - `tokenId` must not exist.
 * - `to` cannot be the zero address.
 *
 * Emits a {Transfer} event.
 */
function _mint(address to, uint256 tokenId) internal virtual {
    require(to != address(0), "ERC721: mint to the zero address");
    require(!_exists(tokenId), "ERC721: token already minted");

    _beforeTokenTransfer(address(0), to, tokenId);

    _balances[to] += 1;
    _owners[tokenId] = to;

    emit Transfer(address(0), to, tokenId);

    _afterTokenTransfer(address(0), to, tokenId);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 268 &#8211; 292)</em></p>



<p class="wp-block-paragraph">For example, if Alice mints a new NFT, the <code>_owners</code> and <code>_balances</code> variables are updated, as shown below.</p>



<p class="wp-block-paragraph"><code>&nbsp;_owners</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Token ID</td><td>Address</td></tr><tr><td>1</td><td>Alice</td></tr><tr><td>2</td><td>Bob</td></tr><tr><td>3</td><td>Alice</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><code>_balances</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Address</td><td>Token count</td></tr><tr><td>Alice</td><td>2</td></tr><tr><td>Bob</td><td>1</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">There are two internal functions called <code>_safeMint()</code> (with and without <code>_data</code> parameter), which additionally verify that the new owner (the to address) can receive ERC-721 tokens.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev Safely mints `tokenId` and transfers it to `to`.
 *
 * Requirements:
 *
 * - `tokenId` must not exist.
 * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
 *
 * Emits a {Transfer} event.
 */
function _safeMint(address to, uint256 tokenId) internal virtual {
    _safeMint(to, tokenId, "");
}

/**
 * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
 * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
 */
function _safeMint(
    address to,
    uint256 tokenId,
    bytes memory _data
) internal virtual {
    _mint(to, tokenId);
    require(
        _checkOnERC721Received(address(0), to, tokenId, _data),
        "ERC721: transfer to non ERC721Receiver implementer"
    );
}
</pre>



<h3 class="wp-block-heading">Transfer workflow</h3>



<p class="wp-block-paragraph">Like ERC-20, ERC-721 has two workflows to transfer tokens from one address to another. The first workflow is used when the owner transfers tokens, and it is implemented in the _transfer() internal function, as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev Transfers `tokenId` from `from` to `to`.
 *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
 *
 * Requirements:
 *
 * - `to` cannot be the zero address.
 * - `tokenId` token must be owned by `from`.
 *
 * Emits a {Transfer} event.
 */
function _transfer(
    address from,
    address to,
    uint256 tokenId
) internal virtual {
   require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
    require(to != address(0), "ERC721: transfer to the zero address");

    _beforeTokenTransfer(from, to, tokenId);

    // Clear approvals from the previous owner
    _approve(address(0), tokenId);

    _balances[from] -= 1;
    _balances[to] += 1;
    _owners[tokenId] = to;

    emit Transfer(from, to, tokenId);

    _afterTokenTransfer(from, to, tokenId);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 320 &#8211; 351)</em></p>



<p class="wp-block-paragraph">The core part of the function is to update the <code>_owners</code> and <code>_balances</code> variables.<br></p>



<p class="wp-block-paragraph">For example, when Alice has the NFTs (ID = 1 and 3) and Bob has the NFT (ID = 2), the <code>_owners</code> and <code>_balances</code> variables contain the following entries.</p>



<p class="wp-block-paragraph"><code>_owners</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Token ID</td><td>Address</td></tr><tr><td>1</td><td>Alice</td></tr><tr><td>2</td><td>Bob</td></tr><tr><td>3</td><td>Alice</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><code>_balances</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Address</td><td>Token count</td></tr><tr><td>Alice</td><td>2</td></tr><tr><td>Bob</td><td>1</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Then, when Alice transfers the NFT (ID 3) to Charlie, the address value for Token ID 3 is updated from Alice to Charlie in the <code>_owners</code> variable. Their counts are also updated in the <code>_balances</code> variable accordingly.</p>



<p class="wp-block-paragraph"><code>_owners</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Token ID</td><td>Address</td></tr><tr><td>1</td><td>Alice</td></tr><tr><td>2</td><td>Bob</td></tr><tr><td>3</td><td>Charlie</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><code>_balances</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Address</td><td>Token count</td></tr><tr><td>Alice</td><td>1</td></tr><tr><td>Bob</td><td>1</td></tr><tr><td>Charlie</td><td>1</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Although this function performs the actual transfer operations, it is not exposed to the users because it is internal. The <code>transferFrom()</code> function (and its variants) is used for the transfer workflow instead, which we will explore in the next section.&nbsp;</p>



<h3 class="wp-block-heading">TransferFrom workflow</h3>



<p class="wp-block-paragraph">The second workflow to transfer tokens is used when a third party transfers tokens using the <code>transferFrom()</code> function on behalf of the owner.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC721-transferFrom}.
 */
function transferFrom(
    address from,
    address to,
    uint256 tokenId
) public virtual override {
    //solhint-disable-next-line max-line-length
    require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");

    _transfer(from, to, tokenId);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 147 &#8211; 159)</em></p>



<p class="wp-block-paragraph">The difference is that the <code>transferFrom()</code> function also calls the <code>_isApprovedOrOwner()</code> internal function, which is implemented as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev Returns whether `spender` is allowed to manage `tokenId`.
 *
 * Requirements:
 *
 * - `tokenId` must exist.
 */
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
    require(_exists(tokenId), "ERC721: operator query for nonexistent token");
    address owner = ERC721.ownerOf(tokenId);
    return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
</pre>



<p class="wp-block-paragraph"><em>(Line 225 &#8211; 236)</em></p>



<p class="wp-block-paragraph">In other words, the <code>transferFrom()</code> function is checking if any of the following conditions is true or not:</p>



<ul class="wp-block-list"><li>The <code>msg.sender</code> (who is calling this function) is the owner.</li><li>The <code>msg.sender</code> has been approved to transfer the token on behalf of the owner.</li><li>The owner has approved the <code>msg.sender</code> to transfer all their tokens.</li></ul>



<p class="wp-block-paragraph">The first condition is true when the owner calls the <code>transferFrom()</code> function. It means that we can use the <code>transferFrom()</code> function in the transfer workflow we looked at in the previous section.<br></p>



<p class="wp-block-paragraph">The <code>getApproved()</code> function is used in the second condition, which simply looks up the <code>_tokenApprovals</code> private variable.<br></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC721-getApproved}.
 */
function getApproved(uint256 tokenId) public view virtual override returns (address) {
    require(_exists(tokenId), "ERC721: approved query for nonexistent token");

    return _tokenApprovals[tokenId];
}
</pre>



<p class="wp-block-paragraph"><em>(Line 124 &#8211; 131)</em></p>



<p class="wp-block-paragraph">The <code>_tokenApprovals</code> variable is a map of a token ID and an address.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;</pre>



<p class="wp-block-paragraph"><em>(Line 35 &#8211; 36)</em></p>



<p class="wp-block-paragraph">It is updated by the <code>approve()</code> function via the <code>_approve()</code> internal function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC721-approve}.
 */
function approve(address to, uint256 tokenId) public virtual override {
    address owner = ERC721.ownerOf(tokenId);
    require(to != owner, "ERC721: approval to current owner");

    require(
        _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
        "ERC721: approve caller is not owner nor approved for all"
    );

    _approve(to, tokenId);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 109 &#8211; 122)</em></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev Approve `to` to operate on `tokenId`
 *
 * Emits a {Approval} event.
 */
function _approve(address to, uint256 tokenId) internal virtual {
    _tokenApprovals[tokenId] = to;
    emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 353 &#8211; 361)</em></p>



<p class="wp-block-paragraph">So, the owner needs to call the <code>approve()</code> function first for the second condition to be true. It will add the spender address and the token ID to the the <code>_tokenApprovals</code> variable, so the <code>_isApprovedOrOwner()</code> internal function will return true.&nbsp;</p>



<p class="wp-block-paragraph">In the third condition, the <code>isApprovedForAll()</code> function checks if the owner has given <code>msg.sender</code> a blanket approval to send their tokens.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC721-isApprovedForAll}.
 */
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
    return _operatorApprovals[owner][operator];
}
</pre>



<p class="wp-block-paragraph"><em>(Line 140 &#8211; 145)</em></p>



<p class="wp-block-paragraph">It looks up the <code>_operatorApprovals</code> private variable, a map of maps.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
</pre>



<p class="wp-block-paragraph">It is updated by the <code>setApprovalForAll()</code> function via the <code>_setApprovalForAll()</code> internal function.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC721-setApprovalForAll}.
 */
function setApprovalForAll(address operator, bool approved) public virtual override {
    _setApprovalForAll(_msgSender(), operator, approved);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 133 &#8211; 138)</em></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev Approve `operator` to operate on all of `owner` tokens
 *
 * Emits a {ApprovalForAll} event.
 */
function _setApprovalForAll(
    address owner,
    address operator,
    bool approved
) internal virtual {
    require(owner != operator, "ERC721: approve to caller");
    _operatorApprovals[owner][operator] = approved;
    emit ApprovalForAll(owner, operator, approved);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 363 &#8211; 376)</em></p>



<p class="wp-block-paragraph">So, for the third condition to be true, the owner would need to call the <code>setApprovalForAll()</code> function to give the <code>msg.sender</code> approval in advance.</p>



<p class="wp-block-paragraph">If any of these three conditions is true, the <code>transferFrom()</code> function calls the <code>_transfer()</code> internal function, and it performs the transfer, as explained in the previous section.</p>



<h3 class="wp-block-heading">Safe Transfer</h3>



<p class="wp-block-paragraph">In addition to the <code>transferFrom()</code> function, the <code>safeTransferFrom()</code> functions (there are two variations, with and without the <code>_data</code> parameter) are available. They perform extra checks to see if the recipient can receive ERC-721 tokens or not, via the <code>_safeTransfer()</code> internal function.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @dev See {IERC721-safeTransferFrom}.
 */
function safeTransferFrom(
    address from,
    address to,
    uint256 tokenId
) public virtual override {
    safeTransferFrom(from, to, tokenId, "");
}

/**
 * @dev See {IERC721-safeTransferFrom}.
 */
function safeTransferFrom(
    address from,
    address to,
    uint256 tokenId,
    bytes memory _data
) public virtual override {
    require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
    _safeTransfer(from, to, tokenId, _data);
}
</pre>



<p class="wp-block-paragraph"><em>(Line 161 &#8211; 183)</em></p>



<h2 class="wp-block-heading">ERC-721 Metadata Extension</h2>



<p class="wp-block-paragraph">So far, we’ve looked at the basic functionality of ERC-721, but the token&#8217;s non-fungibility is only manifested in the token IDs. Although we can see that each token is unique by looking at the ID, its use case is very limited in the real world if unique data is only the IDs.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">The ERC-721 specification defines the optional metadata extension (<strong>ERC721Metadata</strong>), where we can implement the <code>tokenURI()</code> function to give each token a unique URI (Uniform Resource Identifier). A typical form of URI is URL (such as an HTTP address). </p>



<p class="wp-block-paragraph">Another popular form of URI for NFT is the content identifier (CID) in the <a href="https://ipfs.io/" target="_blank" rel="noreferrer noopener"><strong>IPFS</strong></a> network because we cannot modify the data without changing the CID. We will not go into details about IPFS, but you can read more in the <a href="https://docs.ipfs.io/how-to/mint-nfts-with-ipfs/" target="_blank" rel="noreferrer noopener"><strong>IPFS documentation</strong></a>. </p>



<p class="wp-block-paragraph">The OpenZeppelin library includes the <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/extensions/ERC721URIStorage.sol" target="_blank" rel="noreferrer noopener">ERC721URIStorage<strong> extension</strong></a>, which provides a basic implementation of the <code>tokenURI()</code> function. In real-world use cases, each project will need to override this function depending on the requirements for the NFT.</p>



<h2 class="wp-block-heading">ERC-721 Token with Brownie</h2>



<p class="wp-block-paragraph">This section will create an ERC-721 token using an example in the <a href="https://docs.openzeppelin.com/contracts/4.x/erc721" target="_blank" rel="noreferrer noopener"><strong>OpenZeppelin documentation</strong></a> and try some functions.</p>



<h3 class="wp-block-heading">&nbsp;Set up the Brownie environment</h3>



<p class="wp-block-paragraph">If you haven’t installed Brownie, you can install it by following the tutorial below:</p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/brownie-smart-contracts-in-python/" target="_blank" rel="noreferrer noopener"><strong>Brownie – Smart Contracts in Python</strong></a></li></ul>



<p class="wp-block-paragraph">After installing Brownie, go to a new directory and run the <code>brownie init</code> command.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc721_test]$ brownie init
Brownie v1.17.1 - Python development framework for Ethereum

SUCCESS: A new Brownie project has been initialized at /Users/mikio/erc721_test
</pre>



<p class="wp-block-paragraph">Then install the OpenZeppelin library. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc721_test]$ brownie pm install OpenZeppelin/openzeppelin-contracts@4.4.1                  
Brownie v1.17.1 - Python development framework for Ethereum

1.71MiB [00:00, 11.2MiB/s]
New compatible solc version available: 0.8.10
Compiling contracts...
  Solc version: 0.8.10
  Optimizer: Enabled  Runs: 200
  EVM Version: Istanbul
Generating build data...
 - AccessControl
 - AccessControlEnumerable
...
...
...

SUCCESS: Package 'OpenZeppelin/openzeppelin-contracts@4.4.1' has been installed</pre>



<p class="wp-block-paragraph">Create the configuration file <code>brownie-config.yaml</code> in the current directory and add the following content.</p>



<p class="wp-block-paragraph"><code>brownie-config.yaml</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dependencies:
  - OpenZeppelin/openzeppelin-contracts@4.4.1
compiler:
    solc:
        remappings:
          - "@openzeppelin=OpenZeppelin/openzeppelin-contracts@4.4.1"
</pre>



<h3 class="wp-block-heading">Set up accounts</h3>



<p class="wp-block-paragraph">In this example, we will use the accounts alice, bob, charlie, which we created in <a href="https://blog.finxter.com/how-does-the-erc-20-token-work/" target="_blank" rel="noreferrer noopener"><strong>my previous article</strong></a>. If you don’t have these accounts, you can create them in Brownie, as shown below. When prompted, type a password. Remember it, as we need it in the later steps.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc721_test]$ brownie accounts generate alice
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'xxxx xxxx ...'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0x32d506BccD1367e779c53A2887070C611cC40Aa8' has been generated with the id 'alice'
[~/erc721_test]$ brownie accounts generate bob  
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'yyyy yyyy ....'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0x80b8EFE085A0671931606eB1cF1314cf4dcc9062' has been generated with the id 'bob'
[~/erc721_test]$ brownie accounts generate charlie
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'zzzz zzzz ....'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0xCa31275A8eF4a16cfaC4f7317aBeeDe31F73558D' has been generated with the id 'charlie'
</pre>



<h3 class="wp-block-heading">Deploy smart contract</h3>



<p class="wp-block-paragraph">We use the following example for demonstration purposes, which I took from the <a href="https://docs.openzeppelin.com/contracts/4.x/erc721" target="_blank" rel="noreferrer noopener"><strong>OpenZeppelin documentation</strong></a> and slightly modified it. Save this file as <code>GameItem.sol</code> in the contracts directory.</p>



<p class="wp-block-paragraph"><code>contracts/GameItem.sol</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// contracts/GameItem.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

contract GameItem is ERC721URIStorage {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;

    constructor() ERC721("GameItem", "ITM") {}

    function awardItem(address player, string memory tokenURI)
        public
        returns (uint256)
    {
        _tokenIds.increment();

        uint256 newItemId = _tokenIds.current();
        _mint(player, newItemId);
        _setTokenURI(newItemId, tokenURI);

        return newItemId;
    }

}
</pre>



<p class="wp-block-paragraph">The smart contract inherits from <code>ERC721URIStorage</code>, which again inherits from <code>ERC721</code>. Both of them are provided in the OpenZeppelin library. </p>



<p class="wp-block-paragraph">The <code>awardItem()</code> function creates a new NFT. It generates a token ID, creates a new token using the <code>_mint()</code> function with the token ID, and sets the specified URI to the token metadata using the <code>_setTokenURI()</code> function. In this example, anyone can call this function and mint a new NFT.</p>



<p class="wp-block-paragraph">Let’s deploy this smart contract in the local development environment to interact with it using the Brownie console. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc721_test]$ brownie console
Brownie v1.17.1 - Python development framework for Ethereum

New compatible solc version available: 0.8.10
Compiling contracts...
  Solc version: 0.8.10
  Optimizer: Enabled  Runs: 200
  EVM Version: Istanbul
Generating build data...
 - OpenZeppelin/openzeppelin-contracts@4.4.1/ERC721
 - OpenZeppelin/openzeppelin-contracts@4.4.1/IERC721
 - OpenZeppelin/openzeppelin-contracts@4.4.1/IERC721Receiver
 - OpenZeppelin/openzeppelin-contracts@4.4.1/ERC721URIStorage
 - OpenZeppelin/openzeppelin-contracts@4.4.1/IERC721Metadata
 - OpenZeppelin/openzeppelin-contracts@4.4.1/Address
 - OpenZeppelin/openzeppelin-contracts@4.4.1/Context
 - OpenZeppelin/openzeppelin-contracts@4.4.1/Counters
 - OpenZeppelin/openzeppelin-contracts@4.4.1/Strings
 - OpenZeppelin/openzeppelin-contracts@4.4.1/ERC165
 - OpenZeppelin/openzeppelin-contracts@4.4.1/IERC165
 - GameItem

Erc721TestProject is the active project.

Launching 'ganache-cli --accounts 10 --hardfork istanbul --gasLimit 12000000 --mnemonic brownie --port 8545'...
Brownie environment is ready.
>>> </pre>



<p class="wp-block-paragraph">Then, load the accounts.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> alice = accounts.load('alice')
Enter password for "alice": 
>>> bob = accounts.load('bob')
Enter password for "bob": 
>>> charlie = accounts.load('charlie')
Enter password for "charlie": </pre>



<p class="wp-block-paragraph">Now, let’s deploy the smart contract using the alice account.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItem = GameItem.deploy({'from': alice})
Transaction sent: 0xc973d95cd3ee93fccbab0536778a450252c82932653e595a32af4b2d532829df
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0
  GameItem.constructor confirmed   Block: 1   Gas used: 1367483 (11.40%)
  GameItem deployed at: 0xa0433E13f093739643D7d8bb632f5fa87942ae24</pre>



<h3 class="wp-block-heading">Create NFTs</h3>



<p class="wp-block-paragraph">Let’s create a new NFT and award it to Alice. The URI is just a random URL in this example.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> tx1 = gameItem.awardItem(alice, 'http://example.com/item1.json')
Transaction sent: 0x44db1ab578dfc8cea532a06a1d0408c028e5a34788337622aa68c06ca3188da6
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 1
  GameItem.awardItem confirmed   Block: 2   Gas used: 111734 (0.93%)</pre>



<p class="wp-block-paragraph">The token ID is 1 in the transaction details. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> tx1.info()
Transaction was Mined 
---------------------
Tx Hash: 0x44db1ab578dfc8cea532a06a1d0408c028e5a34788337622aa68c06ca3188da6
From: 0x32d506BccD1367e779c53A2887070C611cC40Aa8
To: 0xa0433E13f093739643D7d8bb632f5fa87942ae24
Value: 0
Function: GameItem.awardItem
Block: 2
Gas Used: 111734 / 12000000 (0.9%)

Events In This Transaction
--------------------------
└── GameItem (0xa0433E13f093739643D7d8bb632f5fa87942ae24)
    └── Transfer
        ├── from: 0x0000000000000000000000000000000000000000
        ├── to: 0x32d506BccD1367e779c53A2887070C611cC40Aa8
        └── tokenId: 1
</pre>



<p class="wp-block-paragraph">Now, we can run the <code>ownerOf()</code> function to verify that Alice is indeed the owner of the token 1. We can also run the <code>balanceOf()</code> function to check that Alice owns one token.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItem.ownerOf(1) == alice
True
>>> gameItem.balanceOf(alice)
1
</pre>



<p class="wp-block-paragraph">We can also run the <code>tokenURI()</code> function to find the token URI. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItem.tokenURI(1)
'http://example.com/item1.json'
</pre>



<p class="wp-block-paragraph">We can repeat the same process and award a new item to Bob.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> tx2 = gameItem.awardItem(bob, 'http://example.com/item2.json')
Transaction sent: 0xafb89196d99b50f265490f1ae077959488da8de369c6dec303a901e76b7e84f0
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 2
  GameItem.awardItem confirmed   Block: 3   Gas used: 96734 (0.81%)

>>> tx2.info()
Transaction was Mined 
---------------------
Tx Hash: 0xafb89196d99b50f265490f1ae077959488da8de369c6dec303a901e76b7e84f0
From: 0x32d506BccD1367e779c53A2887070C611cC40Aa8
To: 0xa0433E13f093739643D7d8bb632f5fa87942ae24
Value: 0
Function: GameItem.awardItem
Block: 3
Gas Used: 96734 / 12000000 (0.8%)

Events In This Transaction
--------------------------
└── GameItem (0xa0433E13f093739643D7d8bb632f5fa87942ae24)
    └── Transfer
        ├── from: 0x0000000000000000000000000000000000000000
        ├── to: 0x80b8EFE085A0671931606eB1cF1314cf4dcc9062
        └── tokenId: 2

>>> gameItem.ownerOf(2) == bob
True
>>> gameItem.balanceOf(bob)
1
>>> gameItem.tokenURI(2)
'http://example.com/item2.json'
</pre>



<h3 class="wp-block-heading">Transfer an NFT</h3>



<p class="wp-block-paragraph">We can use the <code>transferFrom()</code> function to transfer an NFT.</p>



<p class="wp-block-paragraph">Firstly, let’s check that Alice can transfer the NFT 1 to Charlie.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> tx3 = gameItem.transferFrom(alice, charlie, 1, {'from': alice})
Transaction sent: 0x4b2977d149f81867351457ff0ed7afcf701134e5eab7dbf2e9a4246fde2dff1b
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 3
  GameItem.transferFrom confirmed   Block: 4   Gas used: 49948 (0.42%)

>>> tx3.info()
Transaction was Mined 
---------------------
Tx Hash: 0x4b2977d149f81867351457ff0ed7afcf701134e5eab7dbf2e9a4246fde2dff1b
From: 0x32d506BccD1367e779c53A2887070C611cC40Aa8
To: 0xa0433E13f093739643D7d8bb632f5fa87942ae24
Value: 0
Function: GameItem.transferFrom
Block: 4
Gas Used: 49948 / 12000000 (0.4%)

Events In This Transaction
--------------------------
└── GameItem (0xa0433E13f093739643D7d8bb632f5fa87942ae24)
    ├── Approval
    │   ├── owner: 0x32d506BccD1367e779c53A2887070C611cC40Aa8
    │   ├── approved: 0x0000000000000000000000000000000000000000
    │   └── tokenId: 1
    └── Transfer
        ├── from: 0x32d506BccD1367e779c53A2887070C611cC40Aa8
        ├── to: 0xCa31275A8eF4a16cfaC4f7317aBeeDe31F73558D
        └── tokenId: 1
</pre>



<p class="wp-block-paragraph">We can see two events, <code>Approval</code> and <code>Transfer</code>. The first event comes from the <code>_approve()</code> internal function and the second comes from the <code>_transfer(</code>) internal function.</p>



<p class="wp-block-paragraph">Now, we can confirm that the token 1 owner is Charlie, not Alice.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItem.ownerOf(1) == alice
False
>>> gameItem.ownerOf(1) == charlie
True
</pre>



<p class="wp-block-paragraph">Next, let’s see if Alice can transfer Bob’s token to Charlie.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItem.transferFrom(bob, charlie, 2, {'from': alice})
Transaction sent: 0x26b0f19314c9962970580cf20e0e79059b2e70654676212ea3e2057ebef66f32
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 4
  GameItem.transferFrom confirmed (ERC721: transfer caller is not owner nor approved)   Block: 5   Gas used: 27476 (0.23%)

&lt;Transaction '0x26b0f19314c9962970580cf20e0e79059b2e70654676212ea3e2057ebef66f32'>
</pre>



<p class="wp-block-paragraph">This call fails (<code>"transfer caller is not the owner nor approved"</code>). It is correct because Alice is not the owner of the token 2, and Bob hasn’t approved Alice.</p>



<p class="wp-block-paragraph">Assuming that Bob is happy for Alice to transfer his token, he runs the <code>approve()</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItem.approve(alice, 2, {'from': bob})
Transaction sent: 0xd1dbaf920fa26b0af79055e5ed4f68ba5a8a55dac1cdece7f61c86c627238089
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0
  GameItem.approve confirmed   Block: 6   Gas used: 46822 (0.39%)

&lt;Transaction '0xd1dbaf920fa26b0af79055e5ed4f68ba5a8a55dac1cdece7f61c86c627238089'></pre>



<p class="wp-block-paragraph">Alternatively, Bob can run the <code>setApprovalForAll()</code> function if he wants to give Alice his approval to transfer all his tokens.</p>



<p class="wp-block-paragraph">Either way, Alice can now transfer Bob’s token 2 to Charlie.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItem.transferFrom(bob, charlie, 2, {'from': alice})
Transaction sent: 0xcace7e5b7f6317861046e6b2c2e84c2376fac9f36b10e552545f60337f76ab1c
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 5
  GameItem.transferFrom confirmed   Block: 7   Gas used: 28026 (0.23%)

&lt;Transaction '0xcace7e5b7f6317861046e6b2c2e84c2376fac9f36b10e552545f60337f76ab1c'>
</pre>



<p class="wp-block-paragraph">Now, we can see that Charlie is the token 2 owner.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> gameItem.ownerOf(2) == charlie
True
</pre>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this article, we looked at the basic functionality of the ERC-721 token.&nbsp;</p>



<p class="wp-block-paragraph">An ERC-721 token is a smart contract on Ethereum that implements the methods and events specified in the <a href="https://eips.ethereum.org/EIPS/eip-721" target="_blank" rel="noreferrer noopener"><strong>EIP-721: Non-Fungible Token Standard</strong></a>. It is designed to be used as a non-fungible token (NFT), meaning the token&#8217;s instances (or units) are distinct from one another. </p>



<p class="wp-block-paragraph">The non-fungibility is achieved by assigning a unique identifier to each token, and then, the ID and owner are kept in a map variable.</p>



<p class="wp-block-paragraph">The ERC-721 standard defines the functionality of the ERC-721 token, such as creating and transferring tokens. It also specifies the optional functionality, such as the metadata extension, where we can implement a function to give each token a unique URI (Uniform Resource Identifier). This part will vary significantly depending on the requirements for the NFT project.</p>



<p class="wp-block-paragraph">I hope this overview has been helpful to understand how ERC-721 tokens work.&nbsp;</p>



<p class="wp-block-paragraph">You can find more in the following resources.</p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://eips.ethereum.org/EIPS/eip-721" target="_blank"><strong>EIP-721: Non-Fungible Token Standard</strong></a></li><li><a rel="noreferrer noopener" href="https://ethereum.org/en/developers/docs/standards/tokens/erc-721/" target="_blank"><strong>ERC-721 NON-FUNGIBLE TOKEN STANDARD (ethereum.org)</strong></a></li><li><a rel="noreferrer noopener" href="https://docs.openzeppelin.com/contracts/4.x/api/token/erc721" target="_blank"><strong>ERC 721 (OpenZeppelin docs)</strong></a></li><li><a rel="noreferrer noopener" href="https://docs.ipfs.io/how-to/mint-nfts-with-ipfs/#a-short-introduction-to-nfts" target="_blank"><strong>Mint an NFT with IPFS (IPFS docs)</strong></a></li></ul>






<h2 class="wp-block-heading"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">Learn Solidity Course</a></h2>



<p class="wp-block-paragraph">Solidity is the programming language of the future.</p>



<p class="wp-block-paragraph">It gives you the rare and sought-after superpower to program against the &#8220;Internet Computer&#8221;, i.e., against decentralized Blockchains such as <em>Ethereum</em>, <em>Binance Smart Chain</em>, <em>Ethereum Classic</em>, <em>Tron</em>, and <em>Avalanche </em>&#8211; to mention just a few Blockchain infrastructures that support Solidity.<br><br>In particular, Solidity allows you to<em> create smart contracts</em>, i.e., pieces of code that automatically execute on specific conditions in a completely decentralized environment. For example, smart contracts empower you to create your own <em>decentralized autonomous organizations</em> (DAOs) that run on Blockchains without being subject to centralized control.<br><br>NFTs, DeFi, DAOs, and Blockchain-based games are all based on smart contracts.<br><br><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">This course</a> is a simple, low-friction introduction to creating your first smart contract using the Remix IDE on the Ethereum testnet &#8211; without fluff, significant upfront costs to purchase ETH, or unnecessary complexity.</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png" alt="" class="wp-image-37299" width="491" height="287" srcset="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png 982w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-300x175.png 300w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-768x448.png 768w" sizes="auto, (max-width: 491px) 100vw, 491px" /></a></figure></div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How Does the ERC-20 Token Work?</title>
		<link>https://blog.finxter.com/how-does-the-erc-20-token-work/</link>
		
		<dc:creator><![CDATA[Mikio Oba]]></dc:creator>
		<pubDate>Wed, 15 Dec 2021 08:21:36 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=87294</guid>

					<description><![CDATA[What is an ERC-20 token? An ERC-20 token is a smart contract on Ethereum that implements the methods and events specified in the ERC-20 standard. It is designed to be used as a fungible token, meaning each instance (or unit) of a token has the same value as another instance of the same token. It ... <a title="How Does the ERC-20 Token Work?" class="read-more" href="https://blog.finxter.com/how-does-the-erc-20-token-work/" aria-label="Read more about How Does the ERC-20 Token Work?">Read more</a>]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How Does the ERC-20 Token Work?" width="937" height="527" src="https://www.youtube.com/embed/CyxFtHBLhbk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">What is an ERC-20 token?</h2>



<p class="wp-block-paragraph">An ERC-20 token is a smart contract on <a rel="noreferrer noopener" href="https://blog.finxter.com/ethereum-top-10-articles-to-get-started/" data-type="post" data-id="53284" target="_blank">Ethereum</a> that implements the methods and events specified in the <a rel="noreferrer noopener" href="https://eips.ethereum.org/EIPS/eip-20" target="_blank"><strong>ERC-20 standard</strong></a>. It is designed to be used as a fungible token, meaning each instance (or unit) of a token has the same value as another instance of the same token. It provides the following functionalities (<a rel="noreferrer noopener" href="https://ethereum.org/en/developers/docs/standards/tokens/erc-20/#body" target="_blank"><strong>ethereum.org</strong></a>):&nbsp;</p>



<ul class="wp-block-list"><li>transfer tokens from one account to another</li><li>get the current token balance of an account</li><li>get the total supply of the token available on the network</li><li>approve whether an amount of token from an account can be spent by a third-party account&nbsp;</li></ul>



<p class="wp-block-paragraph">Since it was proposed in November 2015, the popularity of ERC-20 tokens has exploded and, at the time of writing, <a href="https://etherscan.io/tokens" target="_blank" rel="noreferrer noopener"><strong>Token Tracker</strong></a> on etherscan.io claims that it finds nearly half a million ERC-20 tokens. It is not surprising because creating an ERC-20 token is very easy. But first, let’s look at the ERC-20 specification.&nbsp;</p>



<h2 class="wp-block-heading">Overview of a basic ERC-20 token</h2>



<p class="wp-block-paragraph">It is easy to understand the functionality by looking at a concrete example. Brownie has a mix called <a href="https://github.com/brownie-mix/token-mix" target="_blank" rel="noreferrer noopener"><strong>Token Mix</strong></a>, so let’s use it as an example. We can find the smart contract file <code><a href="https://github.com/brownie-mix/token-mix/blob/master/contracts/Token.sol" target="_blank" rel="noreferrer noopener">Token.sol</a></code> on the Github repository, which implements the basic requirements for an ERC-20 token. Later in this article, we will install it on the local machine and try some functions on the local blockchain.</p>



<h3 class="wp-block-heading">balances state variable</h3>



<p class="wp-block-paragraph">The main part of an ERC-20 token is the balances state variable. It has a map data structure (like a Python dictionary) containing addresses and their respective holdings of the ERC-20 token. In other words, it keeps track of who has how much amount of the token.</p>



<p class="wp-block-paragraph">For example, when Alice has 10 units of the token and Bob has 5 units, the balances variable contains the following entries.</p>



<p class="wp-block-paragraph"><code>balances</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Address</strong></td><td><strong>Value</strong></td></tr><tr><td>Alice</td><td>10</td></tr><tr><td>Bob</td><td>5</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">When Alice sends 5 units to Bob, the <code>balances</code> variable is updated.</p>



<p class="wp-block-paragraph"><code>balances</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Address</strong></td><td><strong>Value</strong></td></tr><tr><td>Alice</td><td>5</td></tr><tr><td>Bob</td><td>10</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">So, simply put, when we say we “own” a certain amount of an ERC-20 token, it just means our addresses and the corresponding amount are stored in the balances variable in the specific smart contract. Our accounts do not actually “own” anything.&nbsp;</p>



<p class="wp-block-paragraph">This mechanism is fundamentally different from the ether (ETH). When an Ethereum account has ether, the amount is stored in the balance field of the account. On the other hand, ERC-20 tokens are not stored in the account, and only the address and the record about the holdings are stored in the token’s smart contract.</p>



<h3 class="wp-block-heading">transfer() workflow</h3>



<p class="wp-block-paragraph">Another essential thing to note is two workflows that transfer tokens from one account to another. One is when the spender directly transfers the token to another address, and the other is when a third party transfers the token on behalf of the spender.&nbsp;</p>



<p class="wp-block-paragraph">The first workflow is straightforward. The sender directly calls the function <code>transfer()</code> with the receiver address and the amount to send as parameters. For example, Alice can execute <code>transfer(Bob, 5)</code> to send 5 units of her token to Bob. The function updates the balances state variable to reduce Alice’s balance by 5 units and increase Bob’s balance by the same amount, as we saw earlier.</p>



<h3 class="wp-block-heading">transferFrom() workflow</h3>



<p class="wp-block-paragraph">The function <code>transferFrom()</code> is used in the second workflow. In this case, the address that calls the function is not the same as the sender. To prevent unauthorized transfers, the sender first executes the <code>approve()</code> function to allow the third party address to send a specific amount of token on its behalf. It updates the <code>allowed</code> state variable with the information about who approved whom to spend how much.&nbsp;</p>



<p class="wp-block-paragraph">For example, let’s say Alice wants Charlie to send 5 units of the token to Bob on her behalf. Before Charlie can make the transfer, Alice executes <code>approve(Charlie, 5)</code> first. The function adds the following entry to the <code>allowed</code> state variable.</p>



<p class="wp-block-paragraph"><code>allowed</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Owner address</strong></td><td><strong>Spender address</strong></td><td><strong>Value</strong></td></tr><tr><td>Alice</td><td>Charlie</td><td>5</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">It shows that Charlie can transfer up to 5 units of the token from Alice’s balance.&nbsp;</p>



<p class="wp-block-paragraph">Now, Charlie can execute <code>transferFrom(Alice, Bob, 5)</code>. First, the function reduces Charlie’s allowance by 5 units in the <code>allowed</code> variable.</p>



<p class="wp-block-paragraph"><code>allowed</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Owner address</strong></td><td><strong>Spender address</strong></td><td><strong>Value</strong></td></tr><tr><td>Alice</td><td>Charlie</td><td>0</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Then, it updates the Alice’s and Bob’s values in the <code>balances</code> variable, as we saw in the <code>transfer()</code> workflow, which completes the transfer.</p>



<p class="wp-block-paragraph">The third-party address can be an externally owned account (= human), but more often, it is a smart contract address, such as an exchange, to delegate certain operations to a system.</p>



<h2 class="wp-block-heading">ERC-20 token with Brownie</h2>



<p class="wp-block-paragraph">This section will create an ERC-20 token using Brownie <a href="https://github.com/brownie-mix/token-mix" target="_blank" rel="noreferrer noopener"><strong>Token Mix</strong></a> and try its functionality on the Brownie console.</p>



<h3 class="wp-block-heading">Install Brownie Token Mix</h3>



<p class="wp-block-paragraph">If you haven’t installed Brownie, you can install it by following the tutorial below:</p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/brownie-smart-contracts-in-python/" target="_blank"><strong>Brownie – Smart Contracts in Python</strong></a></li></ul>



<p class="wp-block-paragraph">After <a href="https://eth-brownie.readthedocs.io/en/stable/install.html" target="_blank" rel="noreferrer noopener"><strong>installing Brownie</strong></a>, go to a new directory and run the <code>brownie bake token</code> command.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc20_test]$ brownie bake token
Brownie v1.17.1 - Python development framework for Ethereum

Downloading from https://github.com/brownie-mix/token-mix/archive/master.zip...
9.13kiB [00:00, 4.57MiB/s]
SUCCESS: Brownie mix 'token' has been initiated at /Users/mikio/erc20_test/token
</pre>



<p class="wp-block-paragraph">You can find the ERC-20 smart contract file (<code>Token.sol</code>) in the token/contracts directory.</p>



<h3 class="wp-block-heading">Set up accounts</h3>



<p class="wp-block-paragraph">In this example, we will use the accounts <code>alice</code>, <code>bob</code>, <code>charlie</code>, which we can create in Brownie as shown below. When prompted, type a password. Remember it, as we need it in the later steps.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc20_test/token]$ brownie accounts generate alice
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'xxxx xxxx ...'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0xf56B3FEC97cCc891999a1F8D4BfF30455C89594F' has been generated with the id 'alice'
[~/erc20_test/token]$ brownie accounts generate bob  
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'yyyy yyyy ....'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0x9fecB3A269327fEf1c03636Bca82Ec8B6C875121' has been generated with the id 'bob'
[~/erc20_test/token]$ brownie accounts generate charlie
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'zzzz zzzz ....'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0x86Aa12E566Ebecb6C8a4b887A375c1b46f015326' has been generated with the id 'charlie'</pre>



<h3 class="wp-block-heading">Import accounts into MetaMask</h3>



<p class="wp-block-paragraph">We can optionally import the accounts into MetaMask. This step is not necessary to understand ERC-20 tokens, but I’ve included it just for demonstrations purposes.&nbsp;</p>



<p class="wp-block-paragraph">If you have not installed MetaMask, you can find the tutorial on Finxter below.&nbsp;</p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/metamask-simple-tutorial/"><strong>MetaMask Simple Tutorial</strong></a>&nbsp;</li></ul>



<p class="wp-block-paragraph">Firstly, we need to export accounts into keystore files. On the terminal, run the following commands, which exports the keystone files in the current directory.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc20_test/token]$ brownie accounts export alice ./alice.json
Brownie v1.17.1 - Python development framework for Ethereum

SUCCESS: Account with id 'alice' has been exported to keystore '/Users/mikio/erc20_test/token/alice.json'
[~/erc20_test/token]$ brownie accounts export bob ./bob.json
Brownie v1.17.1 - Python development framework for Ethereum

SUCCESS: Account with id 'bob' has been exported to keystore '/Users/mikio/erc20_test/token/bob.json'
[~/erc20_test/token]$ brownie accounts export charlie ./charlie.json
Brownie v1.17.1 - Python development framework for Ethereum

SUCCESS: Account with id 'charlie' has been exported to keystore '/Users/mikio/erc20_test/token/charlie.json'</pre>



<p class="wp-block-paragraph">Log on to MetaMask, click on the account icon in the top-right corner and select “Import Account”</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/ca-EZstCai7vm0IaatTf-fXuhW4psfi2anvxxt_E_gRlzOdELG4vginWaztaq4SXPjhyh776-sL9nH9MnneE8Q9fruSDkPmNJNMhOilMVlRTwn_Mf0w5AASP54bjEtrJnc-yoyHT" alt=""/></figure></div>



<p class="wp-block-paragraph">Select “JSON File” from the drop-down menu as Select Type and upload the file exported in the previous step. Type the password and click “Import”.&nbsp;</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh3.googleusercontent.com/eenQ88EVL8Rq5BM9yengUOX3mtm1AaWxh82dVOOC-u2Ckoyi0XwAupdqeJ9G1Vh0N1M9LID5y7oGUcFeqEB34_Ci5RgUo86KVFxHRbaJBxH-uW-JZAWe0R7omfJQoX1g8Csi6UhK" alt=""/></figure></div>



<p class="wp-block-paragraph">The account will appear on the list after a few minutes. Click on the three dots next to the account name and select “Account details”.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/0m_3PauwiS78enArie2UMr-obKK-AsfQvcviPHdyc6PI0YEum-N9m0no4LvXM0lisYVpm4jAWZAkhLwj5t_jKl6Ou2T3UGCKFAvqNHwXx-17Gdwb8nWi3-3q2m_Y1nufSE9fHMLw" alt=""/></figure></div>



<p class="wp-block-paragraph">Then click on the pencil icon next to the account name to change the account name (e.g. Alice)</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/H3oosBDfNuRafFv8TJcMuxS-yH-u7oug6sM6MWushLSsl1upzwST2-8FY5olJwvmoShMrJK46FOrmIIfMcBldJhl-4okZXU_c_eGxglSeRaa9EuB_nV5vU-6ZkVXeTVuCh59C96V" alt=""/></figure></div>



<p class="wp-block-paragraph">Repeat the same steps for the other two accounts (Bob and Charlie).</p>



<h3 class="wp-block-heading">Deploy smart contract</h3>



<p class="wp-block-paragraph">To create an ERC-20 token, we need to decide the following attributes.&nbsp;</p>



<ul class="wp-block-list"><li><strong>Name</strong>: the name of the token</li><li><strong>Symbol</strong>: the symbol of the token</li><li><strong>Total supply</strong>: the total token supply</li><li><strong>Decimals</strong>: the number of decimals the token uses&nbsp;</li></ul>



<p class="wp-block-paragraph">We will create “Miko Token” for this example, as shown below.</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Name</strong></td><td><strong>Symbol</strong></td><td><strong>Total Supply</strong></td><td><strong>Decimals</strong></td></tr><tr><td>Mikio Token</td><td>MIK</td><td>100000</td><td>2</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">The attribute <code>Decimals</code> is set to 2. It means that the amount of token is divided by 100 (=<em>10**2</em>) to get its representation, similar to representing 100 cents as 1 USD. As the total supply equals 100,000, the maximum amount of Mikio Token is 1000.00 MIK (= <em>totalSupply / decimals = 100000 / 10**2</em>). Note that this is just an example, and it can be a different value, such as 18, which is the same value as ether (<em>1 ether = 10**18 wei</em>).</p>



<p class="wp-block-paragraph">Now we can deploy the smart contract. First, start the Brownie console using the local blockchain.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc20_test/token]$ brownie console
Brownie v1.17.1 - Python development framework for Ethereum

Compiling contracts...
  Solc version: 0.6.12
  Optimiser: Enabled  Runs: 200
  EVM Version: Istanbul
Generating build data...
 - SafeMath
 - Token

TokenProject is the active project.

Launching 'ganache-cli --accounts 10 --hardfork istanbul --gasLimit 12000000 --mnemonic brownie --port 8545'...
Brownie environment is ready.
>>>
</pre>



<p class="wp-block-paragraph">Load the accounts. Type the password for each account when prompted.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> alice = accounts.load('alice')
Enter password for "alice": 
>>> bob = accounts.load('bob')
Enter password for "bob": 
>>> charlie = accounts.load('charlie')
Enter password for "charlie": </pre>



<p class="wp-block-paragraph">Brownie console automatically loads the Token contract object. We can deploy it to the network by running the <code>deploy()</code> method with the abovementioned details as the arguments. The deployment account is specified in the from field. Let’s use the account alice to deploy the smart contract.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> token = Token.deploy('Mikio Token', 'MIK', 2, 100000, {'from': alice})
Transaction sent: 0xd63d04a68f4bc6e16ef58003bf9cca7bfa6b480bab3d7911fabcc7cf33e3d302
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0
  Token.constructor confirmed   Block: 1   Gas used: 516339 (4.30%)
  Token deployed at: 0xe5D97d3F9bfDb9B5981DA4b89c72cCcABe25cbd7
</pre>



<p class="wp-block-paragraph">The total supply is automatically transferred to the deployment account when the smart contract is created, as we can see in the constructor() function. We can confirm it by checking Alice’s balance.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> token.balanceOf(alice)
100000
</pre>



<p class="wp-block-paragraph">This value means 100,000 cents or 1,000 MIK, as explained above. We can also confirm that Bob and Charlie don’t have any MIK tokens.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> token.balanceOf(bob)
0
>>> token.balanceOf(charlie)
0
</pre>



<p class="wp-block-paragraph">The smart contract&#8217;s balances state variable would contain the following entry.</p>



<p class="wp-block-paragraph">balances</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Address</strong></td><td><strong>Value</strong></td></tr><tr><td>Alice</td><td>100000</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">Import Token into MetaMask</h3>



<p class="wp-block-paragraph">We can see the balances on MetaMask as well. MetaMask knows nothing about “Mikio Token” yet, so let’s import it.</p>



<p class="wp-block-paragraph">Log on to MetaMask and select Alice&#8217;s account. Make sure to choose the network “Localhost 8545”. Then, click the link “Import tokens” at the bottom.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/lShlzjmbtLHijWEl7nCwS8rrmZGLDbGeIS2VhG_ynt9XfzFurOJzROJNOgZfaZIQTFCwOwREsJhKxxDjVaXLZS-in_Z0MJIUBAHoymnCIFHJyVY_tngxG91Mm15Wq8EBNXnpRDFA" alt=""/></figure></div>



<p class="wp-block-paragraph">Then, copy the token address from the deploy command output on the console in the previous step and paste it to the <strong>Token Contract Address</strong> field. The other fields (<strong>Token Symbol</strong> and <strong>Token Decimal</strong>) will be automatically filled. Click the <strong>Add Custom Token</strong> button.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/ut4L6KDfCXQ0FvwgL7xADhuotyDI4vRB8odGceeLWr9xQ9rRvUijy1QQDVx--LafQTrZGKRB0e-PGBg393jYP3azRjs-HzwR7MTc7-VjOiJC4ZRZP1g8jHOLxbq_tNA5hYAsNHAF" alt=""/></figure></div>



<p class="wp-block-paragraph">On the next screen, click on the <strong>Import Tokens</strong> button.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh3.googleusercontent.com/zg3XJQ5Lp-mpnQO2_t8TduQ3dX7W4kchYTgCcCUaAiZQOkw95aB90TWYi8zMTKxPjZQXW5tgCISUhFJ2cCygVzMGE88IVmLJy7zvYgHpwnP5PEQPCgySOuVzgSNvB1uNgnqIVygV" alt=""/></figure></div>



<p class="wp-block-paragraph">Go back to Alice account’s main page, and we can now see that Alice has 1000 MIK.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/MmrVR-KQitWfONXcI3dAxKCyI-bdm74RXtqKtESkRThNEYFd64M_Vk7-fLbLdbJnnOUTYJ9VsYOftEH2CJ2kcVt-ceb62QSNlmqw1R10dd5zJwc9TQt_bp_atz1CgNzrEyVySS8H" alt=""/></figure></div>



<p class="wp-block-paragraph">Repeat the same steps for Bob and Charlie. We can see that they don’t have any MIK tokens yet.</p>



<h3 class="wp-block-heading">Transfer workflow</h3>



<p class="wp-block-paragraph">Let’s say Alice has decided to transfer 100 MIK to Bob. We can simulate it by running the <code>transfer()</code> command with Alice in the from field.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> token.transfer(bob, 10000, {'from': alice})
Transaction sent: 0xe7c4fc8ef260a1a4cca696e0cde73eba4e9b792136f661cf05ec18bc7c24b810
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 1
  Token.transfer confirmed   Block: 2   Gas used: 51608 (0.43%)

&lt;Transaction '0xe7c4fc8ef260a1a4cca696e0cde73eba4e9b792136f661cf05ec18bc7c24b810'>
</pre>



<p class="wp-block-paragraph">We can check the balance of Alice and Bob as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> token.balanceOf(alice)
90000
>>> token.balanceOf(bob)
10000
</pre>



<p class="wp-block-paragraph">On MetaMask, we can also see that Alice has 900 MIK and Bob has 100 MIK.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh3.googleusercontent.com/d6SVKC9PaNXA8aL0SI4yVKpl_fCRHEiuEi5-Ef98lzDEH45i_cX0autHXoaJNOOksLWMOBKn6XV5oNNZ85Vi5YE0AejbVLM5Fp1UZToQa9LsXyYW7Rf-oDBPllFFcYMwRdfRcP6K" alt=""/></figure></div>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/LwpVYtbUz83PzwKPPB6gxigOBHEEytlbv8TfwYlXPiPinnLdMXOmeBtKQq7F0B_S4vBuKjxzZJfgSqfIyivVu5xPYIabXdkOYn0Gw-YhTP0kvRN06MIjAGsLCQUoQ4FXT4LWA4XE" alt=""/></figure></div>



<p class="wp-block-paragraph">In the smart contract, the <code>balances</code> state variable would contain the following entries.</p>



<p class="wp-block-paragraph"><code>balances</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Address</strong></td><td><strong>Value</strong></td></tr><tr><td>Alice</td><td>90000</td></tr><tr><td>Bob</td><td>10000</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">TransferFrom workflow</h3>



<p class="wp-block-paragraph">Alice can delegate transfer operations to Charlie. Charlie can be an externally owned account (human user) or a smart contract address, such as an exchange. Let’s see how it works.</p>



<p class="wp-block-paragraph">First, Alice needs to execute the <code>approve()</code> function to grant the allowance for Charlie, as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> token.approve(charlie, 10000, {'from': alice})
Transaction sent: 0xb045165c372ba1f53145933f866bd9f67b434c4be166f410d5cdef12c3b2e56b
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 2
  Token.approve confirmed   Block: 3   Gas used: 43683 (0.36%)

&lt;Transaction '0xb045165c372ba1f53145933f866bd9f67b434c4be166f410d5cdef12c3b2e56b'></pre>



<p class="wp-block-paragraph">The smart contract&#8217;s <code>allowed</code>&nbsp;state variable would now contain the following entry.</p>



<p class="wp-block-paragraph"><code>allowed</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Owner address</strong></td><td><strong>Spender address</strong></td><td><strong>Value</strong></td></tr><tr><td>Alice</td><td>Charlie</td><td>10000</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Now, Charlie can transfer up to 100 MIK from Alice’s balance, as shown below. Note that the <code>from</code> field is Charlie because Charlie is now executing the function.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> token.transferFrom(alice, bob, 10000, {'from': charlie})
Transaction sent: 0x8eab4ad0560073187a0c9e346f901bc313134195b2577b206d01fb038b3d0f37
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0
  Token.transferFrom confirmed   Block: 4   Gas used: 29180 (0.24%)

&lt;Transaction '0x8eab4ad0560073187a0c9e346f901bc313134195b2577b206d01fb038b3d0f37'>
</pre>



<p class="wp-block-paragraph">We can check Alice’s and Bob’s balances.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> token.balanceOf(alice)
80000
>>> token.balanceOf(bob)
20000
</pre>



<p class="wp-block-paragraph">We can also check the balances on MetaMask.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/O_3fm-6oehxycO0plD8tc2bgmL2yV1fJYUeG3Gj4vGY_jaxWdJqaBEjyVgIDIrEYTOL7CbMOprlj1sJsnBXV2WmPkjvzCEJ-PzKagBypn3yjgiSF-xkGfvgOmU6fuWgVj1PGd700" alt=""/></figure></div>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/XFzGe4Ka8Givkiancw179jH6Go2vyhN3BNUF5arLop5-uAWEb1vqz_DDnmx_E7_-4_Yv7mI-IhPYRFcnuCa5JHp1jcxI6rKOhwMX8LfbEcIFhqyyklf_qVcRoU3HcMpYUF54D74p" alt=""/></figure></div>



<p class="wp-block-paragraph">In the smart contract, the state variables would contain the following entries.</p>



<p class="wp-block-paragraph"><code>balances</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Address</strong></td><td><strong>Value</strong></td></tr><tr><td>Alice</td><td>80000</td></tr><tr><td>Bob</td><td>20000</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><code>allowed</code></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Owner address</strong></td><td><strong>Spender address</strong></td><td><strong>Value</strong></td></tr><tr><td>Alice</td><td>Charlie</td><td>0</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">Run unit test</h3>



<p class="wp-block-paragraph">Brownie Token Mix comes with the following test files in the <code>tests</code> directory.&nbsp;</p>



<ul class="wp-block-list"><li><code><a href="https://github.com/brownie-mix/token-mix/blob/master/tests/test_approve.py" target="_blank" rel="noreferrer noopener">tests/test_approve.py</a></code></li><li><code><a href="https://github.com/brownie-mix/token-mix/blob/master/tests/test_transfer.py" target="_blank" rel="noreferrer noopener">tests/test_transfer.py</a></code></li><li><code><a href="https://github.com/brownie-mix/token-mix/blob/master/tests/test_transferFrom.py" target="_blank" rel="noreferrer noopener">tests/test_transferFrom.py</a></code></li></ul>



<p class="wp-block-paragraph">They are useful because we can see how the <code>transfer()</code>, <code>transferFrom()</code> and <code>approve()</code> functions should work, especially in edge cases.&nbsp;</p>



<p class="wp-block-paragraph">To run the tests for Mikio Token, we first need to update the token <code>pytest fixture</code> in line 15 in the file <code><a href="https://github.com/brownie-mix/token-mix/blob/master/tests/conftest.py" target="_blank" rel="noreferrer noopener">tests/conftest.py</a></code>, as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@pytest.fixture(scope="module")
def token(Token, accounts):
    return Token.deploy("Mikio Token", "MIK", 2, 100000, {'from': accounts[0]})
</pre>



<p class="wp-block-paragraph">Then, we can run the brownie test command from the terminal.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/erc20_test/token]$ brownie test
Brownie v1.17.1 - Python development framework for Ethereum

========================================================== test session starts ===========================================================
platform darwin -- Python 3.9.1, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: /Users/mikio/erc20_test/token
plugins: eth-brownie-1.17.1, web3-5.24.0, hypothesis-6.24.0, xdist-1.34.0, forked-1.3.0
collected 38 items                                                                                                                       

Launching 'ganache-cli --accounts 10 --hardfork istanbul --gasLimit 12000000 --mnemonic brownie --port 8545'...

tests/test_approve.py ............                                                                                                 [ 31%]
tests/test_transfer.py .........                                                                                                   [ 55%]
tests/test_transferFrom.py .................                                                                                       [100%]

========================================================== 38 passed in 10.42s ===========================================================
Terminating local RPC client...</pre>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this article, we looked at the basic functionality of an ERC-20 token by implementing a token using Brownie Token Mix.&nbsp;</p>



<p class="wp-block-paragraph">An ERC-20 token is a smart contract on Ethereum that implements the methods and events specified in the <a href="https://eips.ethereum.org/EIPS/eip-20" target="_blank" rel="noreferrer noopener"><strong>ERC-20 standard</strong></a>. It is designed to be used as a fungible token, meaning each unit has the same value as another unit of the same token.</p>



<p class="wp-block-paragraph">The main part of an ERC-20 token is the balances state variable, and it has a map data structure containing addresses and their respective holdings of the ERC-20 token. Unlike ether, ERC-20 token balances are stored not in accounts but this state variable in the smart contract.</p>



<p class="wp-block-paragraph">There are two workflows to transfer tokens. The spender can execute the <code>transfer()</code> function to transfer tokens to another address directly. Alternatively, the spender can delegate transfer operations to a third party. In this case, the spender needs to execute the <code>approve()</code> function to grant the allowance for the third party. Then, the third party can run the <code>transferFrom()</code> function to make the transfer on behalf of the spender.&nbsp;</p>



<p class="wp-block-paragraph">I hope this overview has been helpful to understand how ERC-20 tokens work.&nbsp;</p>



<p class="wp-block-paragraph">You can find more in the following resources.</p>



<ul class="wp-block-list"><li><a href="https://eips.ethereum.org/EIPS/eip-20" target="_blank" rel="noreferrer noopener"><strong>EIP-20: Token Standard</strong></a></li><li><a href="https://ethereum.org/en/developers/docs/standards/tokens/erc-20/" target="_blank" rel="noreferrer noopener"><strong>ERC-20 TOKEN STANDARD</strong></a></li><li><a href="https://etherscan.io/tokens" target="_blank" rel="noreferrer noopener"><strong>Etherscan Token Tracker</strong></a></li><li><a href="https://github.com/brownie-mix/token-mix" target="_blank" rel="noreferrer noopener"><strong>Brownie Token Mix</strong></a></li><li><a href="https://github.com/ethereumbook/ethereumbook/blob/develop/10tokens.asciidoc" target="_blank" rel="noreferrer noopener"><strong>Mastering Ethereum &#8211; Tokens</strong></a></li></ul>






<h2 class="wp-block-heading"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">Learn Solidity Course</a></h2>



<p class="wp-block-paragraph">Solidity is the programming language of the future.</p>



<p class="wp-block-paragraph">It gives you the rare and sought-after superpower to program against the &#8220;Internet Computer&#8221;, i.e., against decentralized Blockchains such as <em>Ethereum</em>, <em>Binance Smart Chain</em>, <em>Ethereum Classic</em>, <em>Tron</em>, and <em>Avalanche </em>&#8211; to mention just a few Blockchain infrastructures that support Solidity.<br><br>In particular, Solidity allows you to<em> create smart contracts</em>, i.e., pieces of code that automatically execute on specific conditions in a completely decentralized environment. For example, smart contracts empower you to create your own <em>decentralized autonomous organizations</em> (DAOs) that run on Blockchains without being subject to centralized control.<br><br>NFTs, DeFi, DAOs, and Blockchain-based games are all based on smart contracts.<br><br><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">This course</a> is a simple, low-friction introduction to creating your first smart contract using the Remix IDE on the Ethereum testnet &#8211; without fluff, significant upfront costs to purchase ETH, or unnecessary complexity.</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png" alt="" class="wp-image-37299" width="491" height="287" srcset="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png 982w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-300x175.png 300w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-768x448.png 768w" sizes="auto, (max-width: 491px) 100vw, 491px" /></a></figure></div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Create Web Frontend using Brownie react-mix</title>
		<link>https://blog.finxter.com/create-web-frontend-using-brownie-react-mix/</link>
		
		<dc:creator><![CDATA[Mikio Oba]]></dc:creator>
		<pubDate>Tue, 07 Dec 2021 14:01:46 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[React]]></category>
		<category><![CDATA[Smart Contracts]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=74174</guid>

					<description><![CDATA[In this article, we continue exploring the functionality of Brownie, a smart contract development and testing framework for Solidity and Vyper. We created a simple smart contract in the previous tutorials and deployed it to the Ropsten testnet. Please check the following articles if you haven’t done so. Brownie – Smart Contracts in Python How ... <a title="Create Web Frontend using Brownie react-mix" class="read-more" href="https://blog.finxter.com/create-web-frontend-using-brownie-react-mix/" aria-label="Read more about Create Web Frontend using Brownie react-mix">Read more</a>]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Smart Contract - Create Web Frontend using Python Brownie react-mix" width="937" height="527" src="https://www.youtube.com/embed/zVJStyepjhw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="wp-block-paragraph">In this article, we continue exploring the functionality of <a href="https://eth-brownie.readthedocs.io/en/stable/" target="_blank" rel="noreferrer noopener">Brownie</a>, a smart contract development and testing framework for <a href="https://blog.finxter.com/solidity/" data-type="post" data-id="37379" target="_blank" rel="noreferrer noopener">Solidity</a> and Vyper. We created a simple smart contract in the previous tutorials and deployed it to the <strong>Ropsten testnet</strong>. Please check the following articles if you haven’t done so.</p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/brownie-smart-contracts-in-python/" target="_blank" rel="noreferrer noopener"><strong>Brownie – Smart Contracts in Python</strong></a></li><li><a href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" target="_blank" rel="noreferrer noopener"><strong>How to Deploy a Smart Contract on the Ropsten Testnet in Brownie</strong></a></li></ul>



<p class="wp-block-paragraph">Our smart contract is now on the testnet, but we only used it on the Brownie console. It would be helpful if we had a front-end web application to interact with it even if we don’t have Brownie on our computer. Brownie has a template system called <a rel="noreferrer noopener" href="https://github.com/brownie-mix" target="_blank"><strong>Brownie Mixes</strong></a>, which we can use as a starting point for specific types of smart contract projects. There is a mix called <a rel="noreferrer noopener" href="https://github.com/brownie-mix/react-mix" target="_blank"><strong>react-mix</strong></a>, which “comes with everything you need to start using React with a Brownie project”, so it sounds like exactly what we need. Let’s see how it works.</p>



<h2 class="wp-block-heading">How to set up Brownie react-mix with existing smart contract</h2>



<p class="wp-block-paragraph">As Brownie Mixes are templates, it is probably best to use them when starting a new project. But it is also possible to use it even if we already have a smart contract. We just need to modify the directory structure and some files.&nbsp;</p>



<h3 class="wp-block-heading">The current project files</h3>



<p class="wp-block-paragraph">Before installing anything, let’s review our current project. We used the SimpleStorage smart contract from the <a href="https://docs.soliditylang.org/en/v0.8.10/introduction-to-smart-contracts.html#storage-example" target="_blank" rel="noreferrer noopener"><strong>Solidity documentation</strong></a>, which is stored in the <code>contracts</code> directory. We also created a simple unit test (<code>tests/test_storage.py</code>). We used the script <code>scripts/deploy.py</code> to deploy the smart contract, which stores artefact files in the build directory. </p>



<p class="wp-block-paragraph">Since we deployed it to the Ropsten testnet (chain ID = 3), the artifact file was stored in the <code>3</code> subdirectory, and the <code>map.json</code> file contains the corresponding entry. We also have the file <code>.env</code> (containing the environment variable <code>WEB3_INFURA_PROJECT_ID</code>), <code>brownie-config.yaml</code> (containing one line: <code>dotenv: .env</code> ), which are used to deploy the smart contract to the Ropsten testnet. </p>



<p class="wp-block-paragraph">The entire directory structure looks like the following.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ tree .
.
├── .env
├── .gitattributes
├── .gitignore
├── brownie-config.yaml
├── build
│   ├── contracts
│   │   └── SimpleStorage.json
│   ├── deployments
│   │   ├── 3
│   │   │   └── 0xafB83356eeeAA6E18B9a76126DE8edFD61BE5385.json
│   │   └── map.json
│   ├── interfaces
│   └── tests.json
├── contracts
│   └── storage.sol
├── interfaces
├── reports
├── scripts
│   └── deploy.py
└── tests
    └── test_storage.py
</pre>



<h3 class="wp-block-heading">Install react-mix</h3>



<p class="wp-block-paragraph">We can install <code>react-mix</code> by using the <code>brownie bake</code> command, as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie bake react-mix
Brownie v1.17.1 - Python development framework for Ethereum

Downloading from https://github.com/brownie-mix/react-mix/archive/master.zip...
405kiB [00:00, 1.94MiB/s]
SUCCESS: Brownie mix 'react-mix' has been initiated at /Users/mikio/brownie_test/react</pre>



<p class="wp-block-paragraph">It will create a new directory called react in the current directory, containing all the directories we need to start a new project in Brownie.&nbsp;</p>



<p class="wp-block-paragraph">We can then install the necessary dependencies.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ cd ./react/client
[~/brownie_test/react/client]$ yarn install</pre>



<h2 class="wp-block-heading">Walking Through App.js</h2>



<p class="wp-block-paragraph">After <code>react-mix</code> is installed, let’s see how it is implemented. The code is based on the latest version at the time of writing (December 2021).</p>



<p class="wp-block-paragraph">The main part of the application is in <code>react/client/src/App.js</code>. The <code>componentDidMount()</code> lifecycle method takes care of the initial setup, such as connecting to the <a rel="noreferrer noopener" href="https://blog.finxter.com/ethereum-top-10-articles-to-get-started/" data-type="post" data-id="53284" target="_blank">Ethereum</a> network, getting the account information, and loading smart contracts. </p>



<p class="wp-block-paragraph">Line 24 creates a <code>web3</code> instance by calling <code>getWeb3.js</code>.</p>



<p class="wp-block-paragraph"><code><strong>react/client/src/App.js</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">
// Get network provider and web3 instance.
const web3 = await getWeb3()
</pre>



<p class="wp-block-paragraph">It uses the <code>window.ethereum</code> object from <code>getEthereum.js</code>, if it’s available, to create the <code>web3</code> instance.</p>



<p class="wp-block-paragraph"><code><strong>react/client/src/getWeb3.js</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const ethereum = await getEthereum()
let web3

if (ethereum) {
    web3 = new Web3(ethereum)
</pre>



<p class="wp-block-paragraph">Browser extension wallets such as MetaMask <a href="https://docs.metamask.io/guide/ethereum-provider.html"><strong>inject</strong></a> the <code>window.ethereum</code> object to the web page and provide account information and connectivity to the Ethereum network. The code above uses this functionality.</p>



<p class="wp-block-paragraph">Going back to <code>App.js</code>, the code requests MetaMask to provide the account information in line 29.</p>



<p class="wp-block-paragraph"><code><strong>react/client/src/App.js</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Try and enable accounts (connect metamask)
try {
     const ethereum = await getEthereum()
     ethereum.enable()</pre>



<p class="wp-block-paragraph"><a rel="noreferrer noopener" href="https://docs.metamask.io/guide/ethereum-provider.html#legacy-methods" target="_blank"><strong>MetaMask documentation</strong></a> suggests using <code>ethereum.request({ method: 'eth_requestAccounts' })</code> instead of <code>ethereum.enable()</code>, so we should probably update it.</p>



<p class="wp-block-paragraph">Then, it obtains the account information in line 37 and the chain ID in line 40 from MetaMask.</p>



<p class="wp-block-paragraph"><code><strong>react/client/src/App.js</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Use web3 to get the user's accounts
const accounts = await web3.eth.getAccounts()

// Get the current chain id
const chainid = parseInt(await web3.eth.getChainId())
</pre>



<p class="wp-block-paragraph">It loads the information about smart contracts in line 46 by calling the method <code>loadInitialContracts()</code>, defined from lines 50 to 82.</p>



<p class="wp-block-paragraph"><code><strong>react/client/src/App.js</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">this.setState({
    web3,
    accounts,
    chainid
}, await this.loadInitialContracts)</pre>



<p class="wp-block-paragraph">This method uses another method <code>loadContract()</code>, defined from line 84 to 107, to actually load the smart contract artifacts. It searches the contract address in the file <code>client/src/artifacts/deployments/map.json</code> (line 91).</p>



<p class="wp-block-paragraph"><code><strong>react/client/src/App.js</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">
// Get the address of the most recent deployment from the deployment map
let address
try {
    address = map[chain][contractName][0]
} catch (e) {
...
</pre>



<p class="wp-block-paragraph">The file <code>map.json</code> is created by Brownie when the smart contract is deployed. Currently, the file exists in the default directory <code>build/deployments</code>, so we will need to change the location.</p>



<p class="wp-block-paragraph">Then, it loads the smart contract artifacts for the address in line 100. Again the <a href="https://blog.finxter.com/python-input-output-json/" data-type="post" data-id="44727" target="_blank" rel="noreferrer noopener">JSON file</a> is currently located in <code>build/deployments</code>, so we will need to change the location of this file as well. </p>



<p class="wp-block-paragraph"><code><strong>react/client/src/App.js</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Load the artifact with the specified address
let contractArtifact
try {
    contractArtifact = await import(`./artifacts/deployments/${chain}/${address}.json`)
} catch (e) {
...
</pre>



<p class="wp-block-paragraph">It creates a smart contract object using the address and the ABI in the artifact in line 106.</p>



<p class="wp-block-paragraph"><code><strong>react/client/src/App.js</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">
return new web3.eth.Contract(contractArtifact.abi, address)
</pre>



<p class="wp-block-paragraph">This object is stored in the react state, among others (<code>web3</code>, accounts, chain ID), so we can use it to interact with the smart contract. For example, the following part (line 125 &#8211; 139) shows how to call the <code>set()</code> function (line 133) and the <code>get()</code> function (line 136). </p>



<p class="wp-block-paragraph"><code><strong>react/client/src/App.js</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">changeSolidity = async (e) => {
    const {accounts, solidityStorage, solidityInput} = this.state
    e.preventDefault()
    const value = parseInt(solidityInput)
    if (isNaN(value)) {
        alert("invalid value")
        return
    }
    await solidityStorage.methods.set(value).send({from: accounts[0]})
        .on('receipt', async () => {
            this.setState({
                solidityValue: await solidityStorage.methods.get().call()
            })
        })
}
</pre>



<p class="wp-block-paragraph">The sample code is written for the smart contracts implemented in the react/contracts directory. Although the smart contracts are essentially the same as ours, we will need to update the code to use our smart contract.</p>



<h2 class="wp-block-heading">Post-installation modification</h2>



<p class="wp-block-paragraph">We will need to make the following changes so that the React app can use our smart contract.</p>



<ul class="wp-block-list"><li>Move the client directory</li><li>Move the smart contract artifacts</li><li>Update <code>brownie-config.yaml</code></li><li>Update <code>client/src/App.js</code></li></ul>



<h3 class="wp-block-heading">Move the client directory</h3>



<p class="wp-block-paragraph">The template creates all the necessary directories so that we can start a new smart contract project in Brownie. But, as we already have our smart contract, we only need the client application in the <code>react/client</code> directory. So, let’s copy the <code>react/client</code> directory to the project root directory.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ cp -R react/client client</pre>



<p class="wp-block-paragraph">This client directory is essentially the one created by <a rel="noreferrer noopener" href="https://create-react-app.dev/" target="_blank"><code>create-react-app</code></a> with some <code>web3</code> specific files, such as <code>getEthereum.js</code> and <code>getWeb3.js</code> as well as the directory artifacts which is to store smart contract artifacts, as we saw in the previous section.</p>



<p class="wp-block-paragraph">After the copy finishes, we can delete the react directory. The project directory structure looks like below (excluding the <code>react</code> directory).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ tree .
.
├── brownie-config.yaml
├── build
│   ├── contracts
│   │   └── SimpleStorage.json
│   ├── deployments
│   │   ├── 3
│   │   │   └── 0xafB83356eeeAA6E18B9a76126DE8edFD61BE5385.json
│   │   └── map.json
│   ├── interfaces
│   └── tests.json
├── client
│   ├── README.md
│   ├── package-lock.json
│   ├── package.json
│   ├── node_modules
│   │   ├── ...
│   │   └── robots.txt
│   ├── public
│   │   ├── favicon.ico
│   │   ├── ...
│   │   └── robots.txt
│   ├── src
│   │   ├── App.css
│   │   ├── App.js
│   │   ├── App.test.js
│   │   ├── artifacts
│   │   │   ├── contracts
│   │   │   ├── deployments
│   │   │   └── interfaces
│   │   ├── getEthereum.js
│   │   ├── getWeb3.js
│   │   ├── index.css
│   │   ├── index.js
│   │   ├── logo.svg
│   │   ├── serviceWorker.js
│   │   └── setupTests.js
│   └── yarn.lock
├── contracts
│   └── storage.sol
├── interfaces
├── reports
├── scripts
│   └── deploy.py
└── tests
    └── test_storage.py
</pre>



<h3 class="wp-block-heading">Move the smart contract artefacts</h3>



<p class="wp-block-paragraph">Our current smart contract artifacts are in the <code>build</code> directory. But as we saw in the previous section, the React app needs to access the artifacts, so let’s move the artifacts from the <code>build</code> directory to the <code>client/src/artifacts</code> directory.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ mv build/* client/src/artifacts/</pre>



<h3 class="wp-block-heading">Update brownie-config.yaml</h3>



<p class="wp-block-paragraph">We also need to let Brownie know that we are now using a new directory for the artifacts; otherwise, Brownie will continue using the <code>build</code> directory. We can do so by adding the build entry to the <code>project_structure</code> section in the file <code>brownie-config.yaml</code> as shown below.</p>



<p class="wp-block-paragraph">We also need to set <a rel="noreferrer noopener" href="https://eth-brownie.readthedocs.io/en/stable/deploy.html#saving-deployments-on-development-networks" target="_blank"><code>dev_deployment_artifacts</code></a> to <code>true</code>, which will create and remove the artifacts in the development environment.</p>



<p class="wp-block-paragraph"><code><strong>brownie-config.yaml</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dotenv: .env 

project_structure:
    build: client/src/artifacts

dev_deployment_artifacts: true
</pre>



<h3 class="wp-block-heading">Update App.js</h3>



<p class="wp-block-paragraph">Lastly, we need to update the React app to use our existing smart contract. The file <code>App.js</code> is the main application file, so the file&#8217;s actual content will naturally be different depending on the smart contract. But, in this article, we will use the template code as much as possible for demonstration purposes. </p>



<p class="wp-block-paragraph">In this article, we will change the following points:</p>



<ul class="wp-block-list"><li>Update the references to the template smart contracts (<code>vyperStorage</code>, <code>solidityStorage</code>) to our smart contract (<code>simpleStorage</code>)</li><li>Remove the chain ID checks (the sample code is for the Kovan testnet (chain ID = 42), but we are using Ropsten testnet.)</li><li>Clean up the messages shown on the page</li><li>Show the transaction Hash after executing the <code>set()</code> function so that we can verify the transaction.</li></ul>



<p class="wp-block-paragraph">The entire file is as follows.&nbsp;</p>



<p class="wp-block-paragraph"><code><strong>client/src/App.js</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import React, {Component} from "react"
import './App.css'
import {getWeb3} from "./getWeb3"
import map from "./artifacts/deployments/map.json"
import {getEthereum} from "./getEthereum"

class App extends Component {

    state = {
        web3: null,
        accounts: null,
        chainid: null,
        simpleStorage: null,
        storageValue: 0,
        storageInput: 0,
        transactionHash: null
    }

    componentDidMount = async () => {

        // Get network provider and web3 instance.
        const web3 = await getWeb3()

        // Try and enable accounts (connect metamask)
        try {
            const ethereum = await getEthereum()
            // ethereum.enable()
            ethereum.request({ method: 'eth_requestAccounts' });
        } catch (e) {
            console.log(`Could not enable accounts. 
            Interaction with contracts not available.
            Use a modern browser with a Web3 plugin to fix this issue.`)
            console.log(e)
        }

        // Use web3 to get the users accounts
        const accounts = await web3.eth.getAccounts()

        // Get the current chain id
        const chainid = parseInt(await web3.eth.getChainId())

        this.setState({
            web3,
            accounts,
            chainid
        }, await this.loadInitialContracts)

    }

    loadInitialContracts = async () => {
        var _chainID = 0;
        if (this.state.chainid === 3){
            _chainID = 3;
        }
        if (this.state.chainid === 1337){
            _chainID = "dev"
        }
        const simpleStorage = await this.loadContract(_chainID, "SimpleStorage")

        if (!simpleStorage) {
            return
        }

        const storageValue = await simpleStorage.methods.get().call()

        this.setState({
            simpleStorage,
            storageValue,
        })
    }

    loadContract = async (chain, contractName) => {
        // Load a deployed contract instance into a web3 contract object
        const {web3} = this.state

        // Get the address of the most recent deployment from the deployment map
        let address
        try {
            address = map[chain][contractName][0]
        } catch (e) {
            console.log(`Could not find any deployed contract "${contractName}" on the chain "${chain}".`)
            return undefined
        }

        // Load the artifact with the specified address
        let contractArtifact
        try {
            contractArtifact = await import(`./artifacts/deployments/${chain}/${address}.json`)
        } catch (e) {
            console.log(`Failed to load contract artifact "./artifacts/deployments/${chain}/${address}.json"`)
            return undefined
        }

        return new web3.eth.Contract(contractArtifact.abi, address)
    }

    changeStorage = async (e) => {
        const {accounts, simpleStorage, storageInput} = this.state
        e.preventDefault()
        const value = parseInt(storageInput)
        if (isNaN(value)) {
            alert("invalid value")
            return
        }
        await simpleStorage.methods.set(value).send({from: accounts[0]})
            .on('transactionHash', async (transactionHash) => {
                this.setState({ transactionHash })
            })
            .on('receipt', async () => {
                this.setState({
                    storageValue: await simpleStorage.methods.get().call()
                })
            })
    }

    render() {
        const {
            web3, 
            accounts,
            simpleStorage,
            storageValue,
            storageInput,
            transactionHash
        } = this.state

        if (!web3) {
            return &lt;div>Loading Web3, accounts, and contracts...&lt;/div>
        }

        if (!simpleStorage) {
            return &lt;div>Could not find a deployed contract. Check console for details.&lt;/div>
        }

        const isAccountsUnlocked = accounts ? accounts.length > 0 : false

        return (&lt;div className="App">
           {
                !isAccountsUnlocked ?
                    &lt;p>&lt;strong>Connect with Metamask and refresh the page to
                        be able to edit the storage fields.&lt;/strong>
                    &lt;/p>
                    : null
            }
            &lt;h1>Simple Storage&lt;/h1>
            &lt;div>The current stored value is {storageValue}.&lt;/div>
            &lt;br/>
            &lt;form onSubmit={(e) => this.changeStorage(e)}>
                &lt;div>
                    &lt;label>Change the value to &lt;/label>
                    &lt;input
                        name="storageInput"
                        type="text"
                        value={storageInput}
                        onChange={(e) => this.setState({storageInput: e.target.value})}
                    />.
                    &lt;p>
                        &lt;button type="submit" disabled={!isAccountsUnlocked}>Submit&lt;/button>
                    &lt;/p>
                &lt;/div>
            &lt;/form>
            &lt;br/>
            {transactionHash ?
                &lt;div>
                    &lt;p>Last transaction Hash: {transactionHash}&lt;/p>
                &lt;/div>
            : null
            }
        &lt;/div>)
    }
}

export default App</pre>



<h2 class="wp-block-heading">Import account into MetaMask</h2>



<p class="wp-block-paragraph">Since we use MetaMask to interact with the Ethereum network in the React app, we need an account on MetaMask. For demonstration purposes, we will import our <code>deployment_account</code> account to MetaMask.<br></p>



<p class="wp-block-paragraph">We can find the account by running the <code>brownie accounts list</code> command. If you don’t have an account, you can create one by following the <a href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" target="_blank" rel="noreferrer noopener"><strong>previous article</strong></a>. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie accounts list
Brownie v1.17.1 - Python development framework for Ethereum

Found 1 account:
 └─deployment_account: 0x84aa678F1088eC3D6cb74204bB239615846C3526
</pre>



<p class="wp-block-paragraph">If you have not installed MetaMask, you can find the tutorial on Finxter below.&nbsp;</p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/metamask-simple-tutorial/" target="_blank"><strong>MetaMask Simple Tutorial</strong></a></li></ul>



<p class="wp-block-paragraph">To import the <code>deployment_account</code> account into MetaMask, we first need to export it from Brownie as a JSON keystore file by running <code>brownie accounts export</code> command. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie accounts export deployment_account ~/brownie_test/deployment_account.json
Brownie v1.17.1 - Python development framework for Ethereum

SUCCESS: Account with id 'deployment_account' has been exported to keystore '/Users/mikio/brownie_test/deployment_account.json'
</pre>



<p class="wp-block-paragraph">Log on to MetaMask, click on the account icon in the top-right corner and select Import Account.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/8UkPm02G_DFyWJj4xUOdtPUeJLf05seaefO_cemhD1aK0hfQQh8CT295UplurmkIp9MT0bZMYi83IddfojztB7kLzsEBnUeVeNfTN8thOfGQZg7NSG6ofALj-EpT45AQi-y6xybZ" alt=""/></figure></div>



<p class="wp-block-paragraph">Select “JSON File” from the drop-down menu as Select Type and choose the file exported above. Type the password (created when the account was generated) and click “Import”.&nbsp;</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/7XjFbfjRg3gwPtwR5nx_vml1lNcT1hQDoPbTFiRmTzWPzl0e3m_3ePlZLrTmJPftMN6jHl5gaBoc1B3iC8ijHSsIELIOng-uqalh5PR75VK4fNsdhc66swbzvgDz_Gn9ATK_AJgm" alt=""/></figure></div>



<p class="wp-block-paragraph">After a few minutes, the account should become visible on MetaMask. Optionally we can update the account name to <code>deployment_account</code> by clicking on the three dots on the right-hand side of the account name and selecting <code>Account details</code>. Then click on the pencil icon next to the account name.</p>



<h2 class="wp-block-heading">Use Development Network</h2>



<p class="wp-block-paragraph">We can test the application using the local blockchain (Ganache). Start the Brownie console with the <code>--network development</code> option, which automatically runs the <code>ganache-cli</code> command.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie console --network development
Brownie v1.17.1 - Python development framework for Ethereum

BrownieTestProject is the active project.

Launching 'ganache-cli --accounts 10 --hardfork istanbul --gasLimit 12000000 --mnemonic brownie --port 8545 --defaultBalanceEther 100000000000000000000'...
Brownie environment is ready.
</pre>



<p class="wp-block-paragraph">Then, deploy the smart contract.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> run('deploy')

Running 'scripts/deploy.py::main'...
Enter password for "deployment_account": 
Transaction sent: 0x9a45d022b665c1c7e9a9b5df937d8f5ced4da2d6245f67c34474a6b32ff2a85a
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0
  SimpleStorage.constructor confirmed   Block: 1   Gas used: 90539 (0.75%)
  SimpleStorage deployed at: 0x68612eDF8f534eB752DD1Ea1aa931C7808CF75D1
</pre>



<p class="wp-block-paragraph">Note that the artifacts are stored in the <code>client/src/artifacts/deployments/dev</code> directory, and a new entry is added to the file <code>client/src/artifacts/deployments/map.json</code>.</p>



<p class="wp-block-paragraph"><code><strong>client/src/artifacts/deployments/map.json</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
  "3": {
    "SimpleStorage": [
      "0xafB83356eeeAA6E18B9a76126DE8edFD61BE5385"
    ]
  },
  "dev": {
    "SimpleStorage": [
      "0x68612eDF8f534eB752DD1Ea1aa931C7808CF75D1"
    ]
  }
}
</pre>



<p class="wp-block-paragraph">We also need to transfer some <a href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" data-type="post" data-id="37644" target="_blank" rel="noreferrer noopener">Ether</a> to the deployment account.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> deployment_account = accounts.load('deployment_account')
Enter password for "deployment_account": 
>>> deployment_account.balance()
0
>>> accounts[0].transfer(deployment_account, '1 ether')
Transaction sent: 0x148c052e4f0fd172cab4b1c779d663edce80e31198833bdaa3ddd6ffcdbe73ff
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0
  Transaction confirmed   Block: 2   Gas used: 21000 (0.18%)

&lt;Transaction '0x148c052e4f0fd172cab4b1c779d663edce80e31198833bdaa3ddd6ffcdbe73ff'>
>>> deployment_account.balance()
1000000000000000000
</pre>



<p class="wp-block-paragraph">On MetaMask, the account balance should also show 1 Ether. Make sure to select the network <code>localhost:8545</code>. </p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/RCUgB82LldjUaF89adB8oxpKA3i87On89TbgPmTEUKFD7Uf74PVvPdE7oW7rozv82Ia5jbUMYMbW9DIpd1-RJ4WTgs_d0p09EyBkjO_Bqjd2nzCIPBfyEnU0yF0H24eOD2saraWp" alt=""/></figure></div>



<p class="wp-block-paragraph">Now, open a different terminal and start the React app, which should automatically open the page using the default web browser on <code>localhost:3000</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ cd client
[~/brownie_test/client]$ yarn start

Compiled successfully!

You can now view client in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://192.168.1.3:3000

Note that the development build is not optimized.
To create a production build, use yarn build.
</pre>



<p class="wp-block-paragraph">We should see the main screen on the browser showing that the current store value is 0.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/gm9ititFtfw660mEc-M5Yz5yDP324_-aVdYfKhK-ac7nXpW-oAzT_CJ2leR8r7FvhRE-Q-BuMRc45y2WUrPQUW66bnvh8GYypetFBqdj3j-Jr5CtkP0Exwf6RNY4FNBkulD3E97k" alt=""/></figure></div>



<p class="wp-block-paragraph">We can type an arbitrary value (e.g. 10) in the text field and click the <code>Submit</code> button. A MetaMask confirmation window pops up, showing the transaction fee. </p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/W4w4QI5jlW4BTjn7SH6J5Be109UMKvRcU1v62jTcQ8aDYrs092EvEbe_nI024i6xuvEyyXASxvjcNvxaOsipEiPiTkId-jBAOu8wXs_e4lIFDSyYjEhK0fZ2IrZ8N-YTw9z3D-0e" alt=""/></figure></div>



<p class="wp-block-paragraph">After clicking the <code>Confirm</code> button, the store value should become 10, and the transaction hash should appear at the bottom.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/G9w7NcVtb2mXj3Hg-PMEpQrAZaNo8PNQ50p6GhZ9_D7Tg4uhz_B-H6umrdaYGZGzpnpeqMZQ-472q5QLZb7pFWQst-2z9M9l4wKr6RKbhCLaiX2syE7CsoVWsB5WKBXKDtHwyOPC" alt=""/></figure></div>



<p class="wp-block-paragraph">We can also confirm the current storage value from the Brownie console. Load the <code>SimpleStorage</code> smart contract using the <code>at</code> method. We can find the address in the deploy output above or in the file <code>client/src/artifacts/deployments/map.json</code>. </p>



<p class="wp-block-paragraph">As expected, the <code>get()</code> function returns the value 10.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage = SimpleStorage.at('0x68612eDF8f534eB752DD1Ea1aa931C7808CF75D1')
>>> simple_storage.get()
10
</pre>



<p class="wp-block-paragraph">We can stop the React app by typing <code>Ctrl-C</code> on the second terminal and the Brownie console by typing <code>quit()</code> on the first terminal. Terminating the Brownie console (i.e. the local Ganache blockchain) removes the development artifacts in the <code>client/src/artifacts/deployment</code> directory.</p>



<h2 class="wp-block-heading"> Use Ropsten testnet</h2>



<p class="wp-block-paragraph">We can use the Ropsten testnet in the same way. To interact with the smart contract, the account (<code>deployment_account</code> in this case) needs some test Ether on the Ropsten testnet to pay transaction fees.</p>



<p class="wp-block-paragraph">In addition, make sure that the valid Infura project ID is set to <code>WEB3_INFURA_PROJECT_I</code>D environment variable in the <code>.env</code> file, which we did in the <a href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" target="_blank" rel="noreferrer noopener"><strong>previous article</strong></a>.</p>



<p class="wp-block-paragraph">On the terminal, let’s start the React app. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test/client]$ yarn start

Compiled successfully!

You can now view client in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://192.168.1.3:3000

Note that the development build is not optimized.
To create a production build, use yarn build.
</pre>



<p class="wp-block-paragraph">Open MetaMask and select the network to “Ropsten Test Network”.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/adWv9MzOJxsGMMRNEY1ZyEtlLgCzoZLNn79meOM1nBIsNpqViyWGQ0tR1_5OGqNm5GxNSeThR-Cf3KkGxoqBnnqUtU5OFXyNXtXm0WOsJ-S2EcIFlG0FcEd0CHHVWL22A_7Ppbfc" alt=""/></figure></div>



<p class="wp-block-paragraph">Reload the application, and now the main page should appear. It shows that the current value is 5.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/bG6JnUFf8QYbtUY75jd8PcY5BGRLRdPZAr42nnpISbmqvw2t-KNRtuyX6iCxaAEYEeo5XkXNmBYACMGVTpKryvVaUtCpuQh99YIfXUhzHzsJCNa4Hy23vgfNrnrzBSwyYdl9x-Q6" alt=""/></figure></div>



<p class="wp-block-paragraph">Let’s change it to a different value. Type an arbitrary value (e.g. 10) in the text field and click the <code>Submit</code> button. The MetaMask confirmation window pops up.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/zaUo_SWVk-oLJpVd0JHWVUMv8ZGRZRiD6j6-j__ucD7F726eHUmrTpytDZ5V9DhOiyWWx9GAjfC9FiZeIsQFdcpRbQxcKvTC3pE7fueNvb3fLHGW8PLAa5XYXSsDb1_gy7quU8oT" alt=""/></figure></div>



<p class="wp-block-paragraph">After clicking on the Confirm button, the transaction hash will appear at the bottom. We can search the transaction on <a href="https://ropsten.etherscan.io/" target="_blank" rel="noreferrer noopener"><strong>Ropsten Etherscan</strong></a>, and it will show the details about the transaction. For example, it shows that the input data was 10 at the bottom for this example.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/7RKWm51k0YhyQgvKA4XvHk32qoE2LoSpCz3Zp_wcp0WQAiiYPeENhI-AuI9MGLxAK4xssf5Pn43XRN_OHtgqOVrvxlOIT_fnponM4Edvp3cSDvDxKcX2gauUFMS5KnoFrKWbe-Ny" alt=""/></figure></div>



<p class="wp-block-paragraph">Once the transaction has been confirmed, the React app shows that the currently stored value is 10.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/Bx-ixBt0bHcDdphnUmvgGNPeWxOiC83sAzWJSVvtqIB03jVJUmEm0AvbPU6tCCxzUboyDHEaqqlv-p-8rwgrNMkUJfcTh5kRWasjEo8K8NRQLY2T4LB86-mr5uhcxQRNW98pPsmy" alt=""/></figure></div>



<p class="wp-block-paragraph">We can check the value on the brownie console as well. On the second terminal, start the console using the <code>--network ropsten</code> option.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie console --network ropsten    
Brownie v1.17.1 - Python development framework for Ethereum

BrownieTestProject is the active project.
Brownie environment is ready.
>>> network.show_active()
'ropsten'
>>> network.is_connected()
True
</pre>



<p class="wp-block-paragraph">We can find our smart contract address in the file <code>client/src/artifacts/deployments/map.json</code>. </p>



<p class="wp-block-paragraph"><code><strong>client/src/artifacts/deployments/map.json</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">
{
  "3": {
    "SimpleStorage": [
      "0xafB83356eeeAA6E18B9a76126DE8edFD61BE5385"
    ]
  }
}
</pre>



<p class="wp-block-paragraph">Load the smart contract by specifying the address and checking the current storage value.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage = SimpleStorage.at('0xafB83356eeeAA6E18B9a76126DE8edFD61BE5385')
>>> simple_storage.get()
10</pre>



<p class="wp-block-paragraph">We can stop the React app by typing <code>Ctrl-C</code> on the first terminal and the Brownie console by typing <code>quit()</code> on the second terminal. Since the artefacts are stored in the <code>client/src/artifacts</code> directory, we can always restart the React app and Brownie console to access the smart contract on the testnet.</p>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this article, we explored the Brownie <code>react-mix</code>, a template for creating a React app as a front-end application in Brownie. It comes with sample smart contracts and React app code. Since we already had a smart contract, we modified the directory structure and some files to use our smart contract in the React app. Then we ran the app in the local development environment and the Ropsten testnet. </p>



<p class="wp-block-paragraph">The application implemented in this article is very primitive, but it shows the basic functionality to use the Ethereum network via MetaMask. It is a regular React application, so we can use it as a starting point and enhance it to suit our needs.&nbsp;</p>



<p class="wp-block-paragraph">As Brownie is Python-based and React is JavaScript, they might not be a natural fit. But the functionality to share the artifacts between Brownie and React would be helpful when developing smart contracts and the front-end application at the same time. </p>



<p class="wp-block-paragraph">You can find more about Brownie React Mix on <a href="https://github.com/brownie-mix/react-mix" target="_blank" rel="noreferrer noopener"><strong>Github</strong></a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Deploy a Smart Contract on the Ropsten Testnet in Brownie</title>
		<link>https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/</link>
		
		<dc:creator><![CDATA[Mikio Oba]]></dc:creator>
		<pubDate>Tue, 30 Nov 2021 19:14:47 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=63341</guid>

					<description><![CDATA[In my previous article, we looked at how to set up Brownie, create a project with a simple smart contract, interact with it on a local blockchain and run a unit test. If you haven’t read it yet, please check the following link. Brownie – Smart Contracts in Python Now, we are ready to deploy ... <a title="How to Deploy a Smart Contract on the Ropsten Testnet in Brownie" class="read-more" href="https://blog.finxter.com/how-to-deploy-a-smart-contract-to-the-ropsten-testnet-in-brownie/" aria-label="Read more about How to Deploy a Smart Contract on the Ropsten Testnet in Brownie">Read more</a>]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Deploy a Smart Contract on the Ropsten Testnet in Brownie" width="937" height="527" src="https://www.youtube.com/embed/UISu1jFJOGc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="wp-block-paragraph">In my previous article, we looked at how to set up Brownie, create a project with a simple smart contract, interact with it on a local blockchain and run a unit test. If you haven’t read it yet, please check the following link.</p>



<p class="wp-block-paragraph"><a href="https://blog.finxter.com/brownie-smart-contracts-in-python/"><strong>Brownie – Smar</strong></a><strong><a href="https://blog.finxter.com/brownie-smart-contracts-in-python/" target="_blank" rel="noreferrer noopener">t</a></strong><a href="https://blog.finxter.com/brownie-smart-contracts-in-python/"><strong> Contracts in Python</strong></a></p>



<p class="wp-block-paragraph">Now, we are ready to <strong>deploy our smart contract to a public testnet</strong> so that other people can try it out.&nbsp;</p>



<p class="wp-block-paragraph">In this article, we first look at deploying using a third-party API provider (Infura). Then, we will have a quick look at how to use our own Ethereum node.&nbsp;</p>



<h2 class="wp-block-heading">Ethereum networks</h2>



<h3 class="wp-block-heading">Public testnets</h3>



<p class="wp-block-paragraph">When people buy and sell Ether on an exchange or NFTs on a platform like OpenSea, the transactions occur on the public Ethereum production blockchain, the Mainnet. But there are also several public Ethereum networks that are used for development and testing purposes. They are called <strong><em>testnets</em></strong>. </p>



<p class="wp-block-paragraph">Due to the nature of blockchain technology, it is difficult to update a smart contract once it has been deployed to the Mainnet, so it is generally a good idea to thoroughly test it on a testnet in advance.&nbsp;</p>



<p class="wp-block-paragraph">Some of the widely used Ethereum public testnets are listed below. Each testnet is a separate blockchain, meaning they are independent and do not interact with each other. For example, an account on the Ropsten testnet cannot send Ether to an account on the Rinkeby network.&nbsp;</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Name</td><td>Description</td><td>Chain ID</td></tr><tr><td>Ropsten</td><td>A proof-of-work testnet. This means it&#8217;s the best like-for-like representation of Ethereum.</td><td>3</td></tr><tr><td>Rinkeby</td><td>A proof-of-authority testnet for those running Geth client.</td><td>4</td></tr><tr><td>Görli</td><td>A proof-of-authority testnet that works across clients.</td><td>5</td></tr><tr><td>Kovan</td><td>A proof-of-authority testnet for those running OpenEthereum clients.&nbsp;</td><td>42</td></tr></tbody></table></figure>



<ul class="wp-block-list"><li>The descriptions were taken from the <a href="https://ethereum.org/en/developers/docs/networks/#testnets" target="_blank" rel="noreferrer noopener"><strong>Ethereum documentation</strong></a>.</li><li>The Chain IDs can be found on <a href="https://chainlist.org/" target="_blank" rel="noreferrer noopener"><strong>Chainlist</strong></a>.</li></ul>



<h3 class="wp-block-heading">How to connect to a public testnet</h3>



<p class="wp-block-paragraph">Ethereum is a collection of computers (or nodes) running specific software (or Ethereum client) communicating with each other over the Internet. So, we need to connect to one of the nodes when deploying a smart contract. There are two ways to connect to a node:</p>



<ul class="wp-block-list"><li>Running a node ourselves</li><li>Using an API provider</li></ul>



<p class="wp-block-paragraph">As Ethereum is an open-source project, anyone with sufficient Linux administration knowledge and necessary hardware resources can download the client software and run an Ethereum node. I think it is an excellent way to learn how Ethereum works. Still, it might not be suitable for everyone because of the lack of necessary hardware resources, knowledge, interests, time, or a combination of any of them.</p>



<p class="wp-block-paragraph">The second way is to use an API provider, which gives us unique API endpoints (URLs) to interact with Ethereum networks. As there is no upfront financial cost and it is much quicker than setting up and running a node ourselves, this option is probably suitable for everyone.</p>



<p class="wp-block-paragraph">There are several popular providers, but in this article, we use <a href="https://infura.io/" target="_blank" rel="noreferrer noopener"><strong>Infura</strong></a> as an example.</p>



<h3 class="wp-block-heading">Set up Infura</h3>



<p class="wp-block-paragraph">We first need to create a free Infura account. Go to <a href="https://infura.io/"><strong>https://infura.io/</strong></a> and click on the “SIGN UP” button in the top right-hand corner.</p>



<figure class="wp-block-image"><img decoding="async" src="https://lh4.googleusercontent.com/0jZpWIQlPwXhg3cBPL-_NHliL0khdlPSkP1470qCGYSBXGAAHT1sCONxvPDSo6WWvz4YEq-i0dvj_EB5J2boFSLShvmGdqmgurAf_GAqdD_IAyEi7wURUrSvgoQW9lNtHpL5DX2f" alt=""/></figure>



<p class="wp-block-paragraph">Follow the instructions and create an account.&nbsp;</p>



<p class="wp-block-paragraph">Then, log on to the website and click on the “CREATE NEW PROJECT” button on the main screen.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/7SLSihS5WHDwBM8s1oHipZmGfxnh7PD3k28OMGO-bJhATlmHi9X8XAhcmzKGm0NglkA9P1OR-YFOIasntumfiWo9keP_MKBhd0Ve_2q5haVD7makA8SHo513Z6pGmXktVYeYoit_" alt=""/></figure></div>



<p class="wp-block-paragraph">Select “Ethereum” from the PRODUCT drop-down menu and fill in the project name (any name we like).</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/Gg9Q0UK23NFEdbhDMtu4lDGZEyQDJPUt9HgL3bZP0PvwkFVWRvn3XV3DuztZ0iqslbtjWxtK4KGr-6wQkYZLAoN1wSFS_U9GVB7lpPYE_qkr3jfnf5wVvGYqWGq3Ir13gXTNfhvT" alt=""/></figure></div>



<p class="wp-block-paragraph">On the next page, we can find the KEYS section. We need the project ID on the left-hand side, so copy the project ID.&nbsp;</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/iMzszESv-mCIY1NZLl_R7ym6PdQH8XBQYrONWTTKwnzItUozTm9XDONVqYt9JckE_fFQ7VZXz6aieGPlqGwytWmwZwp1s9mG-N3EVIEPYJSVQkdDpKaGVeryruLpJB86kEExXnVb" alt=""/></figure></div>



<p class="wp-block-paragraph">Then, open a terminal window and go to the Brownie project directory we created in the previous article.&nbsp;</p>



<p class="wp-block-paragraph">Now, we need to set the project ID to the environment variable <code>WEB3_INFURA_PROJECT_ID</code>. We can set it as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ export WEB3_INFURA_PROJECT_ID=691a20ed16eb439f8006a2b3edb45cdf</pre>



<p class="wp-block-paragraph">But this is probably not the best way because we will need to set the environment variable again if we start a new terminal session. So, instead of manually setting the environment variable each time, we can do the following to make it persistent.</p>



<p class="wp-block-paragraph">First, create a file called <code>.env</code> in the project root directory and add the following line (replace the project ID value with your ID):</p>



<p class="wp-block-paragraph"><code><strong>.env</strong></code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">WEB3_INFURA_PROJECT_ID=691a20ed16eb439f8006a2b3edb45cdf</pre>



<p class="wp-block-paragraph">Then, create another file called <code>brownie-config.yaml</code> in the project root directory and add the following line:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">brownie-config.yaml
dotenv: .env </pre>



<p class="wp-block-paragraph">Ensure that the <code>.gitignore</code> file contains the entry <code>.env</code>. This is to make sure that the <code>.env</code> file won’t be committed to the <a href="https://blog.finxter.com/top-cheat-sheets-for-git/" data-type="post" data-id="20843" target="_blank" rel="noreferrer noopener">Git</a> repository.&nbsp;</p>



<p class="wp-block-paragraph">The Infura setup is now complete.</p>



<h3 class="wp-block-heading">Brownie network configuration</h3>



<p class="wp-block-paragraph">We can find the network settings in Brownie by running the brownie networks list command on the terminal.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie networks list                
Brownie v1.17.1 - Python development framework for Ethereum

The following networks are declared:

Ethereum
  ├─Mainnet (Infura): mainnet
  ├─Ropsten (Infura): ropsten
  ├─Rinkeby (Infura): rinkeby
  ├─Goerli (Infura): goerli
  └─Kovan (Infura): kovan

Ethereum Classic
  ├─Mainnet: etc
  └─Kotti: kotti

Arbitrum
  └─Mainnet: arbitrum-main

Binance Smart Chain
  ├─Testnet: bsc-test
  └─Mainnet: bsc-main

Fantom Opera
  ├─Testnet: ftm-test
  └─Mainnet: ftm-main

Polygon
  ├─Mainnet (Infura): polygon-main
  └─Mumbai Testnet (Infura): polygon-test

XDai
  ├─Mainnet: xdai-main
  └─Testnet: xdai-test

Development
  ├─Ganache-CLI: development
  ├─Geth Dev: geth-dev
  ├─Hardhat: hardhat
  ├─Hardhat (Mainnet Fork): hardhat-fork
  ├─Ganache-CLI (Mainnet Fork): mainnet-fork
  ├─Ganache-CLI (BSC-Mainnet Fork): bsc-main-fork
  ├─Ganache-CLI (FTM-Mainnet Fork): ftm-main-fork
  ├─Ganache-CLI (Polygon-Mainnet Fork): polygon-main-fork
  └─Ganache-CLI (XDai-Mainnet Fork): xdai-main-fork
</pre>



<p class="wp-block-paragraph">As we can see, Brownie comes with the network settings using Infura by default, so we don’t need to do anything. We only need to set the environment variable <code>WEB3_INFURA_PROJECT_ID</code>, which we already did in the previous section.</p>



<p class="wp-block-paragraph">Let’s connect to the Ropsten testnet from the Brownie console. Run the brownie console command with the <code>--network ropsten</code> option as shown below.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie console --network ropsten
Brownie v1.17.1 - Python development framework for Ethereum

BrownieTestProject is the active project.
Brownie environment is ready.
>>> network.show_active()
'ropsten'
>>> network.is_connected()
True</pre>



<p class="has-base-background-color has-background wp-block-paragraph"><strong>Note</strong>: If you’ve just added your Infura project ID to the <code>.env</code> file, you might need to reopen a terminal window so that Brownie can read it.</p>



<p class="wp-block-paragraph">Now, the network configuration in Brownie is complete.</p>



<h2 class="wp-block-heading">How to deploy a smart contract</h2>



<p class="wp-block-paragraph">To deploy a smart contract to an Ethereum network, we need an Ethereum account. In my <a href="https://blog.finxter.com/brownie-smart-contracts-in-python/"><strong>previous article</strong></a>, we used an account created by Ganache to deploy our smart contract, but it is not a persistent account. When deploying a smart contract to a testnet, we need a permanent account on the network, so let’s create a new account first.&nbsp;</p>



<h3 class="wp-block-heading"><strong>Create a deployment account</strong></h3>



<p class="wp-block-paragraph">First, let’s check if there are any local accounts. Run the <code>brownie accounts lis</code>t command.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie accounts list                     
Brownie v1.17.1 - Python development framework for Ethereum

Found 0 accounts:
</pre>



<p class="wp-block-paragraph">In this case, there is no account. Let’s create a new one called <code>deployment_account</code>. When prompted, type a new password. Be sure to remember it because we will need it later.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie accounts generate deployment_account
Brownie v1.17.1 - Python development framework for Ethereum

Generating a new private key...
mnemonic: 'xxxxx xxxx xxxx xxxxx xxxx xxxx xxxxx xxxxx xxxxxx xxxx xxxxxx xxxxxx'
Enter the password to encrypt this account with: 
SUCCESS: A new account '0x30e4E6290941A35d6988B52451B32badE7C7CbAC' has been generated with the id 'deployment_account'
</pre>



<p class="wp-block-paragraph">The hex-decimal number (<code>0x30e4E6290941A35d6988B52451B32badE7C7CbAC</code>) is the account address. </p>



<p class="wp-block-paragraph">We can check that the account has been created by running the <code>brownie accounts list</code> command again.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie accounts list
Brownie v1.17.1 - Python development framework for Ethereum

Found 1 account:
 └─deployment_account: 0x30e4E6290941A35d6988B52451B32badE7C7CbAC
</pre>



<p class="wp-block-paragraph">Unlike the test accounts created by Ganache, this account does not have any Ether yet. We can check the balance from the console. Open a console with the <code>--network ropsten</code>  option to connect to the Ropsten testnet and load deployment_account we’ve just created. When prompted, type in the password when generating the account. Then run the <code>balance()</code> function, which shows that the balance is currently 0. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie console --network ropsten
Brownie v1.17.1 - Python development framework for Ethereum

BrownieTestProject is the active project.
Brownie environment is ready.
>>> account = accounts.load('deployment_account')
Enter password for "deployment_account": 
>>> account.balance()
0
</pre>



<p class="wp-block-paragraph">When deploying a smart contract, we need to <a href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" data-type="post" data-id="37644" target="_blank" rel="noreferrer noopener">pay the gas</a> because deployment is a transaction. So, we need to send some Ether to this account first. Unless you already have some Ether on the Ropsten testnet, the easiest way is to request some Ether on the Faucet. Go to <a href="https://faucet.ropsten.be/" target="_blank" rel="noreferrer noopener"><strong>Ropsten Ethereum Faucet</strong></a> website and type in the account address (make sure to replace the address value with your own) and press the “Send me test Ether” button.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/d6U9bOeZY57ElSepO_WVwqpnEtqdiu7tJ4alRZAi2Ckvp6gaAhs7CPOelyfZeFb_8ftYFcabuL4POEVE126kfrCwpWY5WtQLInsandWrGBL3QCps8LQx81zNGyQvDXLRmawFPj4S" alt=""/></figure></div>



<p class="wp-block-paragraph">As long as the Faucet is working, we should get 0.3 Ether after a few minutes.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> web3.fromWei(account.balance(), 'ether')
Decimal('0.3')</pre>



<p class="wp-block-paragraph">Another way to get test Ether is by mining some on our own. As the Ropsten testnet uses the proof-of-work consensus mechanism, we can run our node and mine test Ether (at least until <a href="https://blog.finxter.com/ethereum-top-10-articles-to-get-started/" data-type="post" data-id="53284" target="_blank" rel="noreferrer noopener">Ethereum</a> moves to proof-of-stake). I will explain the overview later in this article.</p>



<p class="wp-block-paragraph">Once the account has some Ether (0.1 ether should be enough), we are ready to go to the next step.&nbsp;</p>



<h3 class="wp-block-heading">Deploy a smart contract</h3>



<p class="wp-block-paragraph">In my <a href="https://blog.finxter.com/brownie-smart-contracts-in-python/" target="_blank" rel="noreferrer noopener"><strong>previous article</strong></a>, we manually deployed the smart contract to the local blockchain. Although we can do the same, let’s create a deployment script this time. In the scripts subdirectory, create a file called <code>deploy.py</code> with the following content.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from brownie import SimpleStorage, accounts

def main():
    account = accounts.load('deployment_account')
    SimpleStorage.deploy({'from': account})</pre>



<p class="wp-block-paragraph">As we can see, this is a normal Python script. Just to recap, <code>SimpleStorage</code> is the smart contract we created (stored in <code>contracts/storage.sol</code>), which was taken from the <a href="https://docs.soliditylang.org/en/v0.8.10/introduction-to-smart-contracts.html#storage-example" target="_blank" rel="noreferrer noopener"><strong>Solidity documentation</strong></a>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 &lt;0.9.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }
}
</pre>



<p class="wp-block-paragraph">Now, open a terminal window and run the command brownie run <code>deploy.py --network ropsten</code> as shown below. When prompted, type the account password.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie run deploy.py --network ropsten
Brownie v1.17.1 - Python development framework for Ethereum

BrownieTestProject is the active project.

Running 'scripts/deploy.py::main'...
Enter password for "deployment_account": 
Transaction sent: 0x51f0a466abc059da5185a7dc280990157ee7741e5c0acbeae5674b91cbc026ee
  Gas price: 1.599530008 gwei   Gas limit: 99592   Nonce: 0
  SimpleStorage.constructor confirmed   Block: 11512310   Gas used: 90539 (90.91%)
  SimpleStorage deployed at: 0xafB83356eeeAA6E18B9a76126DE8edFD61BE5385
</pre>



<p class="wp-block-paragraph">We can check our smart contract on <a href="https://ropsten.etherscan.io/" target="_blank" rel="noreferrer noopener"><strong>https://ropsten.etherscan.io/</strong></a>. Copy our smart contract address (<code>0xafB83356eeeAA6E18B9a76126DE8edFD61BE5385</code> in the example above) and paste it into the search box, which shows the information about our smart contract.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/JHOk3vghxOLjARFrPHGPViDV9KqG2unfw2Gh4GZyVn0oTlHu15zlhE5XjA2WRS0oVaDioF_UV4wZ36z6tQjN3Vn6zN5IoTqupsso_7Bg3GUn1iSBuArPd22x6kgtLwQymDUly5wE" alt=""/></figure></div>



<h3 class="wp-block-heading"><strong>&nbsp;Interact with the smart contract</strong></h3>



<p class="wp-block-paragraph">We can interact with the smart contract using the Brownie console. Let’s start the console and connect to the Ropsten testnet.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie console --network ropsten      
Brownie v1.17.1 - Python development framework for Ethereum

BrownieTestProject is the active project.
Brownie environment is ready.
>>>
</pre>



<p class="wp-block-paragraph">Load the smart contract by specifying the address. Make sure to use the address of the deployed smart contract.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage = SimpleStorage.at('0xafB83356eeeAA6E18B9a76126DE8edFD61BE5385')</pre>



<p class="wp-block-paragraph">Then, we can run the function <code>get()</code>, which should return the value 0 because we haven’t set a value yet.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage.get()
0</pre>



<p class="wp-block-paragraph">To update the value, we need to send a transaction, so we need an account. Let’s use <code>deployment_account</code>. When prompted, type in the account password. Then, run the function <code>set()</code> to set the value to 5 by specifying the <code>deployment_account</code> to thefrom address. It should return a transaction object after 10 seconds or so.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage.set(5, {'from': account})
Transaction sent: 0xd3945cbb7f45f8c877f38f869f78040a1952c299ff27a8c9931950efba0095af
  Gas price: 1.504997803 gwei   Gas limit: 47843   Nonce: 1
  SimpleStorage.set confirmed   Block: 11512386   Gas used: 43494 (90.91%)

&lt;Transaction '0xd3945cbb7f45f8c877f38f869f78040a1952c299ff27a8c9931950efba0095af'></pre>



<p class="wp-block-paragraph">We can check the value by running the <code>get()</code> function again, which now shows the value 5.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage.get()
5</pre>



<p class="wp-block-paragraph">We can also find the transaction on <a href="https://ropsten.etherscan.io/address/0xafB83356eeeAA6E18B9a76126DE8edFD61BE5385" target="_blank" rel="noreferrer noopener"><strong>Etherscan</strong></a> by searching the transaction hash value, which shows that the storage value has changed from 0 to 5.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/3ch-DHPgjvbVpJS2LbcMvhXhkCnSbAJCyavNcofgttUTas9y4piXjVDnRBmBTvHP8HQ-CMTZ4ySEQx3yw1bwglKg-wbid3CDb3QEHjhRZLoQSDxeaXZPVrvVuWjbKg2aC4kkyGFE" alt=""/></figure></div>



<h2 class="wp-block-heading">How to use your own node (overview)</h2>



<p class="wp-block-paragraph">As I mentioned in the previous section, another way to connect to the Ropsten testnet is to run an Ethereum node on the testnet ourselves. We will need to set up a Linux server (locally or on a cloud) where we can install the Ethereum client software (<a href="https://geth.ethereum.org/" target="_blank" rel="noreferrer noopener"><strong>Geth</strong></a>) and keep it running (at least while connecting to the testnet). </p>



<p class="wp-block-paragraph">When I set up a local Ethereum node, the following article was very helpful:</p>



<p class="wp-block-paragraph"><a href="https://www.linkedin.com/pulse/how-mine-ropsten-testnet-ether-keir-finlow-bates" target="_blank" rel="noreferrer noopener"><strong>How to mine Ropsten testnet Ether</strong></a></p>



<p class="wp-block-paragraph">I will summarise some of the key points in the following sections. For more details, please read the article above.</p>



<h3 class="wp-block-heading">Install Geth</h3>



<p class="wp-block-paragraph">I used Ubuntu 20.04.3 LTS. To download Geth, run the following commands:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ sudo add-apt-repository -y ppa:ethereum/ethereum
$ sudo apt-get install -y software-properties-common
$ sudo apt-get update
$ sudo apt-get -y install ethereum</pre>



<p class="wp-block-paragraph">Once finished, you can verify the installation by running <code>geth version</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ geth version
Geth
Version: 1.10.12-stable
Git Commit: 6c4dc6c38827296dec5a49a6ea25fd7f0eb4ac77
Architecture: amd64
Go Version: go1.17.2
Operating System: linux
GOPATH=
GOROOT=go
</pre>



<h3 class="wp-block-heading">Run Geth</h3>



<p class="wp-block-paragraph">Now you can start the Ethereum client. First, it will download the blockchain data, which will take a few hours (depending on the Internet connection).&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""> 
geth --ropsten --http --http.api eth,net,web3,personal,miner,admin,txpool,debug --http.corsdomain '*' --http.addr 192.168.1.18 --http.port 8545</pre>



<p class="wp-block-paragraph">You will need to replace the IP address (<code>192.168.1.18</code>) with the IP address of your node. The disk space required to download the blockchain data on Ropsten was currently about 130GB. </p>



<p class="wp-block-paragraph">You can check the status using the Geth console. Open a Linux terminal and run the command <code>geth attach http://&lt;IP address></code> (make sure to use the IP address of your own Ethereum node).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ geth attach http://192.168.1.18:8545
Welcome to the Geth JavaScript console!

instance: Geth/v1.10.12-stable-6c4dc6c3/linux-amd64/go1.17.2
at block: 11512999 (Sun Nov 28 2021 16:36:58 GMT+0100 (CET))
 datadir: /home/mikio/.ethereum/ropsten
 modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

To exit, press ctrl-d or type exit
> </pre>



<p class="wp-block-paragraph">The command <code>eth.syncing</code> will show you the current syncing status. You might also need to add more peers. Please refer to the article above for more details.</p>



<h3 class="wp-block-heading">(Optional) Mine Ether</h3>



<p class="wp-block-paragraph">Once the Ethereum client has synchronised the blockchain data and is up and running, you can also mine some Ether. It will require computational power, so it is generally recommended to use powerful GPUs. But it all depends on the network utilisation and will change when Ethereum moves to the proof-of-stake consensus mechanism, which is planned to take place sometime in 2022 (for more details, see <a href="https://ethereum.org/en/eth2/merge/" target="_blank" rel="noreferrer noopener"><strong>The merge</strong></a>).</p>



<p class="wp-block-paragraph">To mine Ether, you first need an account. Create an account using Brownie as shown in the previous section, or use a wallet such as Metamask. Then, set it to the coinbase address of the node from the Geth console.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">> miner.setEtherbase("0x30e4E6290941A35d6988B52451B32badE7C7CbAC")</pre>



<p class="wp-block-paragraph">Then start the mining process.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">> miner.start(4)</pre>



<p class="wp-block-paragraph">The argument 4 means 4 CPU cores to use. When the miner mines a block, the account will automatically receive the reward (generally about two ether per block). In my environment, about 10 to 20 ether was mined per day without additional powerful GPUs like an Nvidia graphics card.&nbsp;</p>



<h3 class="wp-block-heading">Connect to the node in Brownie</h3>



<p class="wp-block-paragraph">We can use our node to interact with the Ropsten testnet instead of using the Infura API endpoints. All we need to do is add a new network in Brownie.</p>



<p class="wp-block-paragraph">Go to the terminal and run the command below. It will create a new network called <code>ropsten-local</code> using the specified IP address, so make sure to use the IP address of your node. The Chain ID is Ropsten’s ID, 3 (see the section “Public testnets” above).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie networks add "Ethereum" ropsten-local host="http://192.168.1.18:8545" name="Ropsten (Local Geth)" chainid=3
Brownie v1.17.1 - Python development framework for Ethereum

SUCCESS: A new network 'Ropsten (Local Geth)' has been added
  └─Ropsten (Local Geth)
    ├─id: ropsten-local
    ├─chainid: 3
    └─host: http://192.168.1.18:8545
</pre>



<p class="wp-block-paragraph">Then, you can connect to the Ropsten testnet using the option &#8211;network ropsten-local.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie console --network ropsten-local
Brownie v1.17.1 - Python development framework for Ethereum

BrownieTestProject is the active project.
Brownie environment is ready.
>>> network.show_active()
'ropsten-local'
>>> network.is_connected()
True
</pre>



<p class="wp-block-paragraph">We can interact with the smart contract we deployed earlier in the same way.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage = SimpleStorage.at('0xafB83356eeeAA6E18B9a76126DE8edFD61BE5385')
>>> simple_storage.get()
5
</pre>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this article, we looked at how to deploy a smart contract to a public Ethereum testnet in Brownie. There are two ways to connect to Ethereum; one uses an API provider such as Infura, and the other uses our own Ethereum node.</p>



<p class="wp-block-paragraph">First, we looked at the first option. After creating an account on Infura, we set up a project ID and used it to configure a network in Brownie. Then we looked at how to create a deployment account in Brownie and use it to deploy our smart contract. Lastly, we looked at how to interact with the smart contract using the Brownie console and checked the information on <a href="https://etherscan.io/" data-type="URL" data-id="https://etherscan.io/" target="_blank" rel="noreferrer noopener">Etherscan.io</a>.</p>



<p class="wp-block-paragraph">Finally, we looked at the second option. We can download and install the Ethereum client software (Geth) on an Ubuntu machine, run our own Ethereum node on the Ropsten testnet, and optionally mine some Ether (at least for now). We can use the node instead of using Infura endpoints to connect to the Ropsten testnet.</p>



<p class="wp-block-paragraph">You can find more about the deployment in Brownie in the following section of the Brownie documentation.</p>



<p class="wp-block-paragraph"><a href="https://eth-brownie.readthedocs.io/en/stable/deploy.html#" target="_blank" rel="noreferrer noopener"><strong>Deployment Basics</strong></a></p>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">Learn Solidity Course</a></h2>



<p class="wp-block-paragraph">Solidity is the programming language of the future.</p>



<p class="wp-block-paragraph">It gives you the rare and sought-after superpower to program against the &#8220;Internet Computer&#8221;, i.e., against decentralized Blockchains such as <em>Ethereum</em>, <em>Binance Smart Chain</em>, <em>Ethereum Classic</em>, <em>Tron</em>, and <em>Avalanche </em>&#8211; to mention just a few Blockchain infrastructures that support Solidity.<br><br>In particular, Solidity allows you to<em> create smart contracts</em>, i.e., pieces of code that automatically execute on specific conditions in a completely decentralized environment. For example, smart contracts empower you to create your own <em>decentralized autonomous organizations</em> (DAOs) that run on Blockchains without being subject to centralized control.<br><br>NFTs, DeFi, DAOs, and Blockchain-based games are all based on smart contracts.<br><br><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">This course</a> is a simple, low-friction introduction to creating your first smart contract using the Remix IDE on the Ethereum testnet &#8211; without fluff, significant upfront costs to purchase ETH, or unnecessary complexity.</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png" alt="" class="wp-image-37299" width="491" height="287" srcset="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png 982w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-300x175.png 300w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-768x448.png 768w" sizes="auto, (max-width: 491px) 100vw, 491px" /></a></figure></div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Brownie &#8211; Smart Contracts in Python</title>
		<link>https://blog.finxter.com/brownie-smart-contracts-in-python/</link>
		
		<dc:creator><![CDATA[Mikio Oba]]></dc:creator>
		<pubDate>Mon, 22 Nov 2021 19:26:10 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=49808</guid>

					<description><![CDATA[This is an introductory article to Brownie, a smart contract development and testing framework for Solidity and Vyper, especially with Python developers in mind.&#160; We first start with the installation process and then create a project with a simple smart contract. We will look at how to interact with the smart contract on a local ... <a title="Brownie &#8211; Smart Contracts in Python" class="read-more" href="https://blog.finxter.com/brownie-smart-contracts-in-python/" aria-label="Read more about Brownie &#8211; Smart Contracts in Python">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This is an introductory article to <a href="https://eth-brownie.readthedocs.io/en/stable/" target="_blank" rel="noreferrer noopener">Brownie</a>, a smart contract development and testing framework for <a href="https://blog.finxter.com/solidity/" data-type="post" data-id="37379" target="_blank" rel="noreferrer noopener">Solidity</a> and Vyper, especially with Python developers in mind.&nbsp;</p>



<p class="wp-block-paragraph">We first start with the installation process and then create a project with a simple smart contract. We will look at how to interact with the smart contract on a local blockchain using the built-in console. Finally, we will look at how to run a unit test.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Brownie - Smart Contracts in Python" width="937" height="527" src="https://www.youtube.com/embed/oqJrkrWaBdI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">What is Brownie?</h2>



<p class="wp-block-paragraph">Brownie is a popular smart contract development and testing framework for the Ethereum Virtual Machine, supporting Solidity and Vyper as the smart contract languages. </p>



<p class="wp-block-paragraph">It is Python-based, meaning that it uses various Python libraries, such as <a href="https://web3py.readthedocs.io/en/stable/" target="_blank" rel="noreferrer noopener"><strong>web3.py</strong></a> and <strong><a href="https://docs.pytest.org/" target="_blank" rel="noreferrer noopener">p</a></strong><a href="https://docs.pytest.org/"><strong>ytest</strong></a>, and uses Python to write scripts. It also has a built-in console similar to the Python interpreter to interact with smart contracts. </p>



<p class="wp-block-paragraph">All in all, if you are a Python developer and a fan of Pythonic style, you will probably feel more comfortable using Brownie than other JavaScript-based frameworks, such as <a href="https://trufflesuite.com/" target="_blank" rel="noreferrer noopener"><strong>Truffle</strong></a> or <a href="https://hardhat.org/" target="_blank" rel="noreferrer noopener"><strong>Hardhat</strong></a>.<br></p>



<h2 class="wp-block-heading">How to Install Brownie?</h2>



<p class="wp-block-paragraph">The <a href="https://eth-brownie.readthedocs.io/en/stable/install.html" target="_blank" rel="noreferrer noopener"><strong>Brownie documentation</strong></a> recommends to use <code>pipx</code> to install Brownie. So, let’s install <code>pipx</code> first unless you already have it on your machine.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ python3 -m pip install --user pipx
$ python3 -m pipx ensurepath</pre>



<p class="wp-block-paragraph">Then, install Brownie.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ pipx install eth-brownie
  installed package eth-brownie 1.17.1, Python 3.9.1
  These apps are now globally available
    - brownie
done! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2728.png" alt="✨" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f31f.png" alt="🌟" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2728.png" alt="✨" class="wp-smiley" style="height: 1em; max-height: 1em;" /></pre>



<p class="wp-block-paragraph">We can check that Brownie has been installed successfully by running the brownie command:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ brownie --version
Brownie v1.17.1 - Python development framework for Ethereum</pre>



<h2 class="wp-block-heading">How to use Brownie</h2>



<p class="wp-block-paragraph">In this section, we will look at Brownie’s basic functionality, such as:</p>



<ul class="wp-block-list"><li>Create a project from scratch</li><li>Use the console to interact with the smart contract</li><li>Run unit <a href="https://blog.finxter.com/pytest-a-complete-overview/" data-type="post" data-id="35477" target="_blank" rel="noreferrer noopener">tests&nbsp;</a></li></ul>



<h3 class="wp-block-heading">How to create a Brownie project</h3>



<p class="wp-block-paragraph">To create a project, run the command brownie init in an empty directory. Brownie has a template system called Brownie mixes, which we can use to create a project for specific purposes, such as ERC-20 token, <a href="https://blog.finxter.com/nft-101/" data-type="post" data-id="38160" target="_blank" rel="noreferrer noopener">NFT</a>, etc. But in this article, we will start from an empty project and create a very simple smart contract so that we can understand the basic functionality better.&nbsp;</p>



<p class="wp-block-paragraph">In the following example, we create a new directory called <code>brownie_test</code> in the home directory and run <code>brownie init</code> inside the new directory.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~]$ mkdir brownie_test
[~]$ cd brownie_test
[~/brownie_test]$ brownie init
Brownie v1.17.1 - Python development framework for Ethereum

SUCCESS: A new Brownie project has been initialized at /Users/mikio/brownie_test
</pre>



<p class="wp-block-paragraph">The command creates the default directory structure, as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ tree .
.
├── build
│   ├── contracts
│   ├── deployments
│   └── interfaces
├── contracts
├── interfaces
├── reports
├── scripts
└── tests
</pre>



<h3 class="wp-block-heading">How to compile a smart contract</h3>



<p class="wp-block-paragraph">First, we need a smart contract. Let’s take an example from the <a href="https://docs.soliditylang.org/en/v0.8.10/introduction-to-smart-contracts.html#storage-example" target="_blank" rel="noreferrer noopener"><strong>Solidity documentation</strong></a>. Save this smart contract in the contracts directory as <code>storage.sol</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 &lt;0.9.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }
}</pre>



<p class="wp-block-paragraph">We can run the brownie compile command to compile the smart contract.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie compile
Brownie v1.17.1 - Python development framework for Ethereum

Compiling contracts...
  Solc version: 0.8.10
  Optimizer: Enabled  Runs: 200
  EVM Version: Istanbul
Generating build data...
 - SimpleStorage

Project has been compiled. Build artifacts saved at /Users/mikio/brownie_test/build/contracts
</pre>



<p class="wp-block-paragraph">Please note the name of the smart contract (SimpleStorage) because we will need it in the next section.</p>



<p class="wp-block-paragraph">Brownie automatically compiles <a href="https://blog.finxter.com/introduction-to-web3-py/" data-type="post" data-id="38230" target="_blank" rel="noreferrer noopener">smart contracts</a> (if there are any changes) when starting the console or running tests, so we don’t usually need to run the brownie compile command unless we want to compile the code manually.</p>



<h3 class="wp-block-heading">How to use the Brownie console</h3>



<p class="wp-block-paragraph">Brownie offers the built-in console to interact with the local blockchain and smart contracts, like executing Python code using the Python interpreter.&nbsp;</p>



<p class="wp-block-paragraph">Let’s start the console by running the brownie console command.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie console
Brownie v1.17.1 - Python development framework for Ethereum

BrownieTestProject is the active project.

Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie'...
Brownie environment is ready.
>>>
</pre>



<p class="wp-block-paragraph">If you are a Python developer, the prompt <code>&gt;&gt;&gt;</code> should be familiar to you.&nbsp;</p>



<p class="wp-block-paragraph">In the command output, we can also see that it automatically starts a local blockchain (Ethereum simulator) using <a href="https://github.com/trufflesuite/ganache" target="_blank" rel="noreferrer noopener"><strong>Ganache CLI</strong></a>. It creates 10 test accounts by default, which we can access via the object accounts.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> accounts
[&lt;Account '0x66aB6D9362d4F35596279692F0251Db635165871'>, &lt;Account '0x33A4622B82D4c04a53e170c638B944ce27cffce3'>, &lt;Account '0x0063046686E46Dc6F15918b61AE2B121458534a5'>, &lt;Account '0x21b42413bA931038f35e7A5224FaDb065d297Ba3'>, &lt;Account '0x46C0a5326E643E4f71D3149d50B48216e174Ae84'>, &lt;Account '0x807c47A89F720fe4Ee9b8343c286Fc886f43191b'>, &lt;Account '0x844ec86426F076647A5362706a04570A5965473B'>, &lt;Account '0x23BB2Bb6c340D4C91cAa478EdF6593fC5c4a6d4B'>, &lt;Account '0xA868bC7c1AF08B8831795FAC946025557369F69C'>, &lt;Account '0x1CEE82EEd89Bd5Be5bf2507a92a755dcF1D8e8dc'>]</pre>



<p class="wp-block-paragraph">We can access each account just like a Python list. For example, the first account is <code>accounts[0]</code>, the second account is <code>accounts[1]</code>, etc.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> accounts[0]
&lt;Account '0x66aB6D9362d4F35596279692F0251Db635165871'>
>>> accounts[1]
&lt;Account '0x33A4622B82D4c04a53e170c638B944ce27cffce3'></pre>



<p class="wp-block-paragraph">We can see the Ether balance of each account by using the method balance() as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> accounts[0].balance()
100000000000000000000
>>> web3.fromWei(accounts[0].balance(), 'ether')
Decimal('100')</pre>



<p class="wp-block-paragraph">We can access the smart contract we compiled in the previous section by the smart contract name (<code>SimpleStorage</code>).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> SimpleStorage
[]</pre>



<p class="wp-block-paragraph">But to use this smart contract, we first need to deploy it using the deploy method. The following example uses the first account (<code>accounts[0]</code>) to deploy the smart contract.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage = SimpleStorage.deploy({'from': accounts[0]})
Transaction sent: 0xce078c4b3d092d945a56a9b3991e6c9a3a9b712e6ab88dafbcbfe03f1f714f99
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0
  SimpleStorage.constructor confirmed   Block: 1   Gas used: 90539 (0.75%)
  SimpleStorage deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87</pre>



<p class="wp-block-paragraph">The deploy method returns a <code>Contract</code> object.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage
&lt;SimpleStorage Contract '0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87'></pre>



<p class="wp-block-paragraph">We can now run the functions in the smart contract. For example, let’s call the function <code>get()</code> to check the current <code>storedData</code> value.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage.get()
0</pre>



<p class="wp-block-paragraph">Then, we can send a transaction to execute the function <code>set()</code> to update the <code>storedData</code> value, for example, to 5.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> tx = simple_storage.set(5)
Transaction sent: 0x74b1553a551c617d9c631fe4c92e0144faeaa8df426a38ab2980ac02231a26af
  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 1
  SimpleStorage.set confirmed   Block: 2   Gas used: 41394 (0.34%)</pre>



<p class="wp-block-paragraph">The return value is a <code>Transaction</code> object, and we can find more details using the method <code>info()</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> tx.info()
Transaction was Mined 
---------------------
Tx Hash: 0x74b1553a551c617d9c631fe4c92e0144faeaa8df426a38ab2980ac02231a26af
From: 0x66aB6D9362d4F35596279692F0251Db635165871
To: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87
Value: 0
Function: SimpleStorage.set
Block: 2
Gas Used: 41394 / 12000000 (0.3%)
</pre>



<p class="wp-block-paragraph">We can check the <code>storedData</code> value by calling the function <code>get()</code> again.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> simple_storage.get()
5</pre>



<p class="wp-block-paragraph">We can exit the console by running <code>quit()</code>, just like the Python interpreter.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> quit()
Terminating local RPC client...</pre>



<h3 class="wp-block-heading">How to run tests in Brownie</h3>



<p class="wp-block-paragraph">Brownie uses pytest to make <a href="https://blog.finxter.com/the-unix-philosophy/" data-type="post" data-id="19704" target="_blank" rel="noreferrer noopener">unit tests</a> more accessible. Let’s create a simple test file <code>test_storage.py</code> in the directory <code>tests</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># File: test_storage.py #

def test_storage(SimpleStoage, accounts):
    simple_storage = SimpleStorage.deploy({'from': accounts[0]})

    assert simple_storage.get() == 0
    simple_storage.set(5)
    assert simple_storage.get() == 5</pre>



<p class="wp-block-paragraph">The test file is a <code>pytest</code> file, which means the usual <code>pytest</code> conventions apply, such as:</p>



<ul class="wp-block-list"><li>The test file names start with <code>test_</code>&nbsp;</li><li>The test function names start with <code>test_</code>.&nbsp;</li><li>Assertions are done by the <code>assert</code> statement</li></ul>



<p class="wp-block-paragraph">Brownie automatically creates a fixture for our smart contract (<code>SimpleStorage</code>) and the account object (accounts). So, we can use them by specifying the fixture names (<code>SimpleStorage</code>, accounts) in the function arguments.</p>



<p class="wp-block-paragraph">If you’re not familiar with <code>pytest</code>, you might find the following articles helpful:</p>



<ul class="wp-block-list"><li><a href="https://blog.finxter.com/pytest-a-complete-overview/"><strong>Pytest – A Complete Overview</strong></a></li><li><a href="https://blog.finxter.com/how-to-use-pytest-fixtures/"><strong>How to Use Pytest Fixtures</strong></a></li></ul>



<p class="wp-block-paragraph">Then, we deploy the contract and execute the functions, as we did on the Brownie console in the previous section. In this test, we first assert that the <code>storedData</code> value is 0. Then, after setting the value to 5 by executing the function <code>set(5)</code>, assert that the value has been changed to 5.&nbsp;</p>



<p class="wp-block-paragraph">Now, go back to the console and run the command <code>brownie test</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie test   
Brownie v1.17.1 - Python development framework for Ethereum

==================== test session starts ====================
platform darwin -- Python 3.9.1, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: /Users/mikio/brownie_test
plugins: eth-brownie-1.17.1, web3-5.24.0, hypothesis-6.24.0, xdist-1.34.0, forked-1.3.0
collected 1 item                                            

Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie'...

tests/test_storage.py .                               [100%]

===================== 1 passed in 2.21s =====================
Terminating local RPC client...</pre>



<p class="wp-block-paragraph">We can see the <code>pytest</code> output, which shows that the test has passed. Like <code>pytest</code>, using the <code>-v</code> option adds more information to the output.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[~/brownie_test]$ brownie test -v
Brownie v1.17.1 - Python development framework for Ethereum

==================== test session starts ====================
platform darwin -- Python 3.9.1, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- /Users/mikio/.local/pipx/venvs/eth-brownie/bin/python
cachedir: .pytest_cache
hypothesis profile 'brownie-verbose' -> verbosity=2, deadline=None, max_examples=50, stateful_step_count=10, report_multiple_bugs=False, database=DirectoryBasedExampleDatabase(PosixPath('/Users/mikio/.brownie/hypothesis'))
rootdir: /Users/mikio/brownie_test
plugins: eth-brownie-1.17.1, web3-5.24.0, hypothesis-6.24.0, xdist-1.34.0, forked-1.3.0
collected 1 item                                            

Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie'...

tests/test_storage.py::test_storage PASSED            [100%]

===================== 1 passed in 2.33s =====================
Terminating local RPC client...
</pre>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this article, we looked at the basics of Brownie, a popular Python-based smart contract development and testing framework for Solidity and Vyper.</p>



<p class="wp-block-paragraph">We first looked at how to install Brownie and then created a new project from scratch. We then looked at how to interact with the smart contract on the local blockchain using the console. Finally, we leant how to run unit tests.</p>



<p class="wp-block-paragraph">The next step would be to deploy the smart contract to a public testnet, but it will be covered in a future article.&nbsp;</p>



<p class="wp-block-paragraph">I hope this article has been helpful to you. You can find more information about Brownie in the <a href="https://eth-brownie.readthedocs.io/en/stable/toctree.html" target="_blank" rel="noreferrer noopener"><strong>Brownie documentation</strong></a>.</p>



<hr class="wp-block-separator"/>






<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Smart Contract Developers Make $120,000 per Year on Upwork" width="937" height="527" src="https://www.youtube.com/embed/45vaWukF564?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">Learn Solidity Course</a></h2>



<p class="wp-block-paragraph">Solidity is the programming language of the future.</p>



<p class="wp-block-paragraph">It gives you the rare and sought-after superpower to program against the &#8220;Internet Computer&#8221;, i.e., against decentralized Blockchains such as <em>Ethereum</em>, <em>Binance Smart Chain</em>, <em>Ethereum Classic</em>, <em>Tron</em>, and <em>Avalanche </em>&#8211; to mention just a few Blockchain infrastructures that support Solidity.<br><br>In particular, Solidity allows you to<em> create smart contracts</em>, i.e., pieces of code that automatically execute on specific conditions in a completely decentralized environment. For example, smart contracts empower you to create your own <em>decentralized autonomous organizations</em> (DAOs) that run on Blockchains without being subject to centralized control.<br><br>NFTs, DeFi, DAOs, and Blockchain-based games are all based on smart contracts.<br><br><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">This course</a> is a simple, low-friction introduction to creating your first smart contract using the Remix IDE on the Ethereum testnet &#8211; without fluff, significant upfront costs to purchase ETH, or unnecessary complexity.</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png" alt="" class="wp-image-37299" width="491" height="287" srcset="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png 982w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-300x175.png 300w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-768x448.png 768w" sizes="auto, (max-width: 491px) 100vw, 491px" /></a></figure></div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Introduction to Web3.py</title>
		<link>https://blog.finxter.com/introduction-to-web3-py/</link>
		
		<dc:creator><![CDATA[Mikio Oba]]></dc:creator>
		<pubDate>Mon, 15 Nov 2021 16:51:29 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=38230</guid>

					<description><![CDATA[This article will give you a quick overview of a Python library, Web3.py. By the end of this article, we will install it on our local computer and understand how to use the basic functionality, such as sending Ether, deploying a Smart Contract, and interacting with it in Python. What is Web3.py? Web3.py is a ... <a title="Introduction to Web3.py" class="read-more" href="https://blog.finxter.com/introduction-to-web3-py/" aria-label="Read more about Introduction to Web3.py">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This article will give you a quick overview of a Python library, <a rel="noreferrer noopener" href="https://web3py.readthedocs.io/en/stable/index.html" target="_blank"><strong>Web3.py</strong></a>. By the end of this article, we will install it on our local computer and understand how to use the basic functionality, such as sending Ether, deploying a Smart Contract, and interacting with it in Python.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Introduction to Web3.py" width="937" height="527" src="https://www.youtube.com/embed/CSyqWMhVSF0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">What is Web3.py?</h2>



<p class="wp-block-paragraph">Web3.py is a Python library for interacting with Ethereum. Simply put, Ethereum is a collection of computers (or nodes) running specific software (or Ethereum client) communicating with each other over the Internet. Therefore, if we want to interact with Ethereum from our Python programs outside the Ethereum network, we need to connect to one of the Ethereum nodes first. Web3.py is a library to make it easy to connect to an Ethereum node and interact with the Ethereum network.&nbsp;</p>



<p class="wp-block-paragraph">There are several ways to connect to an Ethereum node using Web3.py, such as IPC (if an Ethereum node is running on the same machine), HTTP, or WebSocket. However, in this article, we will use a local Ethereum network provided by <a rel="noreferrer noopener" href="https://github.com/ethereum/eth-tester" target="_blank"><strong>eth-tester</strong></a>. It is basically a test stub designed for local development and testing purposes. It is integrated with Web3.py, so it is a good option for us to see how Web3.py works.</p>



<p class="wp-block-paragraph">We also use Jupyter Notebook in this article. It is probably not the best way to develop Web3 applications, but again it is a good option to explore Web3.py and demonstrate how it works.</p>



<h2 class="wp-block-heading">How to Install web3.py</h2>



<p class="wp-block-paragraph">Firstly create a virtual environment and install the following packages using <a href="https://blog.finxter.com/how-to-install-pip-on-windows/" data-type="post" data-id="21552" target="_blank" rel="noreferrer noopener">pip</a>.</p>



<ul class="wp-block-list"><li><code>jupyterlab</code> (Jupyter Notebook)</li><li><code>web3</code> (Web3.py and tester)</li><li><code>py-solc-x</code> (Python wrapper for the solc Solidity compiler)</li></ul>



<p class="wp-block-paragraph">Open a terminal and execute the following commands:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ mkdir web3py
$ cd web3py
$ python3 -m venv venv
$ source ./venv/bin/activate
(venv) $</pre>



<p class="wp-block-paragraph">Then, install the packages using pip as follows:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(venv) $ pip install -U pip
(venv) $ pip install jupyterlab
(venv) $ pip install web3
(venv) $ pip install "web3[tester]"
(venv) $ pip install py-solc-x
</pre>



<p class="wp-block-paragraph">Note that the version of Web3.py is downgraded when I install web3[tester] for some reason, so double-check the version:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(venv) $ pip list
...
web3                5.9.0
...
</pre>



<p class="wp-block-paragraph">If the version is not the latest (5.24 at the time of writing), try upgrading the library. In my environment, simply upgrading it seems to work fine.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(venv) $ pip install -U web3
(venv) $ pip list
...
web3                5.24.0
...
</pre>



<h2 class="wp-block-heading">How to Connect to a Local Ethereum Test Network</h2>



<p class="wp-block-paragraph">Start Jupyter Notebook by running the command below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(venv) $ jupyter notebook</pre>



<p class="wp-block-paragraph">The default web browser will automatically open the Jupyter notebook home page. Create a new notebook using the Python 3 kernel.&nbsp;</p>



<p class="wp-block-paragraph">As mentioned above, we will use a test Ethereum network running in the local environment for demonstration purposes. To connect to the local Ethereum network, we can use <code>Web3.EthereumTesterProvider()</code> as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from web3 import Web3
w3 = Web3(Web3.EthereumTesterProvider())
print(w3.isConnected())</pre>



<p class="wp-block-paragraph">If the connection is successful, we will get the following output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">True</pre>



<p class="wp-block-paragraph"><code>EthereumTesterProvider</code> creates 10 accounts, which we can use to interact with the network.</p>



<p class="wp-block-paragraph"><code><strong>w3.eth.accounts </strong></code></p>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">['0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',
 '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF',
 '0x6813Eb9362372EEF6200f3b1dbC3f819671cBA69',
 '0x1efF47bc3a10a45D4B230B5d10E37751FE6AA718',
 '0xe1AB8145F7E55DC933d51a18c793F901A3A0b276',
 '0xE57bFE9F44b819898F47BF37E5AF72a0783e1141',
 '0xd41c057fd1c78805AAC12B0A94a405c0461A6FBb',
 '0xF1F6619B38A98d6De0800F1DefC0a6399eB6d30C',
 '0xF7Edc8FA1eCc32967F827C9043FcAe6ba73afA5c',
 '0x4CCeBa2d7D2B4fdcE4304d3e09a1fea9fbEb1528']</pre>



<p class="wp-block-paragraph">We can check the Ether balance of each account by running <a href="https://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth.get_balance" target="_blank" rel="noreferrer noopener"><code>get_balance()</code></a>. The unit is <strong>wei</strong>, but we can convert it to <strong>ether</strong> by using the utility method <code><a href="https://web3py.readthedocs.io/en/stable/web3.main.html#web3.Web3.fromWei" target="_blank" rel="noreferrer noopener">fromWei()</a></code> if necessary, as shown below: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for account in w3.eth.accounts:
    balance = w3.eth.get_balance(account)
    print(f'Account: {account}, balance: {balance} wei = {w3.fromWei(balance, "ether")} ether')</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Account: 0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf, balance: 1000000000000000000000000 wei = 1000000 ether
Account: 0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF, balance: 1000000000000000000000000 wei = 1000000 ether
Account: 0x6813Eb9362372EEF6200f3b1dbC3f819671cBA69, balance: 1000000000000000000000000 wei = 1000000 ether
Account: 0x1efF47bc3a10a45D4B230B5d10E37751FE6AA718, balance: 1000000000000000000000000 wei = 1000000 ether
Account: 0xe1AB8145F7E55DC933d51a18c793F901A3A0b276, balance: 1000000000000000000000000 wei = 1000000 ether
Account: 0xE57bFE9F44b819898F47BF37E5AF72a0783e1141, balance: 1000000000000000000000000 wei = 1000000 ether
Account: 0xd41c057fd1c78805AAC12B0A94a405c0461A6FBb, balance: 1000000000000000000000000 wei = 1000000 ether
Account: 0xF1F6619B38A98d6De0800F1DefC0a6399eB6d30C, balance: 1000000000000000000000000 wei = 1000000 ether
Account: 0xF7Edc8FA1eCc32967F827C9043FcAe6ba73afA5c, balance: 1000000000000000000000000 wei = 1000000 ether
Account: 0x4CCeBa2d7D2B4fdcE4304d3e09a1fea9fbEb1528, balance: 1000000000000000000000000 wei = 1000000 ether
</pre>



<p class="wp-block-paragraph">As you can see, each test account has 1 million ether. These are not real Ether, so they are not worth anything in the real world (just in case you are wondering).</p>



<h2 class="wp-block-heading">How to send Ether</h2>



<p class="wp-block-paragraph">We can send Ether from one account to another by using the method <code><a rel="noreferrer noopener" href="https://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth.send_transaction" target="_blank">send_transaction()</a></code>. For example, the following code sends five ether from the first account (<code>accounts[0]</code>) to the second account (<code>accounts[1]</code>): </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">w3.eth.send_transaction({
    'from': w3.eth.accounts[0],
    'to': w3.eth.accounts[1],
    'value': w3.toWei(5, 'ether')
})
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">HexBytes('0x09e35f432cfd9cf4b4ba06a7c2d617e41f05eac2b1df5db550a9c63fe6d902c0')</pre>



<p class="wp-block-paragraph">The output is the transaction hash. We will use it to get more details about the transaction later, but first, we can confirm that the balances have been changed. The first account has five ether less than before and the second account has five ether more.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for account in w3.eth.accounts[0:2]:
    print(f'Account: {account}, balance: {w3.fromWei(w3.eth.get_balance(account), "ether")}')</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Account: 0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf, balance: 999994.999999999999979
Account: 0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF, balance: 1000005</pre>



<p class="wp-block-paragraph">The first account has slightly less than 999,995 ether (21,000 wei less, to be precise) because it paid the transaction fee (<strong>gas</strong>) when making the transaction. You can check the details of the transaction by the method <a href="https://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth.get_transaction_receipt" target="_blank" rel="noreferrer noopener"><code>get_transaction_receipt()</code></a> with the transaction hash returned by the method <code><a href="https://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth.send_transaction" target="_blank" rel="noreferrer noopener">send_transaction()</a></code> earlier in this section.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">w3.eth.get_transaction_receipt('0x09e35f432cfd9cf4b4ba06a7c2d617e41f05eac2b1df5db550a9c63fe6d902c0')</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">AttributeDict({'transactionHash': HexBytes('0x09e35f432cfd9cf4b4ba06a7c2d617e41f05eac2b1df5db550a9c63fe6d902c0'),
 'transactionIndex': 0,
 'blockNumber': 1,
 'blockHash': HexBytes('0xf9577944f63953f51e080917c07437adfa90a923518f323ca204db5c15b99c41'),
 'cumulativeGasUsed': 21000,
 'gasUsed': 21000,
 'contractAddress': None,
 'logs': [],
 'status': 1})</pre>



<p class="wp-block-paragraph">You can see that the <code>gasUsed</code> value is indeed 21000, which is the base fee for a transaction in Ethereum. In the test network, the gas price is set to 1 <strong>wei</strong> as shown below, so the total transaction fee was 21,000 <strong>wei</strong>.</p>



<p class="wp-block-paragraph"><code><strong>w3.eth.gas_price</strong></code></p>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1</pre>



<p class="wp-block-paragraph">You can find more about Ethereum’s gas in the following Finxter article:</p>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" target="_blank"><strong>Introduction to Ethereum’s Gas in Solidity Development</strong></a></li></ul>



<h2 class="wp-block-heading">How to Deploy a Smart Contract</h2>



<p class="wp-block-paragraph">Now let’s see how the Smart Contract deployment works using Web3.py. First, we need a Smart Contract. In this article, we will use a simple Smart Contract below, which I have taken from the <a href="https://docs.soliditylang.org/en/v0.8.9/introduction-to-smart-contracts.html" target="_blank" rel="noreferrer noopener"><strong>Solidity documentation</strong></a>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// storage.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 &lt;0.9.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }
}
</pre>



<p class="wp-block-paragraph">On Jupyter Notebook, create a new text file with the content above and save it as <code>storage.sol</code> in the same directory as the notebook.</p>



<p class="wp-block-paragraph">Then, go back to the notebook. Before deploying the Smart Contract, we need some preparations, such as setting up the compiler and compiling the Smart Contract. Let’s look at the steps one by one.</p>



<p class="wp-block-paragraph">Import the Solidity compiler <code>solcx</code> and install it:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import solcx
solcx.install_solc()
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Version('0.8.10')</pre>



<p class="wp-block-paragraph">Compile the Smart Contract <code>storage.sol</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">compiled_sol = solcx.compile_files(
    ['storage.sol'], 
    output_values=["abi", "bin"],
    solc_version='0.8.10'
)
contract_id, contract_interface = compiled_sol.popitem()
print(f'contract_id = {contract_id}')
print(f'contract_interface = {contract_interface}')
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract_id = storage.sol:SimpleStorage
contract_interface = {'abi': [{'inputs': [], 'name': 'get', 'outputs': [{'internalType': 'uint256', 'name': '', 'type': 'uint256'}], 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'internalType': 'uint256', 'name': 'x', 'type': 'uint256'}], 'name': 'set', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function'}], 'bin': '608060405234801561001057600080fd5b50610150806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c806360fe47b11461003b5780636d4ce63c14610057575b600080fd5b610055600480360381019061005091906100c3565b610075565b005b61005f61007f565b60405161006c91906100ff565b60405180910390f35b8060008190555050565b60008054905090565b600080fd5b6000819050919050565b6100a08161008d565b81146100ab57600080fd5b50565b6000813590506100bd81610097565b92915050565b6000602082840312156100d9576100d8610088565b5b60006100e7848285016100ae565b91505092915050565b6100f98161008d565b82525050565b600060208201905061011460008301846100f0565b9291505056fea2646970667358221220c742cec841ceedc32c9418a24f498eedbdaa8f7350de2a9f008b8f762a34fd4f64736f6c634300080a0033'}
</pre>



<p class="wp-block-paragraph">You can see the <strong>abi</strong> (Application Binary Interface) and <strong>bin</strong> (byte code) of the compiled code, which are used in the next step. </p>



<p class="wp-block-paragraph">Finally, we can deploy the Smart Contract by the method <code><a href="https://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth.contract" target="_blank" rel="noreferrer noopener">contract()</a></code>. When this method is called without specifying address, it will create a new Smart Contract.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tx_hash = w3.eth.contract(
    abi=contract_interface['abi'],
    bytecode=contract_interface['bin']
).constructor().transact()
</pre>



<p class="wp-block-paragraph">You can find the address of the deployed Smart Contract by looking up the transaction using the transaction hash returned by the <code>contract()</code> method: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">address = w3.eth.get_transaction_receipt(tx_hash)['contractAddress']
print(f'address = {address}')
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">address = 0xF2E246BB76DF876Cef8b38ae84130F4F55De395b</pre>



<h2 class="wp-block-heading">How to use a Smart Contract</h2>



<p class="wp-block-paragraph">Now that we have deployed the Smart Contract and got the address, we can create a contract object using the method <code><a rel="noreferrer noopener" href="https://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth.contract" target="_blank">contract()</a></code> with the address and abi as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract = w3.eth.contract(address=address, abi=contract_interface["abi"])</pre>



<p class="wp-block-paragraph">The Smart Contract has two functions, <code>get()</code> and <code>set()</code>. Let’s use <code><a href="https://web3py.readthedocs.io/en/stable/contracts.html#web3.contract.ContractFunction.call" target="_blank" rel="noreferrer noopener">call()</a></code> to execute the function <code>get()</code> and find the current value.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract.functions.get().call() </pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0</pre>



<p class="wp-block-paragraph">We can see that the current value is 0.&nbsp;</p>



<p class="wp-block-paragraph">Now let’s try the function <code>set()</code> to update the storage value from 0 to 100. As this function changes the state of the blockchain, we use the function <code><a href="https://web3py.readthedocs.io/en/stable/contracts.html#web3.contract.ContractFunction.transact" target="_blank" rel="noreferrer noopener">transact()</a></code>, which will send a new transaction.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tx_hash = contract.functions.set(100).transact()
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print(receipt)
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">AttributeDict({'transactionHash': HexBytes('0xeeb66d2757938585cf52c4cd215d4f4f3c6bb7cc72bde6a3f495e68f68811288'), 'transactionIndex': 0, 'blockNumber': 2, 'blockHash': HexBytes('0x07afe70cd6221e58be98eedbd28702fc108f6725f2855687f1870a70c08b8a6a'), 'cumulativeGasUsed': 41862, 'gasUsed': 41862, 'contractAddress': None, 'logs': [], 'status': 1})</pre>



<p class="wp-block-paragraph">The function finished successfully (status = 1). We can check the stored value by running the function <code>get()</code> again.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">contract.functions.get().call()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">100</pre>



<p class="wp-block-paragraph">We can confirm that the value has been updated to 100.</p>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this article, we looked at the basic functionality of Web3.py, a Python library for interacting with Ethereum.&nbsp;</p>



<p class="wp-block-paragraph">Firstly, we installed <code>web3.py</code> and the related packages and set up the environment. Then, we connected to the local test Ethereum network, explored the accounts and balances, and sent some Ether from one account to another.</p>



<p class="wp-block-paragraph">Lastly, we compiled a Smart Contract, deployed it to the local test Ethereum network, and executed the functions in the Smart Contract.&nbsp;</p>



<p class="wp-block-paragraph">I hope this article has been a helpful introduction to Web3.py. You can find more about <code>Web3.py</code> in the <a href="https://web3py.readthedocs.io/en/stable/index.html" target="_blank" rel="noreferrer noopener"><strong>Web3.py documentation</strong></a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Use FTX REST API in Python</title>
		<link>https://blog.finxter.com/how-to-use-ftx-rest-api-in-python/</link>
		
		<dc:creator><![CDATA[Mikio Oba]]></dc:creator>
		<pubDate>Mon, 08 Nov 2021 07:21:23 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Bitcoin]]></category>
		<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Investment]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=37782</guid>

					<description><![CDATA[This article explains how to use the REST API to access FTX in Python so that you can build your trading program. As you go through the article, you can also watch our article tutorial video: What is FTX? FTX is an exchange where users can trade various digital assets, such as cryptocurrencies, tokenised stocks ... <a title="How to Use FTX REST API in Python" class="read-more" href="https://blog.finxter.com/how-to-use-ftx-rest-api-in-python/" aria-label="Read more about How to Use FTX REST API in Python">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This article explains how to use the REST API to access FTX in Python so that you can build your trading program. As you go through the article, you can also watch our article tutorial video:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Use FTX REST API in Python" width="937" height="527" src="https://www.youtube.com/embed/PxysVcWXI_Q?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">What is FTX?</h2>



<p class="wp-block-paragraph"><a href="https://ftx.com/" target="_blank" rel="noreferrer noopener"><strong>FTX</strong></a> is an exchange where users can trade various digital assets, such as cryptocurrencies, tokenised stocks and derivatives. Founded in 2019, it is a relatively new exchange, but it is ranked as the third top cryptocurrency spot exchange after Binance and Coinbase on <a href="https://coinmarketcap.com/rankings/exchanges/" target="_blank" rel="noreferrer noopener"><strong>CoinMarketCap</strong></a> at the time of writing.&nbsp;</p>



<p class="wp-block-paragraph">When it comes to trading cryptocurrencies, it is no doubt that decentralised exchange (DEX) and decentralised finance (DeFi) will be the future. But central exchanges such as Binance, Coinbase and FTX are still heavily used, especially for fiat on- and off-ramps (converting fiat currencies into cryptocurrencies and visa versa). FTX provides a well-documented API (REST, web socket and FIX) and low trading fees, making it an excellent platform for algorithmic traders. In addition, it publishes a <a href="https://github.com/ftexchange/ftx/blob/master/rest/client.py" target="_blank" rel="noreferrer noopener"><strong>sample client code</strong></a> on Github to use the REST API in Python, so it is straightforward to build trading programs in Python.&nbsp;</p>



<p class="wp-block-paragraph">Please note that, depending on where you reside, FTX service might not be available. Please see the details on <a href="https://help.ftx.com/hc/en-us/articles/360042412652-Location-Restrictions-" target="_blank" rel="noreferrer noopener"><strong>ftx.com</strong></a>. Also, this article does not explain any trading algorithms or strategies. If you are interested in learning algorithmic trading strategies, the following course on Fixter Academy might be of interest to you.</p>



<p class="wp-block-paragraph"><strong><a href="https://academy.finxter.com/university/binance-trading-api-advanced-trading/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/binance-trading-api-advanced-trading/">Binance Trading API &#8211; Mastering Trading Strategies</a></strong></p>



<h2 class="wp-block-heading">How to set up the environment</h2>



<h3 class="wp-block-heading">Set up the Python environment</h3>



<p class="wp-block-paragraph">In this article, we will use Jupyter Notebook to explore the REST APIs. We’ll also use some packages, such as <a href="https://blog.finxter.com/pandas-quickstart/" target="_blank" rel="noreferrer noopener" title="10 Minutes to Pandas (in 5 Minutes)">Pandas </a>and <a href="https://plotly.com/" target="_blank" rel="noreferrer noopener"><strong>Plotly</strong></a>, so let’s set up the environment first.</p>



<p class="wp-block-paragraph">Go to the terminal and create a <a href="https://blog.finxter.com/python-virtual-environments-with-venv-a-step-by-step-guide/" target="_blank" rel="noreferrer noopener" title="Python Virtual Environment “venv” Cheat Sheet">virtual environment</a> first and activate it.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ mkdir ftx
$ cd ftx
$ python3 -m venv venv
$ source ./venv/bin/activate</pre>



<p class="wp-block-paragraph">Then install necessary packages.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(venv) $ pip install -U pip
(venv) $ pip install jupyter
(venv) $ pip intall pandas plotly python-dotenv requests ciso8601
</pre>



<p class="wp-block-paragraph">Create a file called “.env” with the content below in the current directory, which we will update in the next section.</p>



<p class="wp-block-paragraph"><strong>File</strong> <code>.env</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">FTX_API_KEY=
FTX_API_SECRET=
</pre>



<h3 class="wp-block-heading"><strong>Set up the API Key</strong></h3>



<p class="wp-block-paragraph">To use the FTX API, you need to create a free account on <a href="https://ftx.com/" target="_blank" rel="noreferrer noopener"><strong>ftx.com</strong></a>. Click on the REGISTER button on the top right-hand corner and fill in the necessary information.&nbsp;</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/X8fmT8qjR_Yxu-B4ob4DCDHVsRi2Fm6KXzKEYoV8Cm7fxvYDRWqrJevgUvQBI_TIm_j0pr0hAeYy8sfGyug3yTw5Go3ztdzXPoucPHiFvaXCXDJURCkePgtOwuvKN8535krox8z7" alt=""/></figure>
</div>


<p class="wp-block-paragraph">Creating an account is straightforward, but you must go through the KYC process (identify verification) before starting trading. Please see more detail on the help page below:</p>



<p class="wp-block-paragraph"><a href="https://help.ftx.com/hc/en-us/articles/360027668192-Individual-Account-KYC" target="_blank" rel="noreferrer noopener"><strong>Individual Account KYC</strong></a></p>



<p class="wp-block-paragraph">Once you’ve created your account, go to the account settings page and select “Api” on the left-hand side menu.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://lh3.googleusercontent.com/nDwi6h_33uwwFr5H2TWvzk2Pn6MOavWxHsgzvByvW0FfWUirlpNoCp9sFP13hpN_HhpVO0iaDT737lwKUnKpZhEihg0qk64YAkzhoL4mabe8XXtwisqkmkw4nKOnZ7ohIlK81ytk" alt=""/></figure>
</div>


<p class="wp-block-paragraph">Click on the “CREATE API KEY” button. New API Key and API Secret are shown. Open the file “.env”, which we created in the previous section and copy and paste the API Key and API Secret values, respectively.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/HBt_H7GKWXdinLNVJBzRDViAfiNmRcrGt9t1dUBGWRkj2qXkhPO9wHeT3sXKestMsZsyum6GmGTDIIghG4Yb5x3tA17-28qq_LX9dshz879R1iVOprYTkGnksBhjWoiHWj1QKc5f" alt=""/></figure>
</div>


<p class="wp-block-paragraph"><code>.env</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">FTX_API_KEY=Os2HGy3D...
FTX_API_SECRET=uRr2aKYw...</pre>



<p class="wp-block-paragraph">After checking that the values are correctly saved in the file .env, close the API key pane.</p>



<h3 class="wp-block-heading">Get the Python client sample code</h3>



<p class="wp-block-paragraph">FTX publishes sample code to access APIs using Python, C++ and Go on <a href="https://github.com/ftexchange/ftx" target="_blank" rel="noreferrer noopener"><strong>their Github repository</strong></a>. We are going to use the Python REST API client sample code in this article for demonstration purposes.</p>



<p class="wp-block-paragraph">Copy the file <a href="https://github.com/ftexchange/ftx/blob/master/rest/client.py" target="_blank" rel="noreferrer noopener">client.py</a> to the current directory as client.py.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(venv) $ curl https://raw.githubusercontent.com/ftexchange/ftx/master/rest/client.py -o client.py</pre>



<p class="wp-block-paragraph">Alternatively, you can click the “Copy raw contents” to copy the file content to the clipboard, create a new local file <code>client.py</code> and paste the contents from the clipboard.&nbsp;</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/N0VoWdQq51XngIgtK71Uu4QVRddFsUt4NDQlfxw3BceowGjFq73Nfea1aOR6OQgapfj_MvLzW-T_VbmgWrCv5BkYYpswh9gjk72L5wbpanjwPVRabkHYh0tWOR3-0sEbXFuENzXl" alt=""/></figure>
</div>


<h2 class="wp-block-heading">How to get data using the FTX REST API</h2>



<p class="wp-block-paragraph">Now we’re ready to start using the REST API. First, start the <a href="https://blog.finxter.com/how-to-install-jupyter-notebook-on-pycharm/" target="_blank" rel="noreferrer noopener" title="How to Install Jupyter Notebook on PyCharm">Jupyter Notebook</a> from the terminal.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(venv) $ jupyter notebook</pre>



<p class="wp-block-paragraph">Your default web browser will automatically open the Jupyter notebook home page, but if it doesn’t, open the URL shown in the Jupyter notebook command logs.&nbsp;</p>



<p class="wp-block-paragraph">Create a new notebook on the Jupyter notebook home page by clicking the “New” button on the top right corner and selecting “Python3” from the drop-down menu.&nbsp;</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/BHJzIouEd2lYU933aKrrcDr-5ELc6PdVY4pe8cd1oUMwVp6cQtCVMd0dmaqdZweEfiwBa5ebzgC5ZgX8o4Nhdo3UtKsYAeBYwAFi7bdoHO5qd5VqYrO6YwOVxg6_2wROkCph9zyB" alt=""/></figure>
</div>


<p class="wp-block-paragraph">On the new notebook, let’s import the necessary packages and load the environment variables in the file <code>.env</code>, which we created in the previous section.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from datetime import datetime
from dotenv import load_dotenv
import os
import json
import pandas as pd
import plotly.graph_objects as go
import requests
import time

from client import FtxClient

load_dotenv()
</pre>



<p class="wp-block-paragraph">We will use the environment variables later when we create a <code>FtxClient</code> instance.</p>



<h3 class="wp-block-heading">Get all market data</h3>



<p class="wp-block-paragraph">You can get all market data as shown below. Just getting market data does not require an account on FTX.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">endpoint_url = 'https://ftx.com/api/markets'

# Get all market data as JSON
all_markets = requests.get(endpoint_url).json()

# Convert JSON to Pandas DataFrame
df = pd.DataFrame(all_markets['result'])
df.set_index('name', inplace = True)
</pre>



<p class="wp-block-paragraph">This is how the DataFrame <code>df</code> looks:</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/ltTW3W_bdZxttKQS67Xt1UoNvzengw6a44scmTbgeLYdsxvm_HO8XT85D-I9f57yrpk8JP-zE34fA3kPFmmkGkW7zk7YaKM6aa_txceY3iRe0V1dZwuPCxXbzqoj9kr7skfBN-hW" alt=""/></figure>
</div>


<p class="wp-block-paragraph">For the details of the response format, please see the <a href="https://docs.ftx.com/#get-markets" target="_blank" rel="noreferrer noopener"><strong>API doc &#8211; Get markets</strong></a>.&nbsp;</p>



<h3 class="wp-block-heading">Get single market data</h3>



<p class="wp-block-paragraph">You can also get single market data. The following is an example to get BTC/USD (spot) market data.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">base_currency = 'BTC'
quote_currency = 'USD'

# Specify the base and quote currencies to get single market data
request_url = f'{endpoint_url}/{base_currency}/{quote_currency}'

df = pd.DataFrame(requests.get(request_url).json())
df['result']</pre>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://lh6.googleusercontent.com/JivXZwO5-5DhWYT0b2Tky01T-K_YIN_R4Vd19HbnLZMawaOMrbBNyCuZT4cU0fXNibu-hlbEDUv3Bvs3uKeLPLAk4_oLy_1E8qiSaGS7M3ZNjLONXRn3ztTdhEp2mUVINGi33pKO" alt=""/></figure>
</div>


<h3 class="wp-block-heading">Get historical data</h3>



<p class="wp-block-paragraph">You can get historical data using the GET request. The following is an example to get daily BTC/USD market data since 2021-01-01.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 1 day = 60 * 60 * 24 seconds
daily=str(60*60*24)

# Start date = 2021-01-01
start_date = datetime(2021, 1, 1).timestamp()

# Get the historical market data as JSON
historical = requests.get(
    f'{request_url}/candles?resolution={daily}&amp;start_time={start_date}'
).json()

# Convert JSON to Pandas DataFrame
df = pd.DataFrame(historical['result'])

# Convert time to date
df['date'] = pd.to_datetime(
    df['time']/1000, unit='s', origin='unix'
) 

# Remove unnecessar columns
df.drop(['startTime', 'time'], axis=1, inplace=True)
df
</pre>



<p class="wp-block-paragraph">For the details, please see the <a href="https://docs.ftx.com/#get-historical-prices" target="_blank" rel="noreferrer noopener"><strong>API doc &#8211; Get historical prices</strong></a>.&nbsp;</p>



<h3 class="wp-block-heading"><strong>Plot the historical data</strong></h3>



<p class="wp-block-paragraph">This step is optional, but it is usually helpful to plot the historical data when analysing it. The following is an example to use <strong><a href="https://plotly.com/python/candlestick-charts/" target="_blank" rel="noreferrer noopener">P</a></strong><a href="https://plotly.com/python/candlestick-charts/"><strong>lotly</strong></a> to create a candlestick chart, which is commonly used to visualise price movement in the financial markets.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fig = go.Figure()

fig.update_layout(
    title={
        'text': f"{base_currency}/{quote_currency}",
        'x':0.5,
        'xanchor': 'center'
    },
    xaxis_title="Date",
    yaxis_title="Price",
    xaxis_rangeslider_visible=False
)

fig.add_trace(
    go.Candlestick(
        x=df['date'],
        open=df['open'],
        high=df['high'],
        low=df['low'],
        close=df['close']
    )
)
fig.show()
</pre>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/vM2MbnsU80lBjsmaV-v1eqMJVa9mHMQLANnIO2LIpmf_2JT2dJVrnZBFqd9gHrH2LKp4RVfIa470YWyduf0ko2otlaKlSJnBlf6-yMqqPS3S41KkjlFyluzKeBGCB9Ye0WgEStDO" alt=""/></figure>
</div>


<h2 class="wp-block-heading">How to trade using the FTX REST API</h2>



<p class="wp-block-paragraph">To trade on FTX, we need an account and perform the authentication using our API Key and API Secret. <a href="https://blog.ftx.com/blog/api-authentication/" target="_blank" rel="noreferrer noopener"><strong>This process can be tedious</strong></a>, but thanks to the sample code FTX has provided, we don’t need to code the logic ourselves.&nbsp;</p>



<p class="wp-block-paragraph">In the <em><strong>“How to set up the environment”</strong></em> section above, we created API Key and API Secret and saved them in the local file <code>.env</code>. Then, we have already loaded the values using <code>python-dotenv</code>’ s <code>load_dotenv()</code> in the example above, so we can access them using the <code>os.getenv()</code> function.</p>



<p class="wp-block-paragraph">We only need to pass these two values as arguments to create a client, as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ftx_client = FtxClient(
    api_key=os.getenv("FTX_API_KEY"), 
    api_secret=os.getenv("FTX_API_SECRET")
)
</pre>



<p class="wp-block-paragraph">You will need to deposit some funds into your account in advance to buy some assets.</p>



<h3 class="wp-block-heading">Place an order</h3>



<p class="wp-block-paragraph">You can place an order using the <code>place_order()</code> function in the sample code. The following is an example of placing a limit order to buy 0.0001 BTC at 90% of the current price.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Get the current price
market = requests.get(request_url).json()
market_ask = market['result']['ask']
print(f"{base_currency}/{quote_currency} asking price = {market_ask}")

# Place an order
try:
    bo_result = ftx_client.place_order(
        market=f"{base_currency}/{quote_currency}", 
        side="buy",
        price=market_ask*0.9,
        size=0.0001
    )
    print(bo_result)
except Exception as e:
    print(f'Error making order request: {e}')
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">BTC/USD asking price = 61865.0
{'id': 94071380298, 'clientId': None, 'market': 'BTC/USD', 'type': 'limit', 'side': 'buy', 'price': 55678.0, 'size': 0.0001, 'status': 'new', 'filledSize': 0.0, 'remainingSize': 0.0001, 'reduceOnly': False, 'liquidation': None, 'avgFillPrice': None, 'postOnly': False, 'ioc': False, 'createdAt': '2021-11-07T13:21:42.937268+00:00', 'future': None}
</pre>



<h3 class="wp-block-heading">Cancel an order</h3>



<p class="wp-block-paragraph">You can cancel the order you’ve just made by specifying the order ID as shown below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">try:
    co_result = ftx_client.cancel_order(
        order_id=bo_result['id']
    )
    print(co_result)
except Exception as e:
    print(f'Error cancelling order request: {e}')
</pre>



<p class="wp-block-paragraph">If the order has not been filled yet, you should get the following message:</p>



<pre class="wp-block-preformatted">Order queued for cancellation</pre>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph"><a href="https://ftx.com/" target="_blank" rel="noreferrer noopener"><strong>FTX</strong></a> is one of the largest exchanges, where users can trade various digital assets, such as cryptocurrencies, tokenised stocks and derivatives. It provides a well-documented API (REST, web socket and FIX) and low trading fees, making it an excellent platform for algorithmic traders. In addition, it publishes a <a href="https://github.com/ftexchange/ftx/blob/master/rest/client.py" target="_blank" rel="noreferrer noopener"><strong>sample client code</strong></a> on Github to use the REST API in Python, so it is straightforward to build trading programs in Python.&nbsp;</p>



<p class="wp-block-paragraph">In this article, we looked at:</p>



<ul class="wp-block-list"><li>how to get current and historical market data</li><li>how to create a candlestick chart</li><li>how to place an order</li><li>how to cancel an order</li></ul>



<p class="wp-block-paragraph">I hope this article has helped you to get started with trading on FTX in Python. You can find more information about the API on <a rel="noreferrer noopener" href="https://docs.ftx.com/#overview" target="_blank"><strong>the API documentation</strong></a>. </p>



<h2 class="wp-block-heading">Programmer Humor</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><a href="https://imgs.xkcd.com/comics/computers_vs_humans.png" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-163.png" alt="" class="wp-image-435467" width="578" height="282" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-163.png 578w, https://blog.finxter.com/wp-content/uploads/2022/06/image-163-300x146.png 300w" sizes="auto, (max-width: 578px) 100vw, 578px" /></a><figcaption><em>It&#8217;s hard to train deep learning algorithms when most of the positive feedback they get is sarcastic.</em> &#8212; from <a href="https://imgs.xkcd.com/comics/computers_vs_humans.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/computers_vs_humans.png" target="_blank" rel="noreferrer noopener">xkcd</a></figcaption></figure>
</div>


<h2 class="wp-block-heading">Related Course</h2>



<p class="wp-block-paragraph">To boost your understanding of cryptocurrency trading, you may also want to check out our crypto trading bot courses on the <a href="https://academy.finxter.com/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/">Finxter Computer Science Academy</a>:</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-8f761849 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow"><div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://academy.finxter.com/university/binance-trading-api-advanced-trading/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="389" height="633" src="https://blog.finxter.com/wp-content/uploads/2021/11/image-9.png" alt="" class="wp-image-37791" srcset="https://blog.finxter.com/wp-content/uploads/2021/11/image-9.png 389w, https://blog.finxter.com/wp-content/uploads/2021/11/image-9-184x300.png 184w" sizes="auto, (max-width: 389px) 100vw, 389px" /></a><figcaption><a href="https://academy.finxter.com/university/binance-trading-api-advanced-trading/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/binance-trading-api-advanced-trading/">Binance Trading API &#8211; Mastering Trading Strategies</a></figcaption></figure>
</div></div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow"><div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://academy.finxter.com/university/binance-trading-api-creating-your-first-simple-crypto-trading-bot/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="363" height="650" src="https://blog.finxter.com/wp-content/uploads/2021/11/image-10.png" alt="" class="wp-image-37792" srcset="https://blog.finxter.com/wp-content/uploads/2021/11/image-10.png 363w, https://blog.finxter.com/wp-content/uploads/2021/11/image-10-168x300.png 168w" sizes="auto, (max-width: 363px) 100vw, 363px" /></a><figcaption><a href="https://academy.finxter.com/university/binance-trading-api-creating-your-first-simple-crypto-trading-bot/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/binance-trading-api-creating-your-first-simple-crypto-trading-bot/">Binance Trading API &#8211; Creating Your First Simple Crypto-Trading Bot</a></figcaption></figure>
</div></div>
</div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Introduction to Ethereum&#8217;s Gas in Solidity Development</title>
		<link>https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/</link>
		
		<dc:creator><![CDATA[Mikio Oba]]></dc:creator>
		<pubDate>Tue, 02 Nov 2021 09:31:56 +0000</pubDate>
				<category><![CDATA[Crypto]]></category>
		<category><![CDATA[Error]]></category>
		<category><![CDATA[Ethereum]]></category>
		<category><![CDATA[Solidity]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=37644</guid>

					<description><![CDATA[This article explains the concept of gas in Ethereum and the basics you need to know when developing smart contracts in Solidity. What is Gas in Ethereum? In Ethereum, we have to pay for each computational operation, measured in the unit called gas. In the Ethereum documentation, gas is defined as follows: &#8220;Gas refers to ... <a title="Introduction to Ethereum&#8217;s Gas in Solidity Development" class="read-more" href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" aria-label="Read more about Introduction to Ethereum&#8217;s Gas in Solidity Development">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This article explains the concept of <strong><em>gas </em></strong>in Ethereum and the basics you need to know when<strong><em> developing smart contracts</em></strong> in <a href="https://blog.finxter.com/solidity/" target="_blank" rel="noreferrer noopener" title="Solidity Crash Course – Your First Smart Contract on Ethereum">Solidity</a>.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Introduction to Gas in Solidity Development" width="937" height="527" src="https://www.youtube.com/embed/jfLxyuMz8f8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">What is Gas in Ethereum?</h2>



<p class="wp-block-paragraph">In Ethereum, we have to pay for each computational operation, measured in the unit called gas.</p>



<p class="wp-block-paragraph">In the Ethereum documentation, gas is defined as follows:</p>



<p class="wp-block-paragraph"><em>&#8220;Gas refers to the unit that measures the amount of computational effort required to execute specific operations on the Ethereum network.</em></p>



<p class="wp-block-paragraph"><em>Since each Ethereum transaction requires computational resources to execute, each transaction requires a fee. Gas refers to the fee required to conduct a transaction on Ethereum successfully.&#8221;</em> &#8211; <strong>Source</strong>: <a href="https://ethereum.org/en/developers/docs/gas/#what-is-gas" target="_blank" rel="noreferrer noopener"><strong><em>What is gas?</em></strong></a></p>



<p class="wp-block-paragraph">To understand what gas precisely is, let&#8217;s zoom out and take a quick look at Ethereum transaction fees.</p>



<h3 class="wp-block-heading">Ethereum transaction fees</h3>



<p class="wp-block-paragraph">Back in the old days (the 1960s or 70s), people were sharing computers due to the high cost of computer resources and were very conscious of the cost of computational operations. Then, the development of personal computers made computer resources much more accessible, and people no longer think about the cost much except when there are strict resource constraints.&nbsp;</p>



<p class="wp-block-paragraph">The <em><strong>Ethereum Virtual Machine</strong></em> is a shared computer across the Ethereum network, so we have to think about how efficiently we can use the resources like in the old days. But instead of using time-sharing systems, Ethereum uses transaction fees due to the distributed nature of its execution environment. </p>



<p class="wp-block-paragraph">The following formula calculates transaction fees:</p>



<pre class="wp-block-preformatted">Gas units * Gas price</pre>



<p class="wp-block-paragraph">The first term of the formula is the total cost of the computational operations measured in the unit called gas. How much gas each operation consumes is defined in the Ethereum Yellow Paper (Appendix G. Fee Schedule). Still, when sending a transaction, we don&#8217;t usually know the exact cost of the operations in advance. So, we (the sender) pay the maximum amount of gas we are willing to pay for the transaction upfront, called the gas limit. After the transaction finishes, the remaining balance (gas limit &#8211; actual gas used) is returned to the sender. It is like buying a pre-paid card before making a telephone call. Ethereum will deduct the actual amount of gas from the gas limit, execute the transaction and then return the remaining balance to the sender.</p>



<p class="wp-block-paragraph">The second term of the formula is the price of gas in ether (ETH), or more precisely in a fraction of ether called <strong><em>gwei</em></strong>, which is equal to <strong><em>0.000000001 ETH</em></strong> (one billionth ETH). The gas price fluctuates primarily depending on the Ethereum network utilization. The way to calculate the price itself sometimes changes as well. For example, there was a significant change in August 2021 when the <em>London Upgrade</em> was implemented. You can find all the details in the <a href="https://ethereum.org/en/developers/docs/gas/#post-london" target="_blank" rel="noreferrer noopener"><strong>Ethereum documentation</strong></a>.</p>



<p class="wp-block-paragraph">The rest of the article focuses on the first term of the formula (Gas units) to understand the basics of gas when implementing smart contracts in Solidity.</p>



<h2 class="wp-block-heading">Basics of gas in Solidity development</h2>



<h3 class="wp-block-heading">The opcode fee schedule</h3>



<p class="wp-block-paragraph">As mentioned in the previous section, the cost of each operation is defined in the <a href="https://ethereum.github.io/yellowpaper/paper.pdf" target="_blank" rel="noreferrer noopener"><strong>Ethereum Yellow Paper (Appendix G. Fee Schedule)</strong></a>. However, it is not straightforward to know precisely how many gas units our Solidity code costs. The gas units are based on <a href="https://www.ethervm.io/" target="_blank" rel="noreferrer noopener"><strong>Ethereum Virtual Machine opcodes</strong></a>, which are generated by the Solidity compiler. So, the cost will depend on how the compiler generates opcodes from our Solidity code.</p>



<p class="wp-block-paragraph">It is nonetheless helpful to know the cost of some of the frequently used operations. For example,</p>



<ul class="wp-block-list"><li>Every transaction costs at least 21,000 gas (&#8220;base fee&#8221;).</li><li>Each CREATE operation (creating a smart contract) costs 32,000 gas.</li><li>Each SSTORE operation (writing a uint256 value to storage) costs as follows:<ul><li>20,000 gas when the storage value is set from zero to a non-zero value</li><li>5,000 gas when the storage value is set from zero to zero or a non-zero to a non-zero value</li></ul></li><li>Each CALL operation with a non-zero value costs 9,000 gas, in which 2,300 gas is given to the recipient.&nbsp;</li></ul>



<h3 class="wp-block-heading">How do you estimate gas on Remix IDE?</h3>



<p class="wp-block-paragraph">The <a href="https://blog.finxter.com/solidity/" target="_blank" rel="noreferrer noopener" title="Solidity Crash Course – Your First Smart Contract on Ethereum">Remix IDE</a> can indicate the gas estimation wherever possible. After compiling the code, click on the function name on the editor. At the bottom of the editor, we can see the Execution code in gas.</p>



<p class="wp-block-paragraph">The following is an example of a simple smart contract to set a value and make it accessible to other smart contracts.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 &lt;0.9.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }
}
</pre>



<p class="wp-block-paragraph">(<a href="https://docs.soliditylang.org/en/latest/introduction-to-smart-contracts.html"><strong>Storage Example</strong></a>)</p>



<p class="wp-block-paragraph">The function <code>get()</code> reads a value from the storage (<code>storeData</code>). The following screenshot shows that the estimated total cost of the function is 2,437 gas, which more or less matches the cost of storage access (2,100 gas).</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh3.googleusercontent.com/N4TiXOe-TXMSWxPtPh5lNjrbI2Tncyh0-_BpGgtCYYzrbfBKOlTJOOT81_YEOHiBg2FHk8VCR36kZzDIEgPnqOtDIwT54AvJxzNqxrge-tZS52NUxKJuWnLosAwK0JVm6rxaEgrJ" alt=""/></figure></div>



<p class="wp-block-paragraph">On the other hand, the function <code>set()</code> sets a value to the storage, so the estimated cost of the function is 22,498 gas. Again we can see that it more or less matches the cost of operation to set a non-zero value to storage (20,000 gas)</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/8QRsEtR_vZh5a65P-BXwz8vtE5cDEQb-BgBojxCLiS4jnmNjo888RDmgdwgV5LQ5tgZ_6Vmb_dwszaDL9LrK81j_fKfEctWGRiDJYNbohl3fMPVvdLeYB2WY9D95uFMzy4jU3scV" alt=""/></figure></div>



<h3 class="wp-block-heading">How do you see execution cost on Remix IDE?</h3>



<p class="wp-block-paragraph">In real-world situations, you would interact with the Ethereum network using <a href="https://not-satoshi.com/setup-polygon-metamask/" target="_blank" rel="noreferrer noopener" title="https://not-satoshi.com/setup-polygon-metamask/">MetaMask </a>or other web3 interfaces. Still, you can see how much gas your code would cost by executing it using JavaScript VM on Remix IDE. </p>



<p class="wp-block-paragraph">When we deploy the contract and execute the function <code>get()</code>, we see the execution cost in the console output.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/krXGSo3ch784gJnaGvlJPy8A7pXSQ-QH_NvF6AInCRy2y6d-x3BIJ9HdmD4waCV_DB7mEQJS_fAyf3PU8fwy-2vGqa-lCoqDKRSuOh-2jvXUiGPRtGJ7WphA5G5YJAEXRmW7gZbT" alt=""/></figure></div>



<p class="wp-block-paragraph">It shows the cost was 23,501 gas. It is because every transaction costs the base fee of 21,000 gas. If we add 21,000 gas to the estimated cost of 2,437 gas, we get 23,437 gas, which is close to the actual execution cost above.</p>



<p class="wp-block-paragraph">When we run the function <code>set()</code>, we see the execution cost below.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh4.googleusercontent.com/P1a9zrrekpy7_LdVRX0L-j5wifGv6324CNxK47-l5HIk7J1n7mpZQHNYk9SQv3khZ3qKIyIzC7y_srEnsgOpaLd7wyXsgI8_AyMIqJ43rbc-PZMnymhI0MMMTX8RDjBO1fc9-gqz" alt=""/></figure></div>



<p class="wp-block-paragraph">It shows the execution cost was 43,702 gas. Again this is close to the estimated 22,498 gas plus the base fee of 21,000 gas (=43,498 gas).</p>



<h3 class="wp-block-heading">How do you find more details using the debugger?</h3>



<p class="wp-block-paragraph">If you want to know the detailed breakdown of the execution cost, you can use the debugger on Remix IDE. Open the debugger by clicking the Debug button on the console after running the function.</p>



<div class="wp-block-image"><figure class="aligncenter is-resized"><img loading="lazy" decoding="async" src="https://lh5.googleusercontent.com/Bxhuf3eXTA3R_YDmigj3aYNFpGzhLjouxY1DJ0Vm2sOcQGpoNuKw8j9sQyv8t73-37LSiELYYyJylc0a8haNP-u9PT4MWkzkDo2ix-wgiqd6fWjPCP6gOaM5soY3T02_gycXCCSY" alt="" width="758" height="206"/></figure></div>



<p class="wp-block-paragraph">You can run the code one operation at a time and see the detail of each operation, including the amount of gas.&nbsp;</p>



<div class="wp-block-image"><figure class="aligncenter is-resized"><img loading="lazy" decoding="async" src="https://lh5.googleusercontent.com/vpUtPhEdrSDBwfCkqnSWuIx78X_w7LFixp1HXymdGMG9l3PpGqiyr1rTPJPwl6fH9zhvMXT-13At5hjfS4YPMDf3HksYgh7fmy1wRmg916kgEBhJpHKCwUEKGU1OABYj6my7xQvs" alt="" width="320" height="647"/></figure></div>



<p class="wp-block-paragraph">The debugger usage is beyond this introductory article, but you can find more details in the Remix IDE documentation.</p>



<p class="wp-block-paragraph"><a href="https://remix-ide.readthedocs.io/en/latest/debugger.html" target="_blank" rel="noreferrer noopener"><strong>Debugger &#8211; Remix IDE</strong></a></p>



<h3 class="wp-block-heading">What is out of gas error?</h3>



<p class="wp-block-paragraph">Earlier I explained that the sender pays the transaction fee up front by specifying the gas limit and will receive a refund of the remaining balance after the transaction finishes. If the actual execution cost of the transaction exceeds the gas limit, the transaction will fail with an out of gas error. It is like the pre-paid card runs out of credit, so the telephone call suddenly disconnect.</p>



<p class="wp-block-paragraph">When the out of gas error happens, the state change during the transaction reverts, but the transaction fee is not returned to the sender because the EVM already executed the operations up to the point of the error.&nbsp;</p>



<p class="wp-block-paragraph">The following example illustrates how out of gas error happens using the JavaScript VM on Remix IDE.&nbsp;</p>



<p class="wp-block-paragraph">The execution cost of the function <code>get()</code> is 23,501 gas, so as long as the gas limit is equal to or larger than this number, the function successfully runs, as shown in the screenshot below.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh5.googleusercontent.com/PCYVDDejC6yFBu5O6V_t08PzTcWFqVphGxygOGNX14r0NYdnkcLowYdt-cA1Q0KFDCGPhoqb4r3PZzxWdrVq6_UQMD7OMQXGRaz48wjlVIvhKb5eUd7ItT6Ftix5nvMp8oqH8IeB" alt=""/></figure></div>



<p class="wp-block-paragraph">But if we set the gas limit to 23,500 gas, the transaction fails with the following error:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">call to SimpleStorage.get errored: VM error: out of gas.

out of gas
    The transaction ran out of gas. Please increase the Gas Limit.</pre>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh3.googleusercontent.com/xgrIh6VXGr0oEtoAkgqh984QrqXxrT6i2PrUDVRhEJyCbdWca1QeioCoNRHsjtshIIu3Gwkqkw-rcDKlCnsaqZ1Vr6hw-Xknhsw50TYpBlJY8TL2aGS9X1CViQ71PWbb4EWR_9BC" alt=""/></figure></div>



<p class="wp-block-paragraph">So, it is essential to set the gas limit large enough to execute transactions.</p>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">Gas is the unit of computational work on the Ethereum network. Each operation requires a pre-defined amount of gas to execute, and the total amount of gas for a specific transaction needs to be paid by the sender in the form of a transaction fee.</p>



<p class="wp-block-paragraph">When developing smart contracts in Solidity, it is vital to be aware of the gas consumption of the code, although it is not always straightforward to understand precisely how much gas our code costs.</p>



<p class="wp-block-paragraph">Remix IDE can estimate the gas unit of functions wherever possible. Alternatively, you can run your functions on the JavaScript VM and see how much gas they consume. You can even find a detailed breakdown of gas consumption on the opcode level by using the debugger.</p>



<p class="wp-block-paragraph">This article only scratched the surface. You can find more information about gas in the following resources:</p>



<ul class="wp-block-list"><li><a href="https://docs.soliditylang.org/en/v0.8.9/introduction-to-smart-contracts.html?highlight=gas#gas" target="_blank" rel="noreferrer noopener"><strong>Gas (soliditylang.org)</strong></a></li><li><a href="https://docs.soliditylang.org/en/v0.8.9/security-considerations.html?highlight=gas#gas-limit-and-loops" target="_blank" rel="noreferrer noopener"><strong>Gas Limit and Loops (soliditylang.org) </strong></a></li><li><a href="https://github.com/ethereumbook/ethereumbook/blob/develop/07smart-contracts-solidity.asciidoc#gas-considerations" target="_blank" rel="noreferrer noopener"><strong>Gas Considerations (Mastering Ethereum)</strong></a></li><li><a href="https://ethereum.org/en/developers/docs/gas/"><strong>GAS AND FEES (ethereum.org)</strong></a></li><li><a href="https://ethereum.github.io/yellowpaper/paper.pdf" target="_blank" rel="noreferrer noopener"><strong>Ethereum yellow paper (Appendix G. Fee Schedule)</strong></a> </li><li><a href="https://solidity-by-example.org/gas/" target="_blank" rel="noreferrer noopener"><strong>Gas (solidity-by-example.org)</strong></a></li><li><a href="https://eth.wiki/en/fundamentals/design-rationale#gas-and-fees" target="_blank" rel="noreferrer noopener"><strong>Gas and Fees (eth.wiki)</strong></a></li><li><a href="https://medium.com/coinmonks/8-ways-of-reducing-the-gas-consumption-of-your-smart-contracts-9a506b339c0a" target="_blank" rel="noreferrer noopener"><strong>8 Ways of Reducing the Gas Consumption of your Smart Contracts</strong></a></li></ul>



<h2 class="wp-block-heading"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">Learn Solidity Course</a></h2>



<p class="wp-block-paragraph">Solidity is the programming language of the future.</p>



<p class="wp-block-paragraph">It gives you the rare and sought-after superpower to program against the &#8220;Internet Computer&#8221;, i.e., against decentralized Blockchains such as <em>Ethereum</em>, <em>Binance Smart Chain</em>, <em>Ethereum Classic</em>, <em>Tron</em>, and <em>Avalanche </em>&#8211; to mention just a few Blockchain infrastructures that support Solidity.<br><br>In particular, Solidity allows you to<em> create smart contracts</em>, i.e., pieces of code that automatically execute on specific conditions in a completely decentralized environment. For example, smart contracts empower you to create your own <em>decentralized autonomous organizations</em> (DAOs) that run on Blockchains without being subject to centralized control.<br><br>NFTs, DeFi, DAOs, and Blockchain-based games are all based on smart contracts.<br><br><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/solidity-basics/">This course</a> is a simple, low-friction introduction to creating your first smart contract using the Remix IDE on the Ethereum testnet &#8211; without fluff, significant upfront costs to purchase ETH, or unnecessary complexity.</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><a href="https://academy.finxter.com/university/solidity-basics/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png" alt="" class="wp-image-37299" width="491" height="287" srcset="https://blog.finxter.com/wp-content/uploads/2021/10/image-121.png 982w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-300x175.png 300w, https://blog.finxter.com/wp-content/uploads/2021/10/image-121-768x448.png 768w" sizes="auto, (max-width: 491px) 100vw, 491px" /></a></figure></div>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-11-21 11:09:26 by W3 Total Cache
-->