osricpan / data

0 stars 0 forks source link

fido2 python #3

Open osricpan opened 1 year ago

osricpan commented 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'

載入智能合約的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)

    # 構建交易
    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()