brownie部署与测试智能合约

2023-10-30 11:58

本文主要是介绍brownie部署与测试智能合约,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

    brownie是一种Python语言的开发与测试框架,它可以部署.sol、.py格式的智能合约。

  • 完全支持Solidity和Vyper
  • 通过pytest进行智能合约测试,包括基于跟踪的覆盖率评估
  • 通过hypothesis进行基于属性和状态的测试
  • 强大的调试工具,包括python风格的跟踪和自定义错误字符串
  • 内置控制台,用于快速项目互动
  • 支持ethPM软件包

    下面,介绍brownie的安装、部署智能合约、测试智能合约。

1、准备环境

1.1 安装nodejs、python3

    安装nodejs,请参考这篇文章的第1节
    安装Python3,请参考这篇文章的第9节

1.2 安装brownie

    这里选择brownie==1.12.3版本,进行安装

pip3 install eth-brownie==1.12.3

1.3 安装ganache-cli

npm install -g ganache-cli

2、创建工程browthree

2.1 创建文件与文件夹

    a) 打开控制台终端,依次输入如下命令:

mkdir browthree
cd browthree
brownie init
touch brownie-config.yaml
touch .env

    b) 填写brownie的配置文件:brownie-config.yaml
    // brownthree/brownie-config.yaml

dependencies:- OpenZeppelin/openzeppelin-contracts@3.4.0
compiler:solc:remappings:- '@openzeppelin=OpenZeppelin/openzeppelin-contracts@3.4.0'
dotenv: .env
networks:networks:# any settings given here will replace the defaultsdevelopment:host: http://127.0.0.1gas_price: 0persist: falsereverting_tx_gas_limit: 6721975test_rpc:cmd: ganache-cliport: 8545gas_limit: 6721975accounts: 10# set your Infura API token to the environment variable ${WEB3_INFURA_PROJECT_ID}mainnet:host: https://mainnet.infura.io/v3/${WEB3_INFURA_PROJECT_ID}goerli:host: https://goerli.infura.io/v3/${WEB3_INFURA_PROJECT_ID}kovan:host: https://kovan.infura.io/v3/${WEB3_INFURA_PROJECT_ID}rinkeby:host: https://rinkeby.infura.io/v3/${WEB3_INFURA_PROJECT_ID}ropsten:host: https://ropsten.infura.io/v3/${WEB3_INFURA_PROJECT_ID}classic:host: https://www.ethercluster.com/etckotti:host: https://www.ethercluster.com/kotti
wallets:from_key: ${PRIVATE_KEY}

    c) 填写环境变量文件: .env
    // brownthree/.env

export WEB3_INFURA_PROJECT_ID='59...b6'
export PRIVATE_KEY='85...84'

    d) browthree工程的目录结构

图(1) browthree工程的目录结构

2.2 编写智能合约

    在browthree/contracts目录,创建一个智能合约文件: HelloERC20.sol

cd browthree/contracts
touch HelloERC20.sol

    // HelloERC20.sol

pragma solidity >=0.4.22 <0.6.0;interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; 
}contract HelloERC20 {// Public variables of the tokenstring public name;string public symbol;uint8 public decimals = 18;// 18 decimals is the strongly suggested default, avoid changing ituint256 public totalSupply;// This creates an array with all balancesmapping (address => uint256) public balanceOf;mapping (address => mapping (address => uint256)) public allowance;// This generates a public event on the blockchain that will notify clientsevent Transfer(address indexed from, address indexed to, uint256 value);// This generates a public event on the blockchain that will notify clientsevent Approval(address indexed _owner, address indexed _spender, uint256 _value);// This notifies clients about the amount burntevent Burn(address indexed from, uint256 value);constructor(uint256 initialSupply,string memory tokenName,string memory tokenSymbol) public {totalSupply = initialSupply * 10 ** uint256(decimals);  // Update total supply with the decimal amountbalanceOf[msg.sender] = totalSupply;                // Give the creator all initial tokensname = tokenName;                                   // Set the name for display purposessymbol = tokenSymbol;                               // Set the symbol for display purposes}/*** Internal transfer, only can be called by this contract*/function _transfer(address _from, address _to, uint _value) internal {// Prevent transfer to 0x0 address. Use burn() insteadrequire(_to != address(0x0));// Check if the sender has enoughrequire(balanceOf[_from] >= _value);// Check for overflowsrequire(balanceOf[_to] + _value >= balanceOf[_to]);// Save this for an assertion in the futureuint previousBalances = balanceOf[_from] + balanceOf[_to];// Subtract from the senderbalanceOf[_from] -= _value;// Add the same to the recipientbalanceOf[_to] += _value;emit Transfer(_from, _to, _value);// Asserts are used to use static analysis to find bugs in your code. They should never failassert(balanceOf[_from] + balanceOf[_to] == previousBalances);}function transfer(address _to, uint256 _value) public returns (bool success) {_transfer(msg.sender, _to, _value);return true;}function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {require(_value <= allowance[_from][msg.sender]);     // Check allowanceallowance[_from][msg.sender] -= _value;_transfer(_from, _to, _value);return true;}function approve(address _spender, uint256 _value) publicreturns (bool success) {allowance[msg.sender][_spender] = _value;emit Approval(msg.sender, _spender, _value);return true;}function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)publicreturns (bool success) {tokenRecipient spender = tokenRecipient(_spender);if (approve(_spender, _value)) {spender.receiveApproval(msg.sender, _value, address(this), _extraData);return true;}}function burn(uint256 _value) public returns (bool success) {require(balanceOf[msg.sender] >= _value);   // Check if the sender has enoughbalanceOf[msg.sender] -= _value;            // Subtract from the sendertotalSupply -= _value;                      // Updates totalSupplyemit Burn(msg.sender, _value);return true;}function burnFrom(address _from, uint256 _value) public returns (bool success) {require(balanceOf[_from] >= _value);                // Check if the targeted balance is enoughrequire(_value <= allowance[_from][msg.sender]);    // Check allowancebalanceOf[_from] -= _value;                         // Subtract from the targeted balanceallowance[_from][msg.sender] -= _value;             // Subtract from the sender's allowancetotalSupply -= _value;                              // Update totalSupplyemit Burn(_from, _value);return true;}
}

2.3 编写测试脚本

    在browthree/tests目录,创建一个测试脚本文件: 1_func_test.py

cd browthree/tests
touch 1_func_test.py

    // 1_func_test.py

import pytest
from brownie import HelloERC20, accounts@pytest.fixture
def token():return accounts[0].deploy(HelloERC20, 1000,"AppleToken", "APT")def test_transfer(token):token.transfer(accounts[1], "100 ether", {'from': accounts[0]})assert token.balanceOf(accounts[0]) == "900 ether"def test_name(token):assert token.name() == "AppleToken"def test_symbol(token):assert token.symbol() == "APT"def test_totalSupply(token):assert token.totalSupply() == "1000 ether"def test_approve(token):token.approve(accounts[1],"100 ether",{'from':accounts[0]})assert token.allowance(accounts[0],accounts[1]) == "100 ether"def test_burn(token):token.burn("100 ether",{'from':accounts[0]})print("addr=",token.address)assert token.totalSupply() == "900 ether"def test_transferFrom(token):token.approve(accounts[1],"100 ether",{'from':accounts[0]})token.transferFrom(accounts[0],accounts[1],"100 ether",{'from':accounts[1]})assert token.balanceOf(accounts[1]) == "100 ether"def test_burnFrom(token):token.approve(accounts[1],"100 ether",{'from':accounts[0]})token.burnFrom(accounts[0],"100 ether",{'from':accounts[1]})assert token.totalSupply() == "900 ether"

2.4 编写部署脚本

    在browthree/tests目录,创建一个部署脚本文件: 1_deploy_token.py

cd browthree/scripts
touch 1_deploy_token.py

    // 1_deploy_token.py

import os
from brownie import accounts,HelloERC20initial_supply = 1000000  # 1000000
token_name =   "AppleToken"
token_symbol = "APT"def get_account():accAddr = accounts.add(os.getenv('PRIVATE_KEY'))return accAddrdef main():account = get_account()print('account=',account)erc20 = HelloERC20.deploy(initial_supply, token_name, token_symbol, {"from": account})

2.5 进行部署与测试

    a) 部署合约到Rinkeby

## 使能.env环境
source .env## 部署到Rinkeby
brownie run scripts/1_deploy_token --network rinkeby

    效果如下:

图(2) 部署合约到Rinkeby

    得到HelloERC20.sol的合约地址为: 0x7000A28DCF57883286bd568CCa4733baF91e62ef

    b) 测试HelloERC20合约

  • 先启动ganache-cli

    在黑框框终端里,输入如下命令即可

ganache-cli
  • 再运行测试脚本
## 方法一:禁用print
brownie test tests/1_func_test.py## 方法二:启用print
brownie test tests/1_func_test.py -s

    效果如下:

图(3) 在ganache-cli里,测试合约

参考文献

brownie 单元测试

这篇关于brownie部署与测试智能合约的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/307765

相关文章

Docker部署Jenkins持续集成(CI)工具的实现

《Docker部署Jenkins持续集成(CI)工具的实现》Jenkins是一个流行的开源自动化工具,广泛应用于持续集成(CI)和持续交付(CD)的环境中,本文介绍了使用Docker部署Jenkins... 目录前言一、准备工作二、设置变量和目录结构三、配置 docker 权限和网络四、启动 Jenkins

Python3脚本实现Excel与TXT的智能转换

《Python3脚本实现Excel与TXT的智能转换》在数据处理的日常工作中,我们经常需要将Excel中的结构化数据转换为其他格式,本文将使用Python3实现Excel与TXT的智能转换,需要的可以... 目录场景应用:为什么需要这种转换技术解析:代码实现详解核心代码展示改进点说明实战演练:从Excel到

SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程

《SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程》本文详细介绍了如何在虚拟机和宝塔面板中安装RabbitMQ,并使用Java代码实现消息的发送和接收,通过异步通讯,可以优化... 目录一、RabbitMQ安装二、启动RabbitMQ三、javascript编写Java代码1、引入

Nginx设置连接超时并进行测试的方法步骤

《Nginx设置连接超时并进行测试的方法步骤》在高并发场景下,如果客户端与服务器的连接长时间未响应,会占用大量的系统资源,影响其他正常请求的处理效率,为了解决这个问题,可以通过设置Nginx的连接... 目录设置连接超时目的操作步骤测试连接超时测试方法:总结:设置连接超时目的设置客户端与服务器之间的连接

ElasticSearch+Kibana通过Docker部署到Linux服务器中操作方法

《ElasticSearch+Kibana通过Docker部署到Linux服务器中操作方法》本文介绍了Elasticsearch的基本概念,包括文档和字段、索引和映射,还详细描述了如何通过Docker... 目录1、ElasticSearch概念2、ElasticSearch、Kibana和IK分词器部署

部署Vue项目到服务器后404错误的原因及解决方案

《部署Vue项目到服务器后404错误的原因及解决方案》文章介绍了Vue项目部署步骤以及404错误的解决方案,部署步骤包括构建项目、上传文件、配置Web服务器、重启Nginx和访问域名,404错误通常是... 目录一、vue项目部署步骤二、404错误原因及解决方案错误场景原因分析解决方案一、Vue项目部署步骤

Linux流媒体服务器部署流程

《Linux流媒体服务器部署流程》文章详细介绍了流媒体服务器的部署步骤,包括更新系统、安装依赖组件、编译安装Nginx和RTMP模块、配置Nginx和FFmpeg,以及测试流媒体服务器的搭建... 目录流媒体服务器部署部署安装1.更新系统2.安装依赖组件3.解压4.编译安装(添加RTMP和openssl模块

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

redis群集简单部署过程

《redis群集简单部署过程》文章介绍了Redis,一个高性能的键值存储系统,其支持多种数据结构和命令,它还讨论了Redis的服务器端架构、数据存储和获取、协议和命令、高可用性方案、缓存机制以及监控和... 目录Redis介绍1. 基本概念2. 服务器端3. 存储和获取数据4. 协议和命令5. 高可用性6.

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll