Subscribe to our free newsletter

To make sure you won't miss any valuable content we share with our community.

Using Brownie to Switch between Different Networks

In this article, we are going to switch between the different available networks we can connect to, using Brownie. Then, we’ll write a statement in the Deploy.py to connect to the network requested in the terminal by the user (the developer). This kind of script for network management makes it easy for us to connect to any network that we want at any time it is required for testing and other purposes.

How to Switch between Networks

As you know, we have different networks to work with. We have already used some of them for deploying our contracts. Sometimes we need to write our deploy.py file in a way that we can switch between different networks and accounts and the deploy.py must understand which ones are available.

Switch between Different Networks

Before we get started with this task, we can check the keywords when we want to connect to different accounts. To look up the keyword related to any network, we write:

brownie networks list

Result:

Brownie v1.18.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 Avalanche ├─Mainnet: avax-main └─Testnet: avax-test Aurora ├─Mainnet: aurora-main └─Testnet: aurora-test Binance Smart Chain ├─Testnet: bsc-test └─Mainnet: bsc-main Fantom Opera ├─Testnet: ftm-test └─Mainnet: ftm-main Harmony └─Mainnet (Shard 0): harmony-main Moonbeam └─Mainnet: moonbeam-main Optimistic Ethereum ├─Mainnet: optimism-main └─Kovan: optimism-test 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 ├─Ganache-CLI (Avax-Mainnet Fork): avax-main-fork └─Ganache-CLI (Aurora-Mainnet Fork): aurora-main-fork

As you can remember, we have used Rinkeby from Infura a number of times and here the keyword for Rinkeby (Infura) is Rinkeby. Here, when we work with Brownie, in order to define the Infura RPC URL on the .env file, we need to write it in a different format:
export WEB3_INFURA_PROJECT_ID=80ca094b614b44b3b647ceb01a2b70d0
Notice that if you write any word other than WEB3_INFURA_PROJECT_ID, you will have a problem working with the Rinkeby or other networks of Infura, because Brownie has some built-in scripts that read from the ID with only this name.

Swtich Between Networks via Network Management in Deploy.py

The next thing we should do when we want to check for networks available for deployment is to add the following function to our deploy.py file:


def get_account():
	if network.show_active() == "development":
		return accounts[0]
	else:
		return accounts.add(config["wallets"]["from_key"])


And whenever we want to define our account, we write:
Account = get_account()
It is also necessary to import the network from Brownie:
from Brownie import network
The above code checks whether we want to use our Ganache CLI test accounts or use any other accounts that we have defined its a private key to our .env file and introduced to Brownie.
In order to connect to Rinkeby account in our Metamask wallet (that we entered its private key in the .env file), and the Rinkeby test network, in the terminal we should type:

brownie run scripts/deploy.py --network rinkeby

Result:

Brownie v1.18.1 - Python development framework for Ethereum BrownieSimpleStorageProject is the active project. Running 'scripts/deploy.py::main'... Transaction sent: 0xbfe6fb9f152eeda4fc880fc5a5cb6f74b0d73b440ada91e8bef71fb7fccf1ccd Gas price: 1.000000012 gwei Gas limit: 367598 Nonce: 48 SimpleStorage.constructor confirmed Block: 10426128 Gas used: 334180 (90.91%) SimpleStorage deployed at: 0x1570258Ee66a921A3f5fdEA48f5ba54bE657AA8b 0 Transaction sent: 0x0a5d8886732d99e6045eede0958894a033e48225d6818c312491b178195576ed Gas price: 1.000000012 gwei Gas limit: 47842 Nonce: 49 SimpleStorage.store confirmed Block: 10426129 Gas used: 43493 (90.91%) SimpleStorage.store confirmed Block: 10426129 Gas used: 43493 (90.91%) 38

And you can see the transaction related to contract deployment and storing a value inside the contract has been successfully completed on the Rinkeby network. Because we are working with Rinkeby, the transaction is trackable on this link. To be able to track it, simply copy and paste the address of the transaction into the search bar of the Etherscan.

Etherscan

Reading from the Contracts

One of the useful and necessary steps in writing an application related to a smart contract is being able to read from the transaction. The following steps will help you retrieve the different properties of the deployed smart contracts.
First, create a file in the scripts folder and name it read_value.py then write the following code in it.


from brownie import SimpleStorage, accounts, config

def read_contract():
	print(SimpleStorage)

def main():
	read_contract()


The above code, reads the contract deployments and their transactions. Let’s see the result by typing in the terminal:

brownie run scripts/read_value.py --network rinkeby

Result:

Brownie v1.18.1 - Python development framework for Ethereum BrownieSimpleStorageProject is the active project. Running 'scripts/read_value.py::main'...

The above result shows an array inside which we can retrieve the first member by changing the code to:


from brownie import SimpleStorage, accounts, config

def read_contract():
	print(SimpleStorage[0])

def main():
	read_contract()


brownie run scripts/read_value.py --network rinkeby

Result:

Brownie v1.18.1 - Python development framework for Ethereum BrownieSimpleStorageProject is the active project. Running 'scripts/read_value.py::main'... 0x1570258Ee66a921A3f5fdEA48f5ba54bE657AA8b

If you take a closer look, you will see that the address given here, is just the same address that we saw on Etherscan (the address of the contract deployment). It is worth knowing that if you want to retrieve the latest address contract that has been deployed, instead of print(SimpleStorage[0]) you can write print (SimpleStorage[-1]).
Notice that Brownie already knows the address and the ABI of our smart contract because it has saved it in a .json file. Also, if we want to retrieve a number again without asking the blockchain for it, we can retrieve it in the read_value.py file by writing:


print(SimpleStorage[-1].retrieve()

Result:

38

Summing Up

In this article, we have managed to write a script that makes it easy to switch between different networks such as Testnet (like Rinkeby), Mainnet, and local (like Ganache CLI) for the users and the developers. With this script written in the deploy.py, we can choose the network at the time of running Brownie by simply calling the network’s name in the terminal.

Download this Article in PDF format

web developement

Check Out Our Services

In Arashtad, we’re working on 3D games, metaverses, and other types of WebGL and 3D applications with our 3D web development team. However, our services are not limited to these. Back-end developments, front-end developments, 3d modeling, and animations are in our arsenal too.

Arashtad Serivces
Drop us a message and tell us about your ideas.
Tell Us What You Need
Blockchain Development

Using Ganache CLI with Brownie to Deploy A Smart Contract

In this article, after installing Brownie, we are going to install the Ganache CLI (Command Line Interface) and use it with Brownie. The Ganache CLI is the same as Ganache IDE with the difference that it automatically runs without the need to open the Ganache IDE. At the end end of this tutorial, we will be able to deploy our smart contracts on top of Ganache CLI simulated blockchain.

Installing Ganache:

To continue our journey with Brownie, we need to make sure Ganache CLI has been installed successfully. To make sure that it has, and also see its virtual accounts, in your console (terminal) write:

ganache

And it should give you the test accounts like this:


ganache v7.0.3 (@ganache/cli: 0.1.4, @ganache/core: 0.1.4)
Starting RPC server

Available Accounts
==================
(0) 0x960F41C52ffAef71fFef2fFBC3C0EA5Dc5748086 (1000 ETH)
(1) 0x39Cf64532C1126c6C9Fa0a02338389d1eb861A12 (1000 ETH)
(2) 0xA1E47c46425e24565666ED350e1edEf6532f348c (1000 ETH)
(3) 0xE441bb58b5369DB428a979fbE77Df2d3Da1F91d4 (1000 ETH)
(4) 0x4498662A9691cfef775d3D212f5938905B5de70E (1000 ETH)
(5) 0x4Da709036c65CB81bF74970945f21Ac2e42e9cA9 (1000 ETH)
(6) 0x32872e4dDB4c4876e7B1359013696344fd976C22 (1000 ETH)
(7) 0x6aadaB117c9f26726D5e23b9A0fdC475F3BEd181 (1000 ETH)
(8) 0xCf763def60f3247CE5bEF18BAfC080dA3573595b (1000 ETH)
(9) 0x3a6AFe48C0889820aa587E9Dd45D1B7d8E4e5039 (1000 ETH)

Private Keys
==================
(0) 0x1093c2edf08326559ffbaccfe2a5c5826d2bee9b42fc71c51ad8d989100a3a31
(1) 0x4ebeaf4a4bb07a875255d1f4627146dcc69c930cc380701e1f338d1975240135
(2) 0xa25ad60447f26ad265962660c88bb04ff671f3a55c0f59985530088dad82c9c8
(3) 0x706fce79c758f53fc9336507a35d66ec285c8f52147a6f7676a0e89925f21d0c
(4) 0xd92dc461456414fa41af48ca8806a50031bdc4d587b8e49b1a3f501790f4b853
(5) 0x0b467e91bb9fef30c51077d9a7ba4b9d0797fe46f7fc1cff202751d9bfcf0bb0
(6) 0xaa05bda4d14e2fd3cac04174feeca371567b8f990acc6fab001f0b3317680d50
(7) 0x3a263493e9763bb5b7f069cd51cbca836298831d59b7f57125c937f8ef76dd82
(8) 0x4d6edbb1e7d4283cdf7cc8ce802ef72bcb7b684a51ab7098834e48a638bcfae5
(9) 0x5cb8a425439d9db86c6a58438fb5a6fa425ab60c675d9fd90bdc14cf093bf33c

HD Wallet
==================
Mnemonic:      patrol juice song save pretty combine dish table sock robust glow bunker
Base HD Path:  m/44'/60'/0'/0/{account_index}

Default Gas Price
==================
2000000000

BlockGas Limit
==================
30000000

Call Gas Limit
==================
50000000

Chain Id
==================
1337

RPC Listening on 127.0.0.1:8545


If you don’t get the above results or you get:

ganache is not recognized …

You might need to install it and that shows that Ganache CLI has not yet been installed. Notice that on Linux, instead of writing:

npm install –-global ganache

You should add sudo at the beginning of the command. Otherwise, it will throw an error saying that the node modules folder is not in usr/local/lib directory. So for Linux, we install the Ganache CLI like this:

sudo npm install –global ganache

Also, before installing the Ganache CLI, you need to make sure you have the node installed on your OS. You can check it by typing:

node -v

Result:

v16.14.2

Deploying the Contract Using Ganache CLI:

After that, we make sure that all the dependencies have been installed, we can continue with Brownie scripts on deploy.py:
First, run Brownie:

brownie

Then, fetch one of the Ganache accounts using the following code in the deploy.py file:


from brownie import accounts

def deploy_simple_storage():
	account = accounts[0]
	print(account)

def main():
	deploy_simple_storage()


We will run the project by the following command in the terminal (In the directory of the project’s folder):

brownie run scripts/deploy.py

Result:

Brownie v1.18.1 - Python development framework for Ethereum BrownieSimpleStorageProject is the active project. Attached to local RPC client listening at '127.0.0.1:8545'... Running 'scripts/deploy.py::main'... 0x960F41C52ffAef71fFef2fFBC3C0EA5Dc5748086

Using Environment Variables for the Private Key:

If you can remember from the previous tutorial, we added the Metamask account to Brownie and the terminal asked for the private key. Now, if we do not want to enter the password every time and make the process run automatically without asking the user for a private key or password, we go after the environment variables again. But, this time is a little a bit different. Like before, we create a .env file and paste our private key:


export PRIVATE_KEY= “here goes your private key”

Then, we create a file called brownie-config.yaml and paste the following code:


dotenv: .env
wallets:
	from_key: ${PRIVATE_KEY}


Then, we modify our deploy.py file as below:


from brownie import accounts, config

def deploy_simple_storage():
	account = accounts.add(config["wallets"]["from_key"])
	print(account)

def main():
	deploy_simple_storage()



And if we run it by the following command in the terminal:

brownie run scripts/deploy.py

Result:

Brownie v1.18.1 - Python development framework for Ethereum BrownieSimpleStorageProject is the active project. Attached to local RPC client listening at '127.0.0.1:8545'... Running 'scripts/deploy.py::main'... 0x25E681EE76469E4cF846567b772e94e082907117

Now to actually deploy the simple storage contract, we import the SimpleStorage in the deploy.py file and also add the contract.deploy({}) line to the first function:


def deploy_simple_storage():


from brownie import accounts, config, SimpleStorage

def deploy_simple_storage():
	account = accounts.add(config["wallets"]["from_key"])
	SimpleStorage.deploy({"from": account})

def main():
	deploy_simple_storage()


And

brownie run scripts/deploy.py

Result:

Brownie v1.18.1 - Python development framework for Ethereum BrownieSimpleStorageProject is the active project. Launching 'ganache-cli --chain.vmErrorsOnRPCResponse true --server.port 8545 --miner.blockGasLimit 12000000 --wallet.totalAccounts 10 --hardfork istanbul --wallet.mnemonic brownie'... Running 'scripts/deploy.py::main'... Transaction sent: 0x1d70d1a30b0266da050d696c14b749bb5e34425159817e5f6e66b1e615221685 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 SimpleStorage.constructor confirmed Block: 1 Gas used: 334180 (2.78%) SimpleStorage deployed at: 0x647Dc9EE9731d35b9031A9ca6c664D6b75d14385 Terminating local RPC client…

Deploying the Contract with the Ganache CLI Accounts

You can also test this with the Ganache accounts:


from brownie import accounts, config, SimpleStorage

def deploy_simple_storage():
	account = accounts[0]
	SimpleStorage.deploy({"from": account})

def main():
	deploy_simple_storage()


Result:

Brownie v1.18.1 - Python development framework for Ethereum BrownieSimpleStorageProject is the active project. Launching 'ganache-cli --chain.vmErrorsOnRPCResponse true --server.port 8545 --miner.blockGasLimit 12000000 --wallet.totalAccounts 10 --hardfork istanbul --wallet.mnemonic brownie'... Running 'scripts/deploy.py::main'... Transaction sent: 0xbbd21a1abc42f0d21f4651b71cddadddecf6ba99af3a31a140434950c7e36876 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 0 SimpleStorage.constructor confirmed Block: 1 Gas used: 334180 (2.78%) SimpleStorage deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87 Terminating local RPC client…

Great! Now we have managed to deploy our contract using Brownie. The Brownie adventure however is goes on in our other articles.

Summing Up

In this article, we have managed to install the Ganache CLI, to be able to automatically use it whenever we want to test our deployment in a simulated blockchain. We have also considered a way to include our private key somewhere safe (in the .env file) out of the deploy.py script file. In the end, we deployed our contract using the Ganache CLI.

Download this Article in PDF format

3d websites

Care to Know Us More?

In Arashtad, we have gathered a professional team of developers who are working in fields such as 3D websites, 3D games, metaverses, and other types of WebGL and 3D applications.

Arashtad Serivces
Drop us a message and tell us about your ideas.
Request a Quote
ThreeJS Development