0

I am developing a web3 application whose some part of backend code runs in a python script hosted on an aws lambda server. However, from this python script I will also be calling certain functions of a smart contract which is deployed on sepolia ethereum testnet. How can I access and trigger the executable function of this smart contract where the servers won't be having access to metamask wallets for signing the transactions? Is it possible to do this with libraries like web3.py?

1 Answer 1

1

Yes, although you would need to store a private key in your lambda. You can use this to retrieve the key securely: https://aws.amazon.com/blogs/compute/securely-retrieving-secrets-with-aws-lambda/

In order to call a function of the contract, you need 2 things:

  1. ABI
  2. Contract Address

In order to send the transaction to the network, you can use a HTTP endpoint provided by these Node-as-a-service platform:

  1. Alchemy (https://www.alchemy.com)
  2. QuickNode (https://www.quicknode.com)
from web3 import Web3

# Set up the web3 provider using Alchemy or QuickNode endpoint
web3_provider = "https://eth-mainnet.alchemyapi.io/v2/YOUR_ALCHEMY_API_KEY"  # or your QuickNode endpoint
web3 = Web3(Web3.HTTPProvider(web3_provider))

# ABI of the smart contract
abi = [
    # ... your contract ABI ...
]

# Contract address
contract_address = "0xYOUR_CONTRACT_ADDRESS"

# Create a contract instance
contract = web3.eth.contract(address=contract_address, abi=abi)

# Account address and private key for signing the transaction
account_address = "0xYOUR_ACCOUNT_ADDRESS"
private_key = "YOUR_PRIVATE_KEY"

# Function parameters (if any)
function_args = [42, "Hello, World!"]

# Get the function object
function = contract.functions.yourFunctionName(*function_args)

# Build the transaction
transaction = function.buildTransaction({
    'from': account_address,
    'gas': web3.eth.estimate_gas({'to': contract_address, 'data': function.encodeABI()})
})

# Sign the transaction
signed_txn = web3.eth.account.sign_transaction(transaction, private_key=private_key)

# Send the signed transaction to the network
tx_hash = web3.eth.send_raw_transaction(signed_txn.rawTransaction)

# Wait for the transaction to be mined
receipt = web3.eth.wait_for_transaction_receipt(tx_hash)

# Print the transaction receipt
print(receipt)
2
  • Hey, I've been trying to run the code, but on the 'signed_txn' line, I am getting this error: raise TypeError("Missing kwargs: {0}".format(sorted(missing_kwargs))) TypeError: Missing kwargs: ['nonce'] Could you also help with this?
    – MT 16
    Jun 7, 2023 at 8:34
  • Got the solution for this error, just add another argument as 'nonce': nonce inside the build_transaction method.
    – MT 16
    Jun 7, 2023 at 9:08

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.