跳转至

合约交互

Deploy

ContractContainer.deploy()

https://eth-brownie.readthedocs.io/en/stable/api-network.html#ContractContainer.deploy

s = SimpleStorage.deploy(*args , {"from": account, "交易参数": xxx}, publish_source=False)
"""
*args: Contract constructor arguments
transaction parameters dict(可选参数)
    docs: https://eth-brownie.readthedocs.io/en/stable/core-contracts.html#transaction-parameters
    如果没有指定from,默认使用合约地址
publish_source: When True, attempts to verify the source code on etherscan.io
"""

deploy 成功后返回合约实例(ProjectContract),存储到 ContractContainer 列表

记录:demo-brownie/build/deployments/map.json

>>> s  # 返回最新的合约:<SimpleStorage Contract '0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6'>
>>> SimpleStorage  # 返回deployed的合约列表:[<SimpleStorage Contract '0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87'>, <SimpleStorage Contract '0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6'>]
>>> SimpleStorage[-1]  # 即最新deployed的合约

>>> dir(s)
[
    abi, address, bytecode, events, selectors, signatures, topics, tx  # 内置属性
    balance, decode_input, get_method, get_method_object, info  # 内置方法
    store, retrieve, addPerson, nameToFavoriteNumber, personList  # 自定义方法和属性
]

Account.deploy()

https://eth-brownie.readthedocs.io/en/stable/api-network.html#Account.deploy

Account.deploy(contract, *args, amount=None, gas_limit=None, gas_price=None, max_fee=None, priority_fee=None, nonce=None, required_confs=1, allow_revert=False, silent=False, publish_source=False)
"""
contract: ContractContainer部署后的实例
*args: Contract constructor arguments
amount~allow_revert: transaction parameters(不包含from字段的account,因为本身是由account调用的)
silent: When True, suppresses any console output for the deployment.
publish_source: When True, attempts to verify the source code on etherscan.io.
"""
# 成功后返回Contract实例,失败返回TransactionReceipt

与项目外合约交互

https://eth-brownie.readthedocs.io/en/stable/core-contracts.html#contracts-outside-of-your-project

from brownie import Contract, interface

# 通过interfaces/DemoInterface.sol
interface.Demo(address, owner=None)

# 通过abi
Contract.from_abi("contract_name", "contract_address", "contract_abi")

# 从Etherscan获取
Contract.from_explorer("contract_address")

# 缓存
Contract("contract_address")

Transactions

# account0 向 account1 转账 1e18 Wei
Demo[-1].transfer(accounts[1], 1e18, {'from': accounts[0]})

Calls

In Solidity, callable methods are labelled as view or pure

Demo[-1].balanceOf(accounts[0])

# 或者
Demo[-1].transfer.call(accounts[1], 1e18, {'from': accounts[0]})