3

I would like to call a smart contract functions using Web3 Python using the Infura mainnet node instead of a local node. I understand that I need to import the private key and use it to sign the transaction but I cannot see any examples for doing this with calling smart contracts.

The code I have is as follows but it fails as there is no wallet attached:

from web3 import Web3
import json
from web3.providers.rpc import HTTPProvider
contractAddress = '0xabcd'
web3 = Web3(HTTPProvider('https://mainnet.infura.io'))
with open('abcd.abi', 'r') as abi_definition:
    abi = json.load(abi_definition)
print (web3.eth.blockNumber)


fContract = web3.eth.contract(abi,contractAddress)

print ("Test",fContract.transact().test("0xabcd",100000))

Error:

ValueError: {u'message': u'gas required exceeds allowance or always failing transaction', u'code': -32000}
2
  • 2
    If you are getting familiar with Blockchain you should use a testnet such as Ropsten or Rinkeby. Using mainnet (mainnet.infura.io) will cost you Ether if you have a wallet (such as MetaMask) setup in your browser or fail as you do not have ether to pay for gas.
    – Chim
    Commented Jan 15, 2018 at 11:56
  • If you are happy to read a JavaScript code and understand the steps involve with signing a transaction, you could refer npmjs.com/package/web3js-raw & github.com/fidenz-chim/fundsplitter_web3jsraw.git
    – Chim
    Commented Jan 15, 2018 at 11:59

1 Answer 1

4

Check out the example of how to invoke a contract using a local key in the docs.

Docs for some of the key methods are here:

Roughly, you're going to want to:

txn = fContract.functions.test("0xabcd", 100000).build_transaction()
signed = web3.eth.account.sign_transaction(txn, privateKey)
txn_hash = web3.eth.send_raw_transaction(signed.rawTransaction)
2
  • 1
    Hi carver, thank you. Also you missed private key: signed = web3.eth.account.signTransaction(txn, privateKey)
    – Russo
    Commented May 21, 2018 at 5:20
  • Hi carver, would you explain a bit in detail about how to use these functions? I tried them but they are not working. Would you have a look here: ethereum.stackexchange.com/questions/49038/… ? Thank you
    – Russo
    Commented May 21, 2018 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.