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

How to Interact with Smart Contracts Using Brownie

After installing and working with Ganache CLI, we are going to interact with simple storage smart contracts Using Brownie. Meaning that we want to store and retrieve a value within the contract. After doing this you will see how simple and efficient Brownie is compared to other methods in python. We are also going to use testing modules to test the functionality of the contract and its deployment.

Using Brownie to Interact with Smart Contracts

In the previous section of this tutorial, we learned how to deploy our simple storage smart contract. In this one, we are going to interact with it, meaning that we want to store a value inside the contract and retrieve it using Brownie. After doing this you will see how simply and efficiently Using Brownie to interact with smart contracts can get compared to other methods in python.

Retrieving the Stored Data:

So, to follow our deploy.py script, we have:


from Brownie import accounts, config, SimpleStorage
def deploy_simple_storage():

	account = accounts[0]
	simple_storage = SimpleStorage.deploy({"from": account})
	stored_value = simple_storage.retrieve()
	print(stored_value)
	transaction = simple_storage.store(38,{"from": account})
	transaction.wait(1)
	updated_stored_value = simple_storage.retrieve()
	print(updated_stored_value)

def main():
	deploy_simple_storage()


In the above code, we first try to retrieve the stored value inside the contract. Then, we store a number in it and again retrieve the stored value. By running this code using:

brownie run scripts/deploy.py

We have:

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 0 Transaction sent: 0x6bd512176120555da2d2682b4dd0256ccb8060a5c63d678d65ff4b554ffd7477 Gas price: 0.0 gwei Gas limit: 12000000 Nonce: 1 SimpleStorage.store confirmed Block: 2 Gas used: 41393 (0.34%) SimpleStorage.store confirmed Block: 2 Gas used: 41393 (0.34%) 38 Terminating local RPC client…

As you can see, 2 blocks have been hashed at the end. And at first, we have nothing stored. So, the first number that has been retrieved is 0, and then after storing the number 38, we have it as the result of the retrieve.

Testing Smart Contracts Using Brownie

One of the important steps in developing a smart contract is to test our contract. Because in the main deployment of the transaction in a real-world smart contract if anything goes wrong, like spending infinitely extra ETH or mistakes like this, there will be no way to compensate for it. The tests folder is located in the main directory and is created by Brownie. We create a file named test_simple_storage.py and write:


from Brownie import SimpleStorage, accounts
def test_deploy():
	account = accounts[0]
	simple_storage = SimpleStorage.deploy({"from": account})
	starting_value = simple_storage.retrieve()
	expected = 0
	assert starting_value == expected


The above script does the same as deploy.py with the difference that it tests whether the output is the expected value or not. This will help us to understand the existing bugs without spending ETH.

brownie test

Result:

Brownie v1.18.1 - Python development framework for Ethereum ===================================================== test session starts ===================================================== platform linux -- Python 3.8.10, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 rootdir: /home/mohamad/Desktop/solidity/Solidity and web3 codes/brownie_simple_storage plugins: eth-brownie-1.18.1, web3-5.27.0, xdist-1.34.0, forked-1.4.0, hypothesis-6.27.3 collected 1 item Launching 'ganache-cli --chain.vmErrorsOnRPCResponse true --server.port 8545 --miner.blockGasLimit 12000000 --wallet.totalAccounts 10 --hardfork istanbul --wallet.mnemonic brownie'... tests/test_simple_storage.py . [100%] ====================================================== 1 passed in 2.17s ====================================================== Terminating local RPC client…

def test_deploy():
	account = accounts[0]
	simple_storage = SimpleStorage.deploy({"from": account})
	starting_value = simple_storage.retrieve()
	expected = 38
	assert starting_value == expected


brownie test Brownie v1.18.1 - Python development framework for Ethereum ===================================================== test session starts ===================================================== platform linux -- Python 3.8.10, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 rootdir: /home/mohamad/Desktop/solidity/Solidity and web3 codes/brownie_simple_storage plugins: eth-brownie-1.18.1, web3-5.27.0, xdist-1.34.0, forked-1.4.0, hypothesis-6.27.3 collected 1 item Launching 'ganache-cli --chain.vmErrorsOnRPCResponse true --server.port 8545 --miner.blockGasLimit 12000000 --wallet.totalAccounts 10 --hardfork istanbul --wallet.mnemonic brownie'... tests/test_simple_storage.py F [100%] ========================================================== FAILURES =========================================================== _________________________________________________________ test_deploy _________________________________________________________ def test_deploy(): account = accounts[0] simple_storage = SimpleStorage.deploy({"from": account}) starting_value = simple_storage.retrieve() expected = 38 > assert starting_value == expected E assert 0 == 38 tests/test_simple_storage.py:10: AssertionError =================================================== short test summary info =================================================== FAILED tests/test_simple_storage.py::test_deploy - assert 0 == 38 ====================================================== 1 failed in 1.83s ====================================================== Terminating local RPC client… *****

As you can see, it shows failure because we haven’t stored any value yet and the expected number should be 0 instead of 38. Now, let’s define another function for storing the expected number, retrieving and putting it into the test:


from Brownie import SimpleStorage, accounts
def test_deploy():

	account = accounts[0]
	simple_storage = SimpleStorage.deploy({"from": account})
	starting_value = simple_storage.retrieve()
	expected = 38
	assert starting_value == expected

def test_updating_storage():

	account = accounts[0]
	simple_storage = SimpleStorage.deploy({"from": account})
	expected = 38
	simple_storage.store(expected,{"from":account})
	assert expected == simple_storage.retrieve()


brownie test

Result:

Brownie v1.18.1 - Python development framework for Ethereum ===================================================== test session starts ===================================================== platform linux -- Python 3.8.10, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 rootdir: /home/mohamad/Desktop/solidity/Solidity and web3 codes/brownie_simple_storage plugins: eth-brownie-1.18.1, web3-5.27.0, xdist-1.34.0, forked-1.4.0, hypothesis-6.27.3 collected 2 items Launching 'ganache-cli --chain.vmErrorsOnRPCResponse true --server.port 8545 --miner.blockGasLimit 12000000 --wallet.totalAccounts 10 --hardfork istanbul --wallet.mnemonic brownie'... tests/test_simple_storage.py F. [100%] ========================================================== FAILURES =========================================================== _________________________________________________________ test_deploy _________________________________________________________ def test_deploy(): account = accounts[0] simple_storage = SimpleStorage.deploy({"from": account}) starting_value = simple_storage.retrieve() expected = 38 > assert starting_value == expected E assert 0 == 38 tests/test_simple_storage.py:10: AssertionError =================================================== short test summary info =================================================== FAILED tests/test_simple_storage.py::test_deploy - assert 0 == 38 ================================================= 1 failed, 1 passed in 2.07s ================================================= Terminating local RPC client…

As you can see, one test failed and the other passed. The expected result was not 38 at first but, after storing it as expected, it passed.

Last Thought on Using Brownie to Interact with Smart Contracts

In this article, we have managed to retrieve the data we stored using the deploy.py python script. We have also created test.py files in the test directory to be able to see if the smart contract and the deploy.py work correctly. The Brownie module comes with a test package called pytest that makes the developers capable of testing any part of their script using the Brownie test command.

Download this Article in PDF format

metaverse

Care to Know About Metaverse?

In Arashtad, we are providing custom services on 3d developments such as 3d websites, 3d models, metaverses and all 3d applications.

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