通过send_raw_transaction发送交易

单击顶部栏上的🚀 -> Binder在线运行此示例!

这个例子展示了如何在不使用w3.wallet的情况下签名交易,并通过send_raw_transaction发送交易。这种方法更灵活,但同时使用起来也更复杂。如果你希望了解更简单的发送交易的方法,请参考Quickstart中发送交易的示例代码。

import pprint
from conflux_web3 import Web3
from conflux_web3.utils import fill_transaction_defaults

w3 = Web3(Web3.HTTPProvider("https://test.confluxrpc.com"))
account = w3.account.from_key("0x....") # 用你的私钥替换 "0x...."

手动发送交易

基本上,我们按照如下 4 步来发送交易:

  • 构造交易

  • 为交易签名

  • 向区块链节点发送交易

  • 等待交易执行结果

如果w3.wallet中添加了帐户,SDK 可以帮助将前三步一起完成,否则你需要手动完成前 3 步的内容。

构造一个简单的交易

我们在这里只提供必要的参数,其他参数由fill_transaction_defaults填充。也可以阅读从零开始构造交易来了解如何手动填充交易的每个字段。

built_trivial_tx = fill_transaction_defaults(w3, {
    'from': account.address,
    'to': w3.account.create().address,
    'value': 100,
})

为交易签名

signed_tx = account.sign_transaction(built_trivial_tx)

发送交易

h = w3.cfx.send_raw_transaction(signed_tx.rawTransaction)

等待交易执行完成

tx_receipt = h.executed()

与合约交互

# 如果需要从合约metadata文件创建合约对象, 使用如下代码
# >>> erc20_metadata = json.load(open("path/to/ERC20metadata.json"))
# >>> erc20 = web3.cfx.contract(bytecode=erc20_metadata["bytecode"], abi=erc20_metadata["abi"])
erc20 = w3.cfx.contract(name="ERC20")

# 构造交易
# 可以在`build_transaction`中额外指定'from', 'gasPrice' 等交易参数
built_constuct_tx = erc20.constructor(name="Coin", symbol="C", initialSupply=10**18).build_transaction({
    'from': account.address,
})
# 签名交易
construct_tx = account.sign_transaction(built_constuct_tx)
# 发送交易并等待执行结果
contract_address = w3.cfx.send_raw_transaction(construct_tx.rawTransaction).executed()['contractCreated']
print(f"deployed contract address: {contract_address}")
deployed contract address: cfxtest:acfgtrw53v4ju9jaydmr9yyf9xyvfxpe0e8ny2fd4d
# 与已部署的合约交互
contract = w3.cfx.contract(address=contract_address, name="ERC20")

# 构造交易
# 可以在`build_transaction`中额外指定'from', 'gasPrice' 等交易参数
built_transfer_tx = contract.functions.transfer(
    w3.account.create().address,
    100
).build_transaction({
    'from': account.address
})

# 签名交易
signed_transfer_tx = account.sign_transaction(
    built_transfer_tx
)

# 发送交易并等待执行结果
print("erc20 transfer receipt: ")
pprint.pprint(
    dict(w3.cfx.send_raw_transaction(signed_transfer_tx.rawTransaction).executed())
)
erc20 transfer receipt: 
{'blockHash': HexBytes('0x9b8a0a0e5eb33d67b2c85d4e951b0251e1b972cd00f7c18c53ecacb7fd7edfd3'),
 'contractCreated': None,
 'epochNumber': 99051304,
 'from': 'cfxtest:aanhtnrex2nj56kkbws4yx0jeab34ae16pcap53w13',
 'gasCoveredBySponsor': False,
 'gasFee': 37063000000000 Drip,
 'gasUsed': 37063,
 'index': 0,
 'logs': [AttributeDict({'address': 'cfxtest:acfgtrw53v4ju9jaydmr9yyf9xyvfxpe0e8ny2fd4d', 'topics': [HexBytes('0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'), HexBytes('0x0000000000000000000000001677ada49e168df1290c9daa4ec820039d0097e3'), HexBytes('0x0000000000000000000000001ab7c2bb12a3484451a55ed15285a4cf10196312')], 'data': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000064')})],
 'logsBloom': HexBytes('0x00000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000200008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000040000200000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000200000000400000000000000000000020000000000000000'),
 'outcomeStatus': 0,
 'stateRoot': HexBytes('0xa14515ac4ad59a0ab8b7c4c1740eb5a97d0b55eabf3b5a0b185867e41d1a1699'),
 'storageCollateralized': 64,
 'storageCoveredBySponsor': False,
 'storageReleased': [],
 'to': 'cfxtest:acfgtrw53v4ju9jaydmr9yyf9xyvfxpe0e8ny2fd4d',
 'transactionHash': HexBytes('0x224e75f10580194685cd2566bd7ec5fdefd09578fe770bddae2ba9f77842f11a'),
 'txExecErrorMsg': None}