Skip to content

Instantly share code, notes, and snippets.

@himawari2021
Last active February 11, 2022 11:09
Show Gist options
  • Save himawari2021/ccd6589df5c2420d1e11c4c57e94f392 to your computer and use it in GitHub Desktop.
Save himawari2021/ccd6589df5c2420d1e11c4c57e94f392 to your computer and use it in GitHub Desktop.
simple web3.py example for accessing to smart contract on Polygon
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