[SOLVED] Why is this cloud function executing but not working?

Hi,

I have 2 cloud functions. One is being called inside the other.

Moralis.Cloud.define("payWinner", async () => {
/* I calculate the winner address and amount here */
....

/* then I save the winner address and amount in the params 
object and pass it into the 2nd cloud function to execute the payment*/

const params = {
to: winnerAddress,
value: winAmount,
}

await Moralis.Cloud.run("pay", params);

}

/* The inner function executes the payment. ABI, address, and rpc node are correct I checked multiple times.*/

Moralis.Cloud.define("pay", async (request) => {

  const logger = Moralis.Cloud.getLogger();
  const eth = Moralis.ethersByChain("0x13881");

  const to = request.params.to;
  const value = request.params.value;

  const ethersProvider = new eth.ethers.providers.JsonRpcProvider(

    "/*my rpc node from chainstack here*/"

  );

  const wallet = new eth.ethers.Wallet(

    "/*my private key here*/",

    ethersProvider

  );

  const contractAddress = "/* my contract address here*/";

  const contractAbi = [/* my ABI here */]
  const contract = new eth.ethers.Contract(

    contractAddress,

    contractAbi,

    wallet

  );
 
  async function payment(contract, to, value) {
    try {
      contract.payment(to, value, { gasLimit: 5000000 }).then((result) => {
        logger.info(JSON.stringify(result));
      });
    } catch (error) {
      logger.error(error.status);
    }
  }
  const receipt = await payment(contract, to, value);
  logger.info(JSON.stringify(receipt));

and here are the logs:

What I can’t understand is this:

  1. Why do the logs show that the inner function (pay) is executed before the outer function (payWinner)?
  2. Why the pay function in the smart contract doesn’t run even though the logs show that it was called with correct parameters? (the function is working from remix)
    function payment(address payable to, uint256 value) /* onlyAdmin */ public {
        require(to != address(0), "Can't transfer to the zero address");
        require(address(this).balance > 0, "The pool is empty at the moment, try later");

        payable(to).transfer(value);
        emit fundsTransfer(to, value, block.timestamp);
    }

Thank you

try to add more logging to see what lines execute and what doesn’t work

I attached logger to almost every line and most of them are undefined. How is that even possible?

Moralis.Cloud.define("processPayment", async (request) => {
  const logger = Moralis.Cloud.getLogger();
  const eth = Moralis.ethersByChain("0x13881");
  logger.info(eth);

  const to = request.params.to;
  logger.info(to);

  const value = request.params.value;
  logger.info(value);

  const ethersProvider = new eth.ethers.providers.JsonRpcProvider(
    "https://nd-732-321-633.p2pify.com/cc/* some random characters */0863ce7a3a8b3c52e"
  );
  logger.info(ethersProvider);

  const wallet = new eth.ethers.Wallet(
    "e96673de506f0cc8d6/* some random characters dc */3db5f60c8ee1",
    ethersProvider
  );
  logger.info(wallet);

  const contractAddress = "0x13D48E90fE20331F60A0e9df4965F2836293ebd0";
  logger.info(contractAddress);

  const contractAbi = [ /* ABI is here */  ];
  logger.info(contractAbi);

  const contract = new eth.ethers.Contract(
    contractAddress,
    contractAbi,
    wallet
  );
  logger.info(contract);

  async function pay(contract, to, value) {
    try {
      await contract.payment(to, value, { gasLimit: 5000000 });
    } catch (error) {
      logger.error(error.status);
    }
  }
  const receipt = await pay(contract, to, value);
  logger.info(JSON.stringify(receipt));
});

Here is the result:

It says that:

This line is undefined

const eth = Moralis.ethersByChain("0x13881");

This line is undefined

  const ethersProvider = new eth.ethers.providers.JsonRpcProvider(
    "https://nd-732-321-633.p2pify.com/cc8XXXXXXXXXXXXXXXa8b3c52e"
  );

This line is undefined

  const wallet = new eth.ethers.Wallet(
    "e96673de50673ZZZZZZZZZZZZZZbadc3db5f60c8ee1",
    ethersProvider
  );

How is this even possible? This code was working yesterday with the difference that abi, contract address and input parameters were different.

What do you suggest?

you have to use logger.info(JSON.stringify(variable)) most of the times
you can also write some string in that logger.info to know where from it is

1 Like

Ok I attached the JSON.stringify as you suggested and got tons of info, but the one that seems erroneous comes from this line I think:

It seems like the problems is with this line:

const eth = Moralis.ethersByChain("0x13881");

1. 2022-09-07T15:12:23.311Z - eth
2. 2022-09-07T15:12:23.309Z - {"provider":{"_isProvider":true,"_events":[],"_emitted":{"block":-2},"disableCcipRead":false,"formatter":{"formats":{"transaction":{},"transactionRequest":{},"receiptLog":{},"receipt":{},"block":{},"blockWithTransactions":{},"filter":{},"filterLog":{}}},"anyNetwork":false,"_networkPromise":{},"_maxInternalBlockNumber":-1024,"_lastBlockNumber":-2,"_maxFilterBlockRange":10,"_pollingInterval":4000,"_fastQueryDate":0,"connection":{"url":"https://speedy-nodes-nyc.moralis.io/246434h7bd0b2fd556dfc4b24abc4c6474610de002a29d5fba042c3359d8733f39b0aaf/polygon/mumbai"},"_nextId":42},"ethers":{"providers":{},"constants":{"AddressZero":"0x0000000000000000000000000000000000000000","NegativeOne":{"type":"BigNumber","hex":"-0x01"},"Zero":{"type":"BigNumber","hex":"0x00"},"One":{"type":"BigNumber","hex":"0x01"},"Two":{"type":"BigNumber","hex":"0x02"},"WeiPerEther":{"type":"BigNumber","hex":"0x0de0b6b3a7640000"},"MaxUint256":{"type":"BigNumber","hex":"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},"MinInt256":{"type":"BigNumber","hex":"-0x8000000000000000000000000000000000000000000000000000000000000000"},"MaxInt256":{"type":"BigNumber","hex":"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},"HashZero":"0x0000000000000000000000000000000000000000000000000000000000000000","EtherSymbol":"Ξ"},"errors":{"UNKNOWN_ERROR":"UNKNOWN_ERROR","NOT_IMPLEMENTED":"NOT_IMPLEMENTED","UNSUPPORTED_OPERATION":"UNSUPPORTED_OPERATION","NETWORK_ERROR":"NETWORK_ERROR","SERVER_ERROR":"SERVER_ERROR","TIMEOUT":"TIMEOUT","BUFFER_OVERRUN":"BUFFER_OVERRUN","NUMERIC_FAULT":"NUMERIC_FAULT","MISSING_NEW":"MISSING_NEW","INVALID_ARGUMENT":"INVALID_ARGUMENT","MISSING_ARGUMENT":"MISSING_ARGUMENT","UNEXPECTED_ARGUMENT":"UNEXPECTED_ARGUMENT","CALL_EXCEPTION":"CALL_EXCEPTION","INSUFFICIENT_FUNDS":"INSUFFICIENT_FUNDS","NONCE_EXPIRED":"NONCE_EXPIRED","REPLACEMENT_UNDERPRICED":"REPLACEMENT_UNDERPRICED","UNPREDICTABLE_GAS_LIMIT":"UNPREDICTABLE_GAS_LIMIT","TRANSACTION_REPLACED":"TRANSACTION_REPLACED"},"logger":{"version":"ethers/5.6.1"},"utils":{"defaultAbiCoder":{"coerceFunc":null},"FormatTypes":{"sighash":"sighash","minimal":"minimal","full":"full","json":"json"},"RLP":{},"defaultPath":"m/44'/60'/0'/0/0","base58":{"alphabet":"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz","base":58,"_alphabetMap":{"1":0,"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"A":9,"B":10,"C":11,"D":12,"E":13,"F":14,"G":15,"H":16,"J":17,"K":18,"L":19,"M":20,"N":21,"P":22,"Q":23,"R":24,"S":25,"T":26,"U":27,"V":28,"W":29,"X":30,"Y":31,"Z":32,"a":33,"b":34,"c":35,"d":36,"e":37,"f":38,"g":39,"h":40,"i":41,"j":42,"k":43,"m":44,"n":45,"o":46,"p":47,"q":48,"r":49,"s":50,"t":51,"u":52,"v":53,"w":54,"x":55,"y":56,"z":57},"_leader":"1"},"base64":{},"Utf8ErrorFuncs":{},"TransactionTypes":{"0":"legacy","1":"eip2930","2":"eip1559","legacy":0,"eip2930":1,"eip1559":2},"SupportedAlgorithm":{"sha256":"sha256","sha512":"sha512"},"UnicodeNormalizationForm":{"current":"","NFC":"NFC","NFD":"NFD","NFKC":"NFKC","NFKD":"NFKD"},"Utf8ErrorReason":{"UNEXPECTED_CONTINUE":"unexpected continuation byte","BAD_PREFIX":"bad codepoint prefix","OVERRUN":"string overrun","MISSING_CONTINUE":"missing continuation byte","OUT_OF_RANGE":"out of UTF-8 range","UTF16_SURROGATE":"UTF-16 surrogate","OVERLONG":"overlong representation"}},"wordlists":{"cz":{"locale":"cz"},"en":{"locale":"en"},"es":{"locale":"es"},"fr":{"locale":"fr"},"it":{"locale":"it"},"ja":{"locale":"ja"},"ko":{"locale":"ko"},"zh":{"locale":"zh_cn"},"zh_cn":{"locale":"zh_cn"},"zh_tw":{"locale":"zh_tw"}},"version":"ethers/5.6.1"}}

Do you know what can be wrong here?

"errors":{"UNKNOWN_ERROR":"UNKNOWN_ERROR","NOT_IMPLEMENTED":"NOT_IMPLEMENTED","UNSUPPORTED_OPERATION":"UNSUPPORTED_OPERATION","NETWORK_ERROR":"NETWORK_ERROR","SERVER_ERROR":"SERVER_ERROR","TIMEOUT":"TIMEOUT","BUFFER_OVERRUN":"BUFFER_OVERRUN","NUMERIC_FAULT":"NUMERIC_FAULT","MISSING_NEW":"MISSING_NEW","INVALID_ARGUMENT":"INVALID_ARGUMENT","MISSING_ARGUMENT":"MISSING_ARGUMENT","UNEXPECTED_ARGUMENT":"UNEXPECTED_ARGUMENT","CALL_EXCEPTION":"CALL_EXCEPTION","INSUFFICIENT_FUNDS":"INSUFFICIENT_FUNDS","NONCE_EXPIRED":"NONCE_EXPIRED","REPLACEMENT_UNDERPRICED":"REPLACEMENT_UNDERPRICED","UNPREDICTABLE_GAS_LIMIT":"UNPREDICTABLE_GAS_LIMIT","TRANSACTION_REPLACED":"TRANSACTION_REPLACED"},

This piece probably

I tried rewriting the code from scratch but got the same error from the eth variable again.

you can use web3 instead of ethers now, I don’t know the syntax for ethers in cloud code

https://v1docs.moralis.io/moralis-dapp/cloud-code/cloud-functions#example-of-how-to-use-a-custom-rpc-url

The reason was because JS can’t represent big numbers accurately as integers. So to solve this I just had to change the integer to a string using template literals and it worked. Can’t believe I spent 8 hours on that.

1 Like

where did you have to make that change?

When forming the params object. I changed this

  const winAmount = valueRow.attributes.maticValue;
  const params = { to: winnerAddress, amount: winAmount };

to this

  const winAmount = `${valueRow.attributes.maticValue}`;
  const params = { to: winnerAddress, amount: winAmount };
1 Like