准备

pip3 install web3
from web3 import Web3
from eth_abi import encode_abi
w3 = Web3(Web3.HTTPProvider('<http://118.31.7.155:8545>'))
chainId = 0x6b0

def sendTx(w3, tx, private_key):
    signed_txn = w3.eth.account.sign_transaction(tx, private_key=private_key)
    send = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    txid = send.hex()
    print(txid)
    res = w3.eth.wait_for_transaction_receipt(txid)
    print(res)
    # assert res["status"] == 1
    return res

address = '0x9DE'
private_key = 'abcdef'

创建合约

直接创建合约,需要自己拼接构造函数参数(无需ABI)

exp_code = "66666666"
#---------------------Deploy Exp------------------------
tx = {
  'from': address,
  'to': None,
  'value': '0x0',
  'data': "0x" + exp_code + encode_single("(uint256,uint256)",(0,12)).hex(),
  'gas': 3000000,
  'gasPrice': w3.eth.gas_price,
  'nonce': w3.eth.getTransactionCount(address),
  'chainId': chainId
}

res = sendTx(w3, tx, private_key)
exp_addr = res["contractAddress"]
print(f"exp: {exp_addr}")
#---------------------Deploy Exp------------------------

通过ABI调用构造函数

exp_abi = "{}"
exp_code = "66666666"
exp = w3.eth.contract(abi=exp_abi, address=exp_addr)
#---------------------Deploy Exp------------------------
tx = exp.constructor(123, b"SOME_DATA").buildTransaction({
    'from': address,
    'nonce': w3.eth.getTransactionCount(address),
    'gas': 3000000,
    'gasPrice': w3.eth.gasPrice,
    'chainId': chainId
})

res = sendTx(w3, tx, private_key)
exp_addr = res["contractAddress"]
print(f"exp: {exp_addr}")
#---------------------Deploy Exp------------------------

调用合约接口

token = w3.eth.contract(abi=token_abi, address=token_addr)

#---------------------Transfer TokenA to Exp------------------------
tx = token.functions.transfer(address, 1000).buildTransaction({
    'from': address,
    'nonce': w3.eth.getTransactionCount(address),
    'gas': 3000000,
    'gasPrice': w3.eth.gasPrice,
    'chainId': chainId
})

res = sendTx(w3, tx, private_key)
#---------------------Transfer TokenA to Exp------------------------

调用view/pure方法

token.functions.balanceOf(address).call()

wei单位转换

w3.toWei(0.008, "ether")

地址转换

将大小写不正确的hex串地址转换为符合ETH地址checksum的hex串

addr = w3.toChecksumAddress("0x2f3863f05621e4af1b753de1b0f91f1f997371f1")

读取Storage

web3.eth.get_storage_at('0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B', 0)