4.1.6 Contracts

Contracts

值得花時(shí)間了解合同的所有內(nèi)容菩佑。要開始口锭,請(qǐng)查看此示例:

Contract Deployment Example

要運(yùn)行此示例,需要安裝一些額外的功能:

  • eth-tester提供的沙箱節(jié)點(diǎn)。您可以使用 pip install -U web3[tester] 進(jìn)行安裝。
  • solc solidity編譯器捞慌。請(qǐng)參閱安裝 Solidity Compiler
import json
import web3

from web3 import Web3
from solc import compile_source
from web3.contract import ConciseContract

# Solidity source code
contract_source_code = '''
pragma solidity ^0.4.21;

contract Greeter {
    string public greeting;

    function Greeter() public {
        greeting = 'Hello';
    }

    function setGreeting(string _greeting) public {
        greeting = _greeting;
    }

    function greet() view public returns (string) {
        return greeting;
    }
}
'''

compiled_sol = compile_source(contract_source_code) # Compiled source code
contract_interface = compiled_sol['<stdin>:Greeter']

# web3.py instance
w3 = Web3(Web3.EthereumTesterProvider())

# set pre-funded account as sender
w3.eth.defaultAccount = w3.eth.accounts[0]

# Instantiate and deploy contract
Greeter = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])

# Submit the transaction that deploys the contract
tx_hash = Greeter.constructor().transact()

# Wait for the transaction to be mined, and get the transaction receipt
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)

# Create the contract instance with the newly-deployed address
greeter = w3.eth.contract(
    address=tx_receipt.contractAddress,
    abi=contract_interface['abi'],
)

# Display the default greeting from the contract
print('Default contract greeting: {}'.format(
    greeter.functions.greet().call()
))

print('Setting the greeting to Nihao...')
tx_hash = greeter.functions.setGreeting('Nihao').transact()

# Wait for transaction to be mined...
w3.eth.waitForTransactionReceipt(tx_hash)

# Display the new greeting value
print('Updated contract greeting: {}'.format(
    greeter.functions.greet().call()
))

# When issuing a lot of reads, try this more concise reader:
reader = ConciseContract(greeter)
assert reader.greet() == "Nihao"

Contract Factories

這些工廠不打算直接初始化柬批。而是使用 w3.eth.contract() 方法創(chuàng)建合約對(duì)象卿闹。默認(rèn)情況下,合約工廠是 Contract萝快。請(qǐng)參閱 ConciseContract 中的示例以指定備用工廠。

class web3.contract.Contract(address)

Contract 提供了一個(gè)默認(rèn)接口著角,用于部署以及與以太坊智能合約交互揪漩。

address參數(shù)可以是十六進(jìn)制地址或ENS名稱,如 mycontract.eth吏口。

class web3.contract.ConciseContract(Contract())

Contract 的這種變體旨在實(shí)現(xiàn)更簡(jiǎn)潔的讀訪問(wèn)奄容,而不會(huì)使寫訪問(wèn)更加冗長(zhǎng)。這是以失去對(duì) deploy()address 等屬性的訪問(wèn)權(quán)為代價(jià)的产徊。建議對(duì)這些用例使用classic Contract昂勒。為了清楚起見,ConciseContract 僅公開合約函數(shù)舟铜,并且 ConciseContract API不提供所有其他 Contract 類方法和屬性戈盈。這包括但不限于 contract.addresscontract.abicontract.deploy()谆刨。

通過(guò)將 Contract 實(shí)例傳遞給 ConciseContract 來(lái)創(chuàng)建此類合約:

>>> concise = ConciseContract(myContract)

此變體將所有方法作為 call 調(diào)用塘娶,因此如果經(jīng)典 Contract 具有類似 contract.functions.owner().call() 的方法,則可以使用 concise.owner() 來(lái)調(diào)用它痊夭。

要訪問(wèn)發(fā)送交易或估計(jì) gas刁岸,可以添加關(guān)鍵字參數(shù),如下所示:

>>> concise.withdraw(amount, transact={'from': eth.accounts[1], 'gas': 100000, ...})

>>>  # which is equivalent to this transaction in the classic contract:

>>> contract.functions.withdraw(amount).transact({'from': eth.accounts[1], 'gas': 100000, ...})
class web3.contract.ImplicitContract(Contract())

這種變化反映了 ConciseContract她我,但它將所有方法作為交易而不是 call 來(lái)調(diào)用虹曙,因此如果經(jīng)典 Contract 有類似 contract.functions.owner.transact() 的方法迫横,則可以使用 implicit.owner() 來(lái)調(diào)用它。

通過(guò)將 Contract 實(shí)例傳遞給 ImplicitContract 來(lái)創(chuàng)建此類合約:

>>> concise = ImplicitContract(myContract)

Properties

每個(gè)合約工廠都公開以下屬性酝碳。

Contract.address

十六進(jìn)制編碼的合同的20字節(jié)地址矾踱,或ENS名稱。如果在工廠創(chuàng)建期間未提供击敌,則可以為無(wú)介返。

Contract.abi

合約ABI數(shù)組。

Contract.bytecode

合約字節(jié)碼字符串沃斤。如果在工廠創(chuàng)建期間未提供圣蝎,則可以為 None

Contract.bytecode_runtime

合約字節(jié)碼字符串的運(yùn)行時(shí)部分衡瓶。如果在工廠創(chuàng)建期間未提供徘公,則可以為 None

Contract.functions

這提供了對(duì)合約函數(shù)作為屬性的訪問(wèn)哮针。例如:myContract.functions.MyMethod()关面。公開的合約函數(shù)是 ContractFunction 類型的類蠢挡。

Contract.events

這提供了作為屬性訪問(wèn)合約事件的權(quán)限廊酣。例如:myContract.events.MyEvent()傀缩。公開的合約事件是 ContractEvent 類型的類瘫想。

Methods

每個(gè)合約工廠都公開以下方法热幔。

classmethod Contract.constructor(*args, **kwargs).transact(transaction=None)

通過(guò)發(fā)送新的公開交易來(lái)構(gòu)建和部署合約渺绒。

如果提供的 transaction 應(yīng)該是符合 web3.eth.sendTransaction(transaction) 方法的字典歹叮。此值可能不包含 datato哗讥。

如果合約采用構(gòu)造函數(shù)參數(shù)包颁,則應(yīng)將它們作為位置參數(shù)或關(guān)鍵字參數(shù)提供瞻想。

如果ABI中指定的任何參數(shù)是 address 類型,則它們將接受ENS名稱娩嚼。

如果未提供 gas 值蘑险,則將使用 web3.eth.estimateGas() 方法創(chuàng)建部署交易的 gas 值。

返回部署交易的交易哈希岳悟。

>>> deploy_txn = token_contract.constructor(web3.eth.coinbase, 12345).transact()
>>> txn_receipt = web3.eth.getTransactionReceipt(deploy_txn)
>>> txn_receipt['contractAddress']
'0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318'
classmethod Contract.constructor(*args, **kwargs).estimateGas(transaction=None)

估算構(gòu)造和部署合約的 gas佃迄。

此方法與 Contract.constructor(*args,**kwargs).transact() 方法的行為相同贵少,交易詳細(xì)信息傳遞到函數(shù)調(diào)用的結(jié)尾部分和屎,函數(shù)參數(shù)傳遞到第一部分。

返回消耗的 gas春瞬,可用作公開執(zhí)行此交易的 gas 估算值柴信。

返回部署合約所需的 gas。

>>> token_contract.constructor(web3.eth.coinbase, 12345).estimateGas()
12563
classmethod Contract.constructor(*args, **kwargs).buildTransaction(transaction=None)

構(gòu)造合約部署交易字節(jié)碼數(shù)據(jù)宽气。

如果合約采用構(gòu)造函數(shù)參數(shù)随常,則應(yīng)將它們作為位置參數(shù)或關(guān)鍵字參數(shù)提供潜沦。

如果ABI中指定的任何args是地址類型,則它們將接受ENS名稱绪氛。

返回可以傳遞給sendTransaction方法的交易字典唆鸡。

>>> transaction = {
'gasPrice': w3.eth.gasPrice,
'chainId': None
}
>>> contract_data = token_contract.constructor(web3.eth.coinbase, 12345).buildTransaction(transaction)
>>> web3.eth.sendTransaction(contract_data)
Contract.events.<event name>.createFilter(fromBlock=block, toBlock=block, argument_filters={"arg1": "value"}, topics=[])

創(chuàng)建一個(gè)新的事件過(guò)濾器,即 web3.utils.filters.LogFilter 的一個(gè)實(shí)例枣察。

fromBlock 是必填字段争占。定義起始區(qū)塊(獨(dú)占)過(guò)濾區(qū)塊范圍。它可以是起始區(qū)塊編號(hào)序目,也可以是最后一個(gè)挖掘塊的 latest臂痕,或者是 pending 的交易。在 fromBlock 的情況下猿涨,'latest' 和 'pending' 將 'latest' 或 'pending' 區(qū)塊設(shè)置為起始過(guò)濾區(qū)塊的靜態(tài)值握童。toBlock 可選。默認(rèn)為 latest叛赚。 澡绩。定義過(guò)濾器區(qū)塊范圍中的結(jié)束區(qū)塊(包括)。特殊值 latestpending 設(shè)置動(dòng)態(tài)范圍俺附,該范圍始終包括過(guò)濾器上部區(qū)塊范圍的 latestpending 塊肥卡。address 可選。默認(rèn)合約地址事镣。過(guò)濾器匹配從 address 發(fā)出的事件日志步鉴。 argument_filters,可選蛮浑。期待參數(shù)名稱和值的字典。提供事件日志時(shí)只嚣,會(huì)針對(duì)事件參數(shù)值進(jìn)行過(guò)濾沮稚。事件參數(shù)既可以是索引的,也可以是非索引的册舞。索引值可以轉(zhuǎn)換為相應(yīng)的主題參數(shù)蕴掏。未使用索引的參數(shù)將使用正則表達(dá)式進(jìn)行過(guò)濾。topics 可選调鲸,接受標(biāo)準(zhǔn)的 JSON-RPC 主題參數(shù)盛杰。有關(guān) topic 參數(shù)的更多信息,請(qǐng)參閱 eth_newFilter 的JSON-RPC文檔藐石。

classmethod Contract.eventFilter(event_name, filter_params=None)

Warning

Contract.eventFilter() 已棄用 即供,替換為 Contract.events.<event name>.createFilter()

創(chuàng)建一個(gè)新的 web3.utils.filters.LogFilter 實(shí)例。

event_name 參數(shù)應(yīng)該是要篩選的合約事件的名稱于微。

如果提供逗嫡,filter_params 應(yīng)該是一個(gè)字典青自,為日志條目指定其他過(guò)濾器。支持以下鍵驱证。

  • filter: dictionary - (可選)字典鍵應(yīng)該是 Event 參數(shù)的參數(shù)名稱延窜。字典值應(yīng)該是要過(guò)濾的值,或者要過(guò)濾的值列表抹锄。值列表將匹配其參數(shù)與列表中的任何值匹配的日志條目逆瑞。接受索引和未索引的事件參數(shù)。使用 filter 參數(shù)時(shí)伙单,內(nèi)部處理索引參數(shù)值到十六進(jìn)制編碼主題的處理获高。
  • fromBlock: integer/tag - (可選,默認(rèn):latest)整數(shù)區(qū)塊編號(hào)车份,或最后一個(gè)已開采塊的 latestpending 的交易谋减,earliest 為最早的區(qū)塊。
  • toBlock: integer/tag - (可選扫沼,默認(rèn):latest)整數(shù)區(qū)塊編號(hào)出爹,或最后一個(gè)已開采塊的 latestpending 的交易,earliest 為最早的區(qū)塊缎除。
  • address: string or list of strings, each 20 Bytes - (可選)合約地址或日志應(yīng)來(lái)自的地址列表严就。
    topics: list of 32 byte strings or null - (可選)應(yīng)該用于過(guò)濾的主題數(shù)組,事件簽名的 keccak 哈希作為第一項(xiàng)器罐,其余項(xiàng)目作為十六進(jìn)制編碼的參數(shù)值梢为。主題依賴于順序。此參數(shù)也可以是主題列表的列表轰坊,在這種情況下铸董,過(guò)濾將匹配任何提供的主題數(shù)組。當(dāng)不希望通過(guò) filter 參數(shù)依賴內(nèi)部生成的主題列表時(shí)肴沫,此參數(shù)很有用粟害。如果 filter 參數(shù)包含 topic,則 topics 將添加到從 filter 參數(shù)推斷出的任何主題列表中颤芬。

event_name 指定的事件的事件主題將添加到 filter_params['topics'] 列表中悲幅。

如果此合約的 Contract.address 屬性為 non-null,則合約地址將添加到 filter_params站蝠。

classmethod Contract.deploy(transaction=None, args=None)

Warning

不推薦使用:不推薦使用此方法汰具,而使用 `constructor()`,這提供了更大的靈活性菱魔。

構(gòu)建并發(fā)送交易以部署合同留荔。

如果提供的 transaction 應(yīng)該是符合 web3.eth.sendTransaction(transaction) 方法的字典。此值可能不包含 datato澜倦。

如果合約采用構(gòu)造函數(shù)參數(shù)存谎,則應(yīng)通過(guò) args 參數(shù)將其作為列表提供拔疚。

如果ABI中指定的任何 argsaddress 類型,則它們將接受ENS名稱既荚。

如果未提供 gas稚失,則將使用 web3.eth.estimateGas() 方法創(chuàng)建部署交易的 gas

返回部署交易的交易哈希恰聘。

classmethod Contract.all_functions()

返回 Contract 中存在的所有函數(shù)的列表句各,其中每個(gè)函數(shù)都是 ContractFunction 的一個(gè)實(shí)例。

>>> contract.all_functions()
[<Function identity(uint256,bool)>, <Function identity(int256,bool)>]
classmethod Contract.get_function_by_signature(signature)

搜索具有匹配簽名的獨(dú)特函數(shù)晴叨。找到匹配項(xiàng)后返回 ContractFunction 的實(shí)例凿宾。如果未找到匹配項(xiàng),則拋出 ValueError兼蕊。

>>> contract.get_function_by_signature('identity(uint256,bool)')
<Function identity(uint256,bool)>
classmethod Contract.find_functions_by_name(name)

搜索具有匹配名稱的所有函數(shù)初厚。返回匹配函數(shù)的列表,其中每個(gè)函數(shù)都是 ContractFunction 的實(shí)例孙技。找不到匹配項(xiàng)時(shí)返回空列表产禾。

>>> contract.find_functions_by_name('identity')
[<Function identity(uint256,bool)>, <Function identity(int256,bool)>]
classmethod Contract.get_function_by_name(name)

搜索具有匹配名稱的獨(dú)特函數(shù)。找到匹配項(xiàng)后返回 ContractFunction 的實(shí)例牵啦。如果未找到匹配項(xiàng)或者找到多個(gè)匹配項(xiàng)亚情,則拋出 ValueError

>>> contract.get_function_by_name('unique_name')
<Function unique_name(uint256)>
classmethod Contract.get_function_by_selector(selector)

使用匹配選擇器搜索不同的函數(shù)哈雏。選擇器可以是十六進(jìn)制字符串楞件,bytes或int。找到匹配項(xiàng)后返回 ContractFunction 的實(shí)例裳瘪。如果未找到匹配項(xiàng)土浸,則拋出 ValueError

>>> contract.get_function_by_selector('0xac37eebb')
<Function identity(uint256)'>
>>> contract.get_function_by_selector(b'\xac7\xee\xbb')
<Function identity(uint256)'>
>>> contract.get_function_by_selector(0xac37eebb)
<Function identity(uint256)'>
classmethod Contract.find_functions_by_args(*args)

搜索具有匹配args的所有函數(shù)彭羹。返回匹配函數(shù)的列表黄伊,其中每個(gè)函數(shù)都是 ContractFunction 的實(shí)例。找不到匹配項(xiàng)時(shí)返回空列表皆怕。

>>> contract.find_functions_by_args(1, True)
[<Function identity(uint256,bool)>, <Function identity(int256,bool)>]
classmethod Contract.get_function_by_args(*args)

使用匹配的args搜索不同的函數(shù)毅舆。找到匹配項(xiàng)后返回 ContractFunction 的實(shí)例西篓。如果未找到匹配項(xiàng)或者找到多個(gè)匹配項(xiàng)愈腾,則拋出 ValueError

Note

合約方法 *all_functions*岂津,*get_function_by_signature*虱黄,*find_functions_by_name*,*get_function_by_name*吮成,*get_function_by_selector*橱乱,*find_functions_by_args* 和 *get_function_by_args* 只能在向合約提供了abi時(shí)使用辜梳。

Note
Web3.py 拒絕具有多個(gè)具有相同選擇器或簽名的函數(shù)的合同的初始化。例如泳叠。 blockHashAddendsInexpansible(uint256)blockHashAskewLimitary(uint256) 具有相同的選擇器值作瞄,等于 0x00000000。包含這兩項(xiàng)功能的合約將被拒絕危纫。

Invoke Ambiguous Contract Functions Example

下面是具有多個(gè)相同名稱的函數(shù)的合約示例宗挥,并且參數(shù)有歧義。

>>> contract_source_code = '''
pragma solidity ^0.4.21;
contract AmbiguousDuo {
  function identity(uint256 input, bool uselessFlag) returns (uint256) {
    return input;
  }
  function identity(int256 input, bool uselessFlag) returns (int256) {
    return input;
  }
}
'''
# fast forward all the steps of compiling and deploying the contract.
>>> ambiguous_contract.functions.identity(1, True) # raises ValidationError

>>> identity_func = ambiguous_contract.get_function_by_signature('identity(uint256,bool)')
>>> identity_func(1, True)
<Function identity(uint256,bool) bound to (1, True)>
>>> identity_func(1, True).call()
1

Event Log Object

事件日志對(duì)象是一個(gè)python字典种蝶,包含以下鍵:

  • args: Dictionary - 來(lái)自事件的參數(shù)契耿。
  • event: String - 事件名。
  • logIndex: Number - 區(qū)塊中日志索引位置的整數(shù)螃征。
  • transactionIndex: Number - 從中創(chuàng)建了交易索引位置日志的整數(shù)搪桂。
  • transactionHash: String, 32 Bytes - 此日志創(chuàng)建的交易的哈希值。
  • address: String, 32 Bytes - 此日志源自的合約地址盯滚。
  • blockHash: String, 32 Bytes -
    此日志所在區(qū)塊的哈希值踢械。當(dāng)其掛起時(shí)為 null
  • blockNumber: Number -
    此日志所在的區(qū)塊編號(hào)淌山。當(dāng)其掛起時(shí)為 null裸燎。
>>> transfer_filter = my_token_contract.eventFilter('Transfer', {'filter': {'_from': '0xdc3a9db694bcdd55ebae4a89b22ac6d12b3f0c24'}})
>>> transfer_filter.get_new_entries()
[...]  # array of Event Log Objects that match the filter.

# wait a while...

>>> transfer_filter.get_new_entries()
[...]  # new events since the last call

>>> transfer_filter.get_all_entries()
[...]  # all events that match the filter.

Contract Functions

class web3.contract.ContractFunction

通過(guò) Contract.functions 屬性公開的命名函數(shù)屬于 ContractFunction 類型。這個(gè)類不能直接使用泼疑,而是通過(guò) Contract.functions德绿。

例如:

myContract = web3.eth.contract(address=contract_address, abi=contract_abi)
twentyone = myContract.functions.multiply7(3).call()

如果在變量中有函數(shù)名稱,則可能更喜歡以下替代方法:

func_to_call = 'multiply7'
contract_func = myContract.functions[func_to_call]
twentyone = contract_func(3).call()

ContractFunction 提供與合約函數(shù)交互的方法退渗。提供給合約函數(shù)子類的位置和關(guān)鍵字參數(shù)將用于通過(guò)簽名查找合約函數(shù)移稳,并在適用時(shí)轉(zhuǎn)發(fā)給合約函數(shù)。

Methods

ContractFunction.transact(transaction)

通過(guò)發(fā)送新的公共交易來(lái)執(zhí)行指定的函數(shù)会油。

請(qǐng)參閱以下調(diào)用:

myContract.functions.myMethod(*args, **kwargs).transact(transaction)

函數(shù)調(diào)用的第一部分 myMethod(*args, **kwargs) 根據(jù)名稱和提供的參數(shù)選擇適當(dāng)?shù)暮霞s函數(shù)个粱。參數(shù)可以作為位置參數(shù),關(guān)鍵字參數(shù)或兩者的混合提供翻翩。

此函數(shù)調(diào)用 transact(transaction) 的結(jié)尾部分采用單個(gè)參數(shù)都许,該參數(shù)應(yīng)該是符合與 web3.eth.sendTransaction(transaction) 方法相同格式的python字典。該字典可能不包含密鑰數(shù)據(jù)嫂冻。

如果ABI中指定的任何 argskwargsaddress 類型胶征,則它們將接受ENS名稱。

如果未提供 gas 值桨仿,則將使用 web3.eth.estimateGas() 方法創(chuàng)建方法事務(wù)的 gas 值睛低。

返回交易哈希。

>>> token_contract.functions.transfer(web3.eth.accounts[1], 12345).transact()
"0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd"
ContractFunction.call(transaction, block_identifier='latest')

調(diào)用合約函數(shù),使用 eth_call API在本地執(zhí)行交易钱雷。這不會(huì)創(chuàng)建新的公共交易骂铁。

請(qǐng)參閱以下調(diào)用:

myContract.functions.myMethod(*args, **kwargs).call(transaction)

此方法與 ContractFunction.transact() 方法的行為相同,交易詳細(xì)信息傳遞到函數(shù)調(diào)用的結(jié)尾部分罩抗,函數(shù)參數(shù)傳遞到第一部分拉庵。

返回已執(zhí)行函數(shù)的返回值。

>>> my_contract.functions.multiply7(3).call()
21
>>> token_contract.functions.myBalance().call({'from': web3.eth.coinbase})
12345  # the token balance for `web3.eth.coinbase`
>>> token_contract.functions.myBalance().call({'from': web3.eth.accounts[1]})
54321  # the token balance for the account `web3.eth.accounts[1]`

可以使用 block_identifier 在歷史塊中調(diào)用該方法套蒂。一些例子:

# You can call your contract method at a block number:
>>> token_contract.functions.myBalance().call(block_identifier=10)

# or a number of blocks back from pending,
# in this case, the block just before the latest block:
>>> token_contract.functions.myBalance().call(block_identifier=-2)

# or a block hash:
>>> token_contract.functions.myBalance().call(block_identifier='0x4ff4a38b278ab49f7739d3a4ed4e12714386a9fdf72192f2e8f7da7822f10b4d')
>>> token_contract.functions.myBalance().call(block_identifier=b'O\xf4\xa3\x8b\'\x8a\xb4\x9fw9\xd3\xa4\xedN\x12qC\x86\xa9\xfd\xf7!\x92\xf2\xe8\xf7\xdax"\xf1\x0bM')

# Latest is the default, so this is redundant:
>>> token_contract.functions.myBalance().call(block_identifier='latest')

# You can check the state after your pending transactions (if supported by your node):
>>> token_contract.functions.myBalance().call(block_identifier='pending')
ContractFunction.estimateGas(transaction)

調(diào)用合約函數(shù)名段,使用 eth_call API在本地執(zhí)行交易。這不會(huì)創(chuàng)建新的公共交易泣懊。

請(qǐng)參閱以下調(diào)用:

myContract.functions.myMethod(*args, **kwargs).estimateGas(transaction)

此方法與 ContractFunction.transact() 方法的行為相同伸辟,交易詳細(xì)信息傳遞到函數(shù)調(diào)用的結(jié)尾部分,函數(shù)參數(shù)傳遞到第一部分馍刮。

返回消耗的 gas 量信夫,可用作公開執(zhí)行此交易的 gas 估算值。

>>> my_contract.functions.multiply7(3).estimateGas()
42650
ContractFunction.buildTransaction(transaction)

根據(jù)指定的合約函數(shù)調(diào)用構(gòu)建交易字典卡啰。

請(qǐng)參閱以下調(diào)用:

myContract.functions.myMethod(*args, **kwargs).buildTransaction(transaction)

此方法的行為與 Contract.transact() 方法相同静稻,交易詳細(xì)信息傳遞到函數(shù)調(diào)用的結(jié)尾部分,函數(shù)參數(shù)傳遞到第一部分匈辱。

Note

除非在函數(shù)調(diào)用的第一部分中指定振湾,否則 *nonce* 不會(huì)作為交易字典的一部分返回:
>>> math_contract.functions.increment(5).buildTransaction({'nonce': 10})
可以使用 `getTransactionCount()` 來(lái)獲取帳戶的當(dāng)前 nonce。因此亡脸,生成包含隨機(jī)數(shù)的交易字典的快捷方式如下所示:
>>> math_contract.functions.increment(5).buildTransaction({'nonce': web3.eth.getTransactionCount('0xF5...')})

返回一個(gè)交易字典押搪。然后可以使用 sendTransaction() 發(fā)送此交易字典。

此外浅碾,字典可以使用 signTransaction() 用于脫機(jī)交易簽名大州。

>>> math_contract.functions.increment(5).buildTransaction({'gasPrice': 21000000000})
{
    'to': '0x6Bc272FCFcf89C14cebFC57B8f1543F5137F97dE',
    'data': '0x7cf5dab00000000000000000000000000000000000000000000000000000000000000005',
    'value': 0,
    'gas': 43242,
    'gasPrice': 21000000000,
    'chainId': 1
}

Fallback Function

Contract Factory還提供了一個(gè)與 fallback 函數(shù)交互的API,它支持四種方法垂谢,如普通函數(shù):

Contract.fallback.call(transaction)

調(diào)用回退函數(shù)厦画,使用 eth_call API在本地執(zhí)行交易。這不會(huì)創(chuàng)建新的公共交易滥朱。

Contract.fallback.estimateGas(transaction)

調(diào)用回退功能并返回 gas 估算根暑。

Contract.fallback.transact(transaction)

通過(guò)發(fā)送新的公共交易來(lái)執(zhí)行回退功能。

Contract.fallback.buildTransaction(transaction)

根據(jù)合約回退函數(shù)調(diào)用構(gòu)建交易字典徙邻。

Events

class web3.contract.ContractEvents

通過(guò) Contract.events 屬性公開的命名事件屬于ContractEvents類型排嫌。這個(gè)類不能直接使用,而是通過(guò) Contract.events鹃栽。

例如:

myContract = web3.eth.contract(address=contract_address, abi=contract_abi)
tx_hash = myContract.functions.myFunction().transact()
receipt = web3.eth.getTransactionReceipt(tx_hash)
myContract.events.myEvent().processReceipt(receipt)

ContractEvent 提供與合約事件交互的方法躏率。提供給合約事件子類的位置和關(guān)鍵字參數(shù)將用于通過(guò)簽名查找合約事件。

ContractEvents.myEvent(*args, **kwargs).processReceipt(transaction_receipt)

從交易收據(jù)中提取相關(guān)日志民鼓。

返回事件日志對(duì)象的元組薇芝,從事件(例如 myEvent)發(fā)出,帶有解碼輸出丰嘉。

>>> tx_hash = contract.functions.myFunction(12345).transact({'to':contract_address})
>>> tx_receipt = w3.eth.getTransactionReceipt(tx_hash)
>>> rich_logs = contract.events.myEvent().processReceipt(tx_receipt)
>>> rich_logs[0]['args']
{'myArg': 12345}

Utils

classmethod Contract.decode_function_input(data)

解碼用于調(diào)用智能合約函數(shù)的交易數(shù)據(jù)夯到,并將ContractFunction和已解碼的參數(shù)作為 dict 返回。

項(xiàng)目源代碼

項(xiàng)目源代碼會(huì)逐步上傳到 Github饮亏,地址為 https://github.com/windstamp/jsonrpc耍贾。

Contributor

  1. Windstamp, https://github.com/windstamp

Reference

  1. https://web3py.readthedocs.io/en/stable/
  2. http://web3py.readthedocs.io
  3. https://github.com/ethereum/web3.py
  4. https://solidity.readthedocs.io/en/latest/installing-solidity.html#binary-packages
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市路幸,隨后出現(xiàn)的幾起案子荐开,更是在濱河造成了極大的恐慌,老刑警劉巖简肴,帶你破解...
    沈念sama閱讀 219,110評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件晃听,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡砰识,警方通過(guò)查閱死者的電腦和手機(jī)能扒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)辫狼,“玉大人初斑,你說(shuō)我怎么就攤上這事∨虼Γ” “怎么了见秤?”我有些...
    開封第一講書人閱讀 165,474評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)真椿。 經(jīng)常有香客問(wèn)我秦叛,道長(zhǎng),這世上最難降的妖魔是什么瀑粥? 我笑而不...
    開封第一講書人閱讀 58,881評(píng)論 1 295
  • 正文 為了忘掉前任挣跋,我火速辦了婚禮,結(jié)果婚禮上狞换,老公的妹妹穿的比我還像新娘避咆。我一直安慰自己,他們只是感情好修噪,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,902評(píng)論 6 392
  • 文/花漫 我一把揭開白布查库。 她就那樣靜靜地躺著,像睡著了一般黄琼。 火紅的嫁衣襯著肌膚如雪樊销。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,698評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音围苫,去河邊找鬼裤园。 笑死,一個(gè)胖子當(dāng)著我的面吹牛剂府,可吹牛的內(nèi)容都是我干的拧揽。 我是一名探鬼主播,決...
    沈念sama閱讀 40,418評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼腺占,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼淤袜!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起衰伯,我...
    開封第一講書人閱讀 39,332評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤铡羡,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后意鲸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蓖墅,經(jīng)...
    沈念sama閱讀 45,796評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,968評(píng)論 3 337
  • 正文 我和宋清朗相戀三年临扮,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了论矾。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,110評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡杆勇,死狀恐怖贪壳,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蚜退,我是刑警寧澤闰靴,帶...
    沈念sama閱讀 35,792評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站钻注,受9級(jí)特大地震影響蚂且,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜幅恋,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,455評(píng)論 3 331
  • 文/蒙蒙 一杏死、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧捆交,春花似錦淑翼、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至肉瓦,卻和暖如春遭京,著一層夾襖步出監(jiān)牢的瞬間胃惜,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工哪雕, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留船殉,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,348評(píng)論 3 373
  • 正文 我出身青樓热监,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親饮寞。 傳聞我的和親對(duì)象是個(gè)殘疾皇子孝扛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,047評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容