Open osricpan opened 1 year ago
from web3 import Web3 import json
web3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'))
private_key = 'YOUR_PRIVATE_KEY' contract_address = 'YOUR_CONTRACT_ADDRESS'
with open('contractABI.json') as f: contract_abi = json.load(f)
contract = web3.eth.contract(address=contract_address, abi=contract_abi)
def call_contract_method(): try: account = web3.eth.account.privateKeyToAccount(private_key) nonce = web3.eth.getTransactionCount(account.address)
# 構建交易 transaction = contract.functions.myMethod().buildTransaction({ 'from': account.address, 'gas': 200000, 'gasPrice': web3.eth.gasPrice, 'nonce': nonce }) # 簽名交易 signed_txn = web3.eth.account.signTransaction(transaction, private_key=private_key) # 發送交易 tx_hash = web3.eth.sendRawTransaction(signed_txn.rawTransaction) tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash) print('交易收據:', tx_receipt) except Exception as e: print('錯誤:', str(e))
call_contract_method()
from web3 import Web3 import json
連接到以太坊網絡
web3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'))
設置以太坊帳戶私鑰和合約地址
private_key = 'YOUR_PRIVATE_KEY' contract_address = 'YOUR_CONTRACT_ADDRESS'
載入智能合約的ABI
with open('contractABI.json') as f: contract_abi = json.load(f)
創建合約實例
contract = web3.eth.contract(address=contract_address, abi=contract_abi)
呼叫智能合約的方法
def call_contract_method(): try: account = web3.eth.account.privateKeyToAccount(private_key) nonce = web3.eth.getTransactionCount(account.address)
呼叫智能合約方法
call_contract_method()