simple web3.py example for accessing to smart contract on Polygon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from web3 import Web3 | |
from web3.middleware import geth_poa_middleware | |
#MyStraget.solにweb3.pyでアクセス | |
def main(): | |
#自分のウォレットのアドレスとプレイベートキー | |
wallet = "0x...[ウォレットアドレス]" | |
key = "[プライベートキー]" | |
#接続するチェーン | |
#rpc_addr = "http://127.0.0.1:8545" #local geth | |
rpc_addr = "https://polygon-rpc.com" #polygon | |
#デプロイしたスマートコントラクトの情報↓以下は私がデプロイしたやつなので自分の情報に変更する | |
#abiはjson形式なのでpythonソース中にそのまま貼り付け可能。PyCharmなら折り畳み表示可能 | |
addr = "0x8b02EB24A5b1af257E22C520406C3dD9c1B55fd8" # polygon | |
abi = [ | |
{ | |
"inputs": [], | |
"name": "get", | |
"outputs": [ | |
{ | |
"internalType": "string", | |
"name": "", | |
"type": "string" | |
} | |
], | |
"stateMutability": "view", | |
"type": "function" | |
}, | |
{ | |
"inputs": [ | |
{ | |
"internalType": "string", | |
"name": "_message", | |
"type": "string" | |
} | |
], | |
"name": "set", | |
"outputs": [], | |
"stateMutability": "nonpayable", | |
"type": "function" | |
} | |
] | |
web3 = Web3(Web3.HTTPProvider(rpc_addr)) | |
#https://chowdera.com/2021/11/20211124152801551d.html | |
web3.middleware_onion.inject(geth_poa_middleware, layer=0) | |
print("isConnect", web3.isConnected()) | |
if( web3.isConnected() != True ): | |
return | |
strage = web3.eth.contract(address=addr, abi=abi) | |
print("strage=", strage) | |
#参照系 | |
ret = strage.functions.get().call() | |
print("ret=", ret) | |
#更新系 | |
nonce = web3.eth.getTransactionCount(wallet) | |
func = strage.functions.set("hello") | |
transaction = func.buildTransaction() | |
transaction.update({ 'nonce' : nonce }) | |
signed_tx = web3.eth.account.sign_transaction(transaction, key) | |
tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction) | |
result = web3.eth.wait_for_transaction_receipt(tx_hash) | |
print("resut=", result) | |
if __name__ == '__main__': | |
main() | |
print("end") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment