Blockchain

如何從不同地址呼叫solidity智能合約中的函式

  • November 1, 2022

我是使用 python 進行區塊鏈開發的初學者。我有一個帶有 3 個功能的 Solidity 智能合約,第一個只能由 ganache 帳戶 A 呼叫,其他功能可以由其他帳戶呼叫(ganache 中的 4 個帳戶:B、C、D 和 E)。我的問題是如何指定函式的呼叫者以及如何更改它?

import json
from web3 import Web3

# Set up web3 connection with Ganache
ganache_url = "http://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))

abi = json.loads('[{"constant":false,"inputs":[{"name":"_greeting","type":"string"}],"name":"setGreeting","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"greeting","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]')
bytecode = "6060604052341561000f57600080fd5b6040805190810160405280600581526020017f48656c6c6f000000000000000000000000000000000..."

所以,首先我相信你想要部署合約。這有效:

tx_hash = web3.eth.contract(
             abi = abi, bytecode = "0x"+bytecode
         ).constructor().transact({'from': web3.eth.accounts[0]})

contractAddress = web3.eth.get_transaction_receipt(tx_hash)['contractAddress']
contract = web3.eth.contract(address=contractAddress, abi=abi)

注意from上面的論點:我們可以通過這種方式指定誰在進行交易。web3.eth.accounts[0]是 ganache 自動為我們創建的錢包(我相信總共有 10 個)。

使用另一個錢包進行交易:

contract.functions.setGreeting("Hola").transact({'from': web3.eth.accounts[1]})

引用自:https://ethereum.stackexchange.com/questions/138501