3

I would like to use web3.py instead of using the etherscan write contract function available in ethercan.io, Etherscan.io write contract function

Is this possible? if yes can someone please show me a sample. The contract address of the sample above: https://etherscan.io/token/0x2b591e99afe9f32eaa6214f7b7629768c40eeb39#writeContract

1 Answer 1

2

"Writing to contracts" is a somewhat confusing term from Etherscan.

It is doing a transaction to a smart contract address and function.

If look Web3.py examples the example that calls the function setVar() is writing to the contract.

import sys
import time
import pprint

from web3.providers.eth_tester import EthereumTesterProvider
from web3 import Web3
from solc import compile_source


def compile_source_file(file_path):
   with open(file_path, 'r') as f:
      source = f.read()

   return compile_source(source)


def deploy_contract(w3, contract_interface):
    tx_hash = w3.eth.contract(
        abi=contract_interface['abi'],
        bytecode=contract_interface['bin']).deploy()

    address = w3.eth.getTransactionReceipt(tx_hash)['contractAddress']
    return address


w3 = Web3(EthereumTesterProvider())

contract_source_path = 'contract.sol'
compiled_sol = compile_source_file('contract.sol')

contract_id, contract_interface = compiled_sol.popitem()

address = deploy_contract(w3, contract_interface)
print("Deployed {0} to: {1}\n".format(contract_id, address))

store_var_contract = w3.eth.contract(
   address=address,
   abi=contract_interface['abi'])

gas_estimate = store_var_contract.functions.setVar(255).estimateGas()
print("Gas estimate to transact with setVar: {0}\n".format(gas_estimate))

if gas_estimate < 100000:
  print("Sending transaction to setVar(255)\n")
  tx_hash = store_var_contract.functions.setVar(255).transact()
  receipt = w3.eth.waitForTransactionReceipt(tx_hash)
  print("Transaction receipt mined: \n")
  pprint.pprint(dict(receipt))
  print("Was transaction successful? \n")
  pprint.pprint(receipt['status'])
else:
  print("Gas cost exceeds 100000")
2
  • thanks for the sample, at first i get this error ImportError: cannot import name 'compile_source' from 'solc'. If i get through this error, would it be possible to give me a hand to actually apply it to my original sample function?
    – Ash
    Mar 19, 2020 at 22:22
  • Yes. You need to compile your smart contracts using solc. Based on the outputted ABI files you can construct web3.Contract code in Python. Mar 20, 2020 at 11:26

Your Answer

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

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