0

I noticed that there are two options to create a transaction / call a state-changing function.

In the first one we receive the transaction hash (tx_hash) by building the transaction, signing the transaction using our private key, sending raw transaction, and waiting for the receipt:

simple_storage = w3.eth.contract(address=tx_receipt.contractAddress, abi=abi)

store_tx = simple_storage.functions.store(_favoriteNumber=12).buildTransaction(
    {
        "from": my_account,
        "chainId": network_id,
        "nonce": w3.eth.get_transaction_count(account=my_account),
    }
)
signed_tx = w3.eth.account.sign_transaction(store_tx, private_key=private_key)
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)

and in the second option we simply use the transact() function to receive our tx_hash:

tx_hash = simple_storage.functions.store(_favoriteNumber=12).transact(
    {
        "from": my_account,
        "chainId": network_id,
        "nonce": w3.eth.get_transaction_count(account=my_account),
    }
)

What is the difference between these two?

1 Answer 1

0

The second one requires a middleware to sign the transaction with the private keys (it could be a web3 provider like Metamask, a hardware wallet service, etc).

If you use the same private key the resulting transaction should be indistinguishable.

2
  • is there any different regarding gas fees and transaction speed? Which approach is considered as better, more appropriate or just safer? Oct 21, 2021 at 17:11
  • @FilipSzczybura There's no difference, usually transact will use send_raw_transaction underneath. Which one to use depends if you want to handle the private keys or prefer to let the user handle them.
    – Ismael
    Oct 21, 2021 at 20:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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