Search code examples
pythonsmartcontractsweb3py

python web3 interaction with smart contract


I'm using web3.py to transact a smart contract method. Though broadcasted successfully, etherscan thinks its an "eth" transfer and not a smart contract interaction.

The method intended is mint().
Please find my code below:

infura_url = "https://rinkeby.infura.io/v3/<Infura code here>"
w3 = Web3(Web3.HTTPProvider(infura_url))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
address = w3.toChecksumAddress(<My wallet address>)
abi = json.loads(<ABI here>)
contract=w3.eth.contract(address=address, abi=abi)

mint_tx = contract.functions.mint(address,1).buildTransaction()
mint_tx['nonce'] = w3.eth.getTransactionCount(address)
signed_txn = w3.eth.account.sign_transaction(mint_tx, private_key=os.environ['private_key'])
txhash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
print(f'Transaction hash: {txhash.hex()}')

It should be like below (Done on etherscan manually):
https://rinkeby.etherscan.io/tx/0xf6626aa3bbfeb67f3798ad1145ec89c8995b0db9315e88cbf9b915f4610b8872

But as of now it's like below (From python):
https://rinkeby.etherscan.io/tx/0x6b43cebf69b82bcbf8cce654a24627688b4fe9ea7d43dd74b4fa4c1c1049a3c7

Am I missing a step before sending the transaction ?
Any help is greatly appreciated. If any more information is required, do let me know, thank you!


Solution

  • You are using the wrong address for your contract. Notice the To: and Interacted With (To): fields on etherscan.

    You have

    contract = w3.eth.contract(address=address, abi=abi)
    

    where address is your wallet address.

    You should have

    contract = w3.eth.contract(address=contract_address, abi=abi)
    

    where contract_address = '0xeB74D88306e09A78570795d7467F729ffA786651' in your case.