[SOLVED] Cloud Function Contract send()

I’m trying to execute a cloud function that calls contract’s function on BSC Test net that changes its state. Here is my understanding of how it should work:

Since send() require gas to execute I need to construct web3 using private key (so that founds from actual account can be used). Yes, I’m aware of security implications of using private key like that.
I do it like that:

   const web3 = await Moralis.web3ByChain(chain, {privateKey: '667b193.........446164'});
   const contract = new web3.eth.Contract(abi, contractAddress);
   const status = await contract.methods.setOperator('0xblahblahblah').send({
        'from': operatorAddress,
        'gas': 100000000,
        'gasPrice': 1000000000
    })
        .catch((e) => logger.error(`callName: ${e}${JSON.stringify(e, null, 2)}`));

This works perfectly fine agains local Ganache using devchain proxy server.

It doesn’t however work at all for BSC Test net and I’m getting

callName: Error: Invalid JSON RPC response: "Method not allowed"{}

Is there a difference on how this should be done for BSC? or my understanding of how it should work is wrong. Can someone share a working example of send() contract call from Cloud Function.

What about trying it this way in a try..catch block

const web3 = Moralis.web3ByChain("0x61");

const contractIns = new web3.eth.Contract(abi, contractAddress);

const fnCall = contractIns.methods.setOperator("0xblahblahblah").encodeABI();

const transaction = {
  to: contractAddress,
  data: fnCall,
  gas: 100000000,
  gasPrice: web3.utils.toWei("2", "gwei"),
};

let signedTransaction = await web3.eth.accounts.signTransaction(
  transaction,
  PRIVATE_KEY.   //Add your private key here
);

const sentTx = await web3.eth.sendSignedTransaction(
  signedTransaction.raw || signedTransaction.rawTransaction
);

logger.info("Transaction Hash", sentTx.transactionHash);

1 Like

Thanks @qudusayo this is working for me nicely. So it turns out that local Ganache has different behaviour to actual chain!