# web3py 交互流程

By [cryptodw.eth](https://paragraph.com/@cryptodw) · 2022-06-12

---

`transaction`参数应该是包含以下字段的字典。

*   `from`: ，校验和地址或 ENS 名称 -（可选，默认值：） 发送交易的地址。`bytes or textweb3.eth.defaultAccount`
    
*   `to`: ，校验和地址或 ENS 名称 - （创建新合约时可选）交易指向的地址。`bytes or text`
    
*   `gas`: `integer`\- （可选）为交易执行提供的气体的整数。它将返回未使用的气体。
    
*   `maxFeePerGas`: - （可选）您愿意支付的最高金额，包括和。和之间的差额退还给用户。`integer`
    
*   `maxPriorityFeePerGas`: - （可选）支付给矿工的部分费用`integer or hex`
    
*   `gasPrice`: `integer`\- 用于每个付费 gas **LEGACY**的 gasPrice 的整数- 除非你有充分的理由使用`gasPrice`, 使用`maxFeePerGas` and`maxPriorityFeePerGas`代替。
    
*   `value`: `integer`\- （可选）与此交易一起发送的值的整数
    
*   `data`: - 合约的编译代码或调用的方法签名和编码参数的哈希值。有关详细信息，请参阅 [以太坊合约 ABI](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI)。`bytes or text`
    
*   `nonce`: `integer`\- （可选）随机数的整数。这允许覆盖您自己的使用相同 nonce 的待处理事务。
    

    from web3 import Web3
    import json
    
    rpc = '公链的RCP'
    # 链接网络
    w3 = Web3(Web3.HTTPProvider(rpc))
    # 如果是合约交互。就需要在获取合约地址和合约的ABI
    # 交互的地址
    address = '钱包地址' 
    # 如果要发送事务，就需要私钥
    private_key = '私钥'
    
    
    # 合约地址 
    contractAddress=  Web3.toCheckSumAddress('合约地址')
    # 合约ABI
    contractABI = json.loads('合约ABI')
    # 构建合约
    contract = w3.eth.contract(address=contractAddress, abi=contractABI)
    
    # 调用合约函数
    func = contract.functions.函数名()
    
    
    # get_nonce
    nonce = w3.eth.getTransactionCount(address)
    # 构建交易参数
    tx = {
    
        'nonce' : nonce,
        'to' : '交易接收的账户'， 
        'value' : Web3.toWei(1, 'ether'),
        'gas' : 2000000,
        'gasPrice' : Web3.toWei(50, 'gwei'),
        
    }
    
    # 签名
    sign_tx = w3.eth.account.sign_transaction(tx, private_key)
    
    # 发送交易 取得交易hash
    tx_hash = w3.eth.send_raw_transaction(sign_tx.rawTransaciton)
    
    # hash 值转换成十六进制
    Web3.toHex(tx_hash)

---

*Originally published on [cryptodw.eth](https://paragraph.com/@cryptodw/web3py)*
