REMIX部署和调用:
REMIX部署,web3.py调用——
调用代码:
# This is a sample Python script.
import json
import web3
from web3.middleware import geth_poa_middleware
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
wb3 = web3.Web3(web3.HTTPProvider('http://127.0.0.1:8545'))
wb3.middleware_onion.inject(geth_poa_middleware, layer=0)
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print('Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
def _load_contract_instance(contract_address, abi_code):
"""加载合约实例"""
contract_instance = wb3.eth.contract(
address=contract_address,
abi=abi_code
)
return contract_instance
def is_conneteed():
if wb3.isConnected():
print('已连接')
else:
print('Fail')
def get_block_info(num):
print(wb3.eth.get_block(num))
def transact(contract_address, contract_abi, function_name, **kwargs):
account_address = '0x1901300c3e828D84651c2bA9CAA21Db60195C2F4'
account_private_key = 'd2f868426f1ddd0dd5e34bff20970ab32a3735e0b391623937ee145f0fb0b5d7'
contract_instance = _load_contract_instance(contract_address, contract_abi)
nonce = wb3.eth.get_transaction_count(account_address)
fn_name = contract_instance.get_function_by_name(function_name)
tx = fn_name(**kwargs).buildTransaction({
'chainId': 981027,
'from': account_address,
'nonce': nonce,
'gas': 2000000,
'gasPrice': 20 * 10 ** 8
})
signed = wb3.eth.account.sign_transaction(tx, account_private_key)
tx_hash = wb3.toHex(wb3.eth.send_raw_transaction(signed.rawTransaction))
tx_receipt = wb3.eth.waitForTransactionReceipt(tx_hash)
return tx_receipt
def call(
contract_address,
abi_code,
function_name,
*args,
**kwargs):
"""合约查询放方法"""
# 获得合约实例
contract_instance = _load_contract_instance(contract_address, abi_code)
# 获得方法
fn_name = contract_instance.get_function_by_name(function_name)
return fn_name(*args, **kwargs).call()
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# print_hi('PyCharm')
# is_conneteed()
# get_block_info(40)
contract_address = '0x5a468bcAF4B4Cb96ED116454b3de3b64C7459595'
abi = '[ { "inputs": [ { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "store", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "ValueChanged", "type": "event" }, { "inputs": [], "name": "retrieve", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" } ]'
# result = transact(
# contract_address=contract_address,
# contract_abi=json.loads(abi),
# function_name='store',
# value=158
# )
# print(result)
result = call(
contract_address=contract_address,
abi_code=json.loads(abi),
function_name='retrieve'
)
print(result)
# See PyCharm help at https://www.jetbrains.com/help/pycharm/