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

相关文章

使用Python进行GRPC和Dubbo协议的高级测试

《使用Python进行GRPC和Dubbo协议的高级测试》GRPC(GoogleRemoteProcedureCall)是一种高性能、开源的远程过程调用(RPC)框架,Dubbo是一种高性能的分布式服... 目录01 GRPC测试安装gRPC编写.proto文件实现服务02 Dubbo测试1. 安装Dubb

Python的端到端测试框架SeleniumBase使用解读

《Python的端到端测试框架SeleniumBase使用解读》:本文主要介绍Python的端到端测试框架SeleniumBase使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全... 目录SeleniumBase详细介绍及用法指南什么是 SeleniumBase?SeleniumBase

基于Python实现智能天气提醒助手

《基于Python实现智能天气提醒助手》这篇文章主要来和大家分享一个实用的Python天气提醒助手开发方案,这个工具可以方便地集成到青龙面板或其他调度框架中使用,有需要的小伙伴可以参考一下... 目录项目概述核心功能技术实现1. 天气API集成2. AI建议生成3. 消息推送环境配置使用方法完整代码项目特点

python多线程并发测试过程

《python多线程并发测试过程》:本文主要介绍python多线程并发测试过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、并发与并行?二、同步与异步的概念?三、线程与进程的区别?需求1:多线程执行不同任务需求2:多线程执行相同任务总结一、并发与并行?1、

JavaScript实战:智能密码生成器开发指南

本文通过JavaScript实战开发智能密码生成器,详解如何运用crypto.getRandomValues实现加密级随机密码生成,包含多字符组合、安全强度可视化、易混淆字符排除等企业级功能。学习密码强度检测算法与信息熵计算原理,获取可直接嵌入项目的完整代码,提升Web应用的安全开发能力 目录

Web技术与Nginx网站环境部署教程

《Web技术与Nginx网站环境部署教程》:本文主要介绍Web技术与Nginx网站环境部署教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、Web基础1.域名系统DNS2.Hosts文件3.DNS4.域名注册二.网页与html1.网页概述2.HTML概述3.

利用Python实现Excel文件智能合并工具

《利用Python实现Excel文件智能合并工具》有时候,我们需要将多个Excel文件按照特定顺序合并成一个文件,这样可以更方便地进行后续的数据处理和分析,下面我们看看如何使用Python实现Exce... 目录运行结果为什么需要这个工具技术实现工具的核心功能代码解析使用示例工具优化与扩展有时候,我们需要将

Nginx使用Keepalived部署web集群(高可用高性能负载均衡)实战案例

《Nginx使用Keepalived部署web集群(高可用高性能负载均衡)实战案例》本文介绍Nginx+Keepalived实现Web集群高可用负载均衡的部署与测试,涵盖架构设计、环境配置、健康检查、... 目录前言一、架构设计二、环境准备三、案例部署配置 前端 Keepalived配置 前端 Nginx

ubuntu如何部署Dify以及安装Docker? Dify安装部署指南

《ubuntu如何部署Dify以及安装Docker?Dify安装部署指南》Dify是一个开源的大模型应用开发平台,允许用户快速构建和部署基于大语言模型的应用,ubuntu如何部署Dify呢?详细请... Dify是个不错的开源LLM应用开发平台,提供从 Agent 构建到 AI workflow 编排、RA

ubuntu16.04如何部署dify? 在Linux上安装部署Dify的技巧

《ubuntu16.04如何部署dify?在Linux上安装部署Dify的技巧》随着云计算和容器技术的快速发展,Docker已经成为现代软件开发和部署的重要工具之一,Dify作为一款优秀的云原生应用... Dify 是一个基于 docker 的工作流管理工具,旨在简化机器学习和数据科学领域的多步骤工作流。它