Site icon EASY2DIGITAL

Brownie FundMe Smart Contract Deployed on Ethereum Using Python & Web3

One of the main Web3.0 product value propositions is payment decentralization from the central bank using Cryptocurrency and Blockchain. The value is kind of imaginable because you can send or receive money using your own developed Crypto payment gateway. Moreover, the traditional bank system is unlikely to record all transactions straightforwardly. That implies quite a lot in fact in terms of business assets and financial operations.

In this article, I’m going to share a Brownie FundMe smart contract and go through how to deploy it onto an Ethereum network.

Ingredient to deploy a Brownie FundMe Smart Contract on Ethereum using Python and Web3

Python3, Brownie, Solidity, ChainLink

Table of Contents

Add a Brownie FundMe Smart Contract .sol

First thing first, we create a smart contract that can process fund send or receive and add under the new Brownie project. There has been a smart contract developed by us before. If you are interested in, please subscribe to the Easy2Digital newsletter by leaving a message “Brownie FundMe smart contract script”, and we’ll send you as soon as possible.

Contact us

Connect with a 3rd party repository using .yaml

External 3rd party repository sources and data feeds are not readable by Brownie if you just add them to the smart contract. Here are the components added for connecting with external sources as follows:

1. Create a brownie-config.YAML and add dependencies – organization and version

First thing first, we need to add a configuration YAML file under the root directory. Namely, this file tells Brownies there are some internal or external sources to connect. In our case, we use Chainlink.

Please be sure to check the brownie smart contract’s latest number, which here is 0.5.1. It’s because it tells brownies which version we’re connecting to. For more details, just do a search in Google and it will pop up. So here is the code sample in the YAML file as follows using dependencies:

Dependencies:

smartcontractkit/chainlink-brownie-contracts@0.5.1

2. Compiler, solc, remapping

After having set up the destination, we need to tell Brownie which module we like to map with the external source. As you can see in our completed Brownie FundMe .sol, we use @chainlink in the module import section

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

So here are the codes as follows for mapping with the external source using compiler, solc and remappings

compiler:

  solc:

    remappings:

      - '@chainlink=smartcontractkit/chainlink-brownie-contracts@0.5.1'

Please be sure to check the version of the external source if it matches the version or is within the scope of the version you are using in the smart contract. For example, we are importing the V8 version of the interface and the solidity version range should cover V8 as follows:

pragma solidity >=0.6.0 <0.9.0;

3. Brownie compile

Once things are completed as mentioned earlier, we can input brownie compile and it depicts that the project has been compiled. Then, you can see there is a new JSON file added under the contracts folder.

Create a get_account function using a standalone Python script

In the previous chapter regarding Infura and Metamask, we created a get_account function in the Python deployment script. This function is used to get the specific cryptocurrency account you like to interact with your smart contract. As well as a general Python functional import approach, Brownie also provides a script folder for anyone to add any scripts needed. These scripts can be connected with each other as well.

Here are the codes of get_account function script which is the same as the one used to connect with Ganache CLI.

from brownie import network, config, accounts

def get_account():

    if network.show_active() == "development":

        return accounts[0]

    else:

        return accounts.add(config["wallets"]["from_key"])

Once the script is created and saved under the script folder, we can import the function in the deploy script as follows:

As highlighted in the code above, please check out the previous article as follow if you have any questions regarding how to create and add wallets, from_key, and .env. They are used to connect with your real wallet in a safe mode.

https://www.easy2digital.com/web3/brownie-web3-develop-ethereum-smart-contracts-interacting-with-cryptocurrency-network-using-brownie-and-python/#4

Or you can go down to the end of this article and subscribe to the Easy2Digital newsletter for the full script.

Last but not least, please be sure to add a Python script named as follow. It tells Python it can import modules with each other.

__init__.py

Verify your Smart Contract on the Etherscan

If we like to check whether our FundMe smart contract verification is valid on the Ethereum network (Note**. Please be sure to deploy the settings that are the same as our scripts, there are a few steps needed as follows:

Step 1: Create an Etherscan account and gain the API Key

Go to etherscan.io and sign u for a free account. Each account has 5 free API keys. After having signed up, please copy it in advance and you will use it in a moment.

Step 2: Add the API key using ETHERSCAN_TOKEN in .env

As well as setting up your private key, we would put the Etherscan key to .env as well. Thus, here is the code as follows you add to the .env file

export ETHERSCAN_TOKEN = your etherscan api key

Step 3: Run the Brownie script and check the verification on Etherscan after the verification occur

Lastly, please run the script in your terminal again and you would see pass and verified once your smart contract is uploaded to the Etherscan network successfully.

Add parameters in the constructor in the FundMe Smart Contract

Sending or receiving funds necessarily shows the real-time currency exchange rate and the funder’s & senders’ address. Thus, before deploying functions for this feature, we need to set the price feed parameter in the constructor, which is address and _priceFeed. Here is the updated constructor code sample in the FundMe smart contract as follows:

    constructor(address _priceFeed) public {

        priceFeed = AggregatorV3Interface(_priceFeed);

        owner = msg.sender;

    }

Deploy Mocks

If we are only on the goerli blockchain network, it’s just for us to use an associate address. But how come we like to set either or, or multip networks that include testing networks and real networks? In this case, we need to deploy mocks.

Step 1: Add the network dataset that includes the ETH to the target currency price feed

For fetching the different network datasets, we need to the network dataset into .yaml. Here is the code:

networks:

  goerli:

    eth_usd_price_feed: '0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e'

    verify: True

Chainlink provides real-time exchange rate data feed, so please go to data.chain.link and copy, and paste the blockchain network’s ETH vs target currency price fee key to .yaml

Step 2: Update deploy.py with fetching network price feed dynamically

    if network.show_active() != "development":

        price_feed_address = config["networks"][network.show_active(

        )]["eth_usd_price_feed"]

Step 3: Deploy Mocks

First thing first, we need to add a test folder and a mock .sol contract under the test folder. For this mock smart contract, please subscribe to the Easy2Digital newsletter by leaving web3 tutorial 4, we’ll send you asap.

Then, after having compiled again,  in the YAML file, we will add one more network called development and the verify should be False because it’s a local testing price feed data.

development: 

verify: False

Additionally, as well as importing FundMe, we need to import MockV3Aggregator and write code in the else section, which means it’s a development mode.

from brownie import FundMe, MockV3Aggregator, network, config

else:

        deploy_mocks()

        price_feed_address = MockV3Aggregator[-1].address

Here we create a function deploy_mock() in the get_account script, which uses Mock contract if it’s a development mode  as follows:

DECIMALS = 8

STARTING_PRICE = 2000000000000000

def deploy_mocks():

    print(f"The active network is {network.show_active()}")

    print("Deploying Mocks......")

    if len(MockV3Aggregator) <= 0:

        mock_aggregator = MockV3Aggregator.deploy(

            DECIMALS, STARTING_PRICE, {

                "from": get_account()}

Add a New Network

Apart from the existing network Brownie provides, we can add a new network needed, for example for testing purposes.

Here is a sample of adding a ganache-local network in the terminal:

brownie networks add Ethereum ganache-local host=http://address chainid=yours

By default, Brownie uses the development mode network. As now there is one more local network added, we need to update the variables to justify the execution

LOCAL_BLOCKCHAIN_ENVIRONMENTS = ["development", "ganache-local"]

Fund and Withdraw

Under the script folder, we create a fund and withdraw script. Here are the functions as follows:

Fund:

def fund():
fund_me = FundMe[-1]
account = get_account()
entrance_fee = fund_me.getEntranceFee()
print(entrance_fee)
print(f”The current entry fee is {entrance_fee}”)
print(“Funding”)
fund_me.fund({“from”: account, “value”: entrance_fee})
Withdraw:
def withdraw():
fund_me = FundMe[-1]
account = get_account()
fund_me.withdraw({“from”: account})
Results:

Full Python Script of Brownie FundMe smart contract

If you are interested in Brownie FundMe Smart Contract Deployed on Ethereum Using Python & Web3, please subscribe to our newsletter by adding the message “Web3.0 tutorial 4”. We would send you the script immediately to your mailbox.

I hope you enjoy reading Brownie FundMe Smart Contract Deployed on Ethereum Using Python & Web3. If you did, please support us by doing one of the things listed below, because it always helps out our channel.

FAQ:

Q1: What is an Ethereum smart contract?

A: An Ethereum smart contract is a self-executing contract with the terms of the agreement directly written into code. The code and the agreements contained therein exist across a distributed, decentralized blockchain network. The blockchain network prevents modification of the smart contract’s code, while its decentralized nature prevents any single entity from controlling the smart contract.

Q2: What are the benefits of using Ethereum smart contracts?

A: Ethereum smart contracts offer a number of benefits, including increased security, transparency, and efficiency. Additionally, smart contracts can be used to automate payments, enforce complex business rules, and create decentralized applications.

Q3: What are some of the challenges of using Ethereum smart contracts?

A: There are a number of challenges associated with using Ethereum smart contracts, including the need for specialized programming skills, the potential for bugs and security vulnerabilities, and the high cost of gas fees.

Q4: What are some of the most popular use cases for Ethereum smart contracts?

A: Some of the most popular use cases for Ethereum smart contracts include decentralized finance (DeFi), non-fungible tokens (NFTs), and decentralized applications (dApps).

Q5: How do I create an Ethereum smart contract?

A: To create an Ethereum smart contract, you will need to learn a smart contract programming language, such as Solidity. Once you have written your smart contract code, you will need to compile it and deploy it to the Ethereum blockchain.

Q6: How do I interact with an Ethereum smart contract?

A: To interact with an Ethereum smart contract, you will need to use a web3 wallet, such as MetaMask. Once you have a web3 wallet, you can connect to the Ethereum blockchain and interact with smart contracts by sending transactions.

Q7: What are some of the security risks associated with Ethereum smart contracts?

A: There are a number of security risks associated with Ethereum smart contracts, including the potential for bugs and security vulnerabilities, the risk of hacking and theft, and the risk of fraud.

Q8: How can I mitigate the security risks associated with Ethereum smart contracts?

A: There are a number of steps you can take to mitigate the security risks associated with Ethereum smart contracts, including using a reputable smart contract development team, conducting thorough security audits, and using a secure web3 wallet.

Q9: What is the future of Ethereum smart contracts?

A: The future of Ethereum smart contracts is bright. As the Ethereum blockchain continues to grow and evolve, smart contracts will play an increasingly important role in a wide variety of industries.

Q10: Where can I learn more about Ethereum smart contracts?

A: There are a number of resources available to learn more about Ethereum smart contracts, including online courses, tutorials, and documentation. Additionally, there are a number of online communities where you can ask questions and get help from other developers.

Exit mobile version