[SOLVED] How to call a write contract method from nodeJs? / Moralis.ethersByChain is not a function

Hi, I try to call a write method from node js. But it says that Moralis.ethersByChain is not a function.

This function is working normally from cloud. I’m just wondering why not from nodejs?

import Moralis from "moralis-v1/node.js";
import * as dotenv from "dotenv";
dotenv.config();

export async function pay(to, amount) {
  await Moralis.start({
    serverUrl: process.env.serverUrl,
    appId: process.env.appId,
    masterKey: process.env.masterKey,
  });

  const eth = Moralis.ethersByChain("0x13881");
  const ethersProvider = new eth.ethers.providers.JsonRpcProvider(process.env.rpcUrl);
  const wallet = new eth.ethers.Wallet(process.env.privateKey, ethersProvider);

  const contractAddress = await Moralis.Query("ContractAddress").first().attributes.engine;
  const contractAbi = await Moralis.Query("Abi").first().attributes.token;

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

  async function pay(contract, to, amount) {
    try {
      await contract.pay(to, amount, { gasLimit: 5000000 });
    } catch (error) {
      throw new Error(error);
    }
  }
  pay(contract, to, amount);
}

Any suggestions will be much appreciated.

Here is the error:

image

P.S. I’m able to call other Moralis functions like queries and saving to DB, meaning that the SDK is imported correctly.

Thank you

you try to run this code locally? that syntax with Moralis.ethersByChain was only specific to cloud code at some point.

you can use directly ethers or web3 to call a write function

No I never ran it locally, I copied from cloud and repurposed. I’ll keep it on the cloud then. Thank you.

that syntax may not work in cloud code now either, because speedy nodes were discontinued

I use one from chainstack. It’s working on cloud. :+1:

1 Like

It worked with native ethers library. Thanks a lot.

import Moralis from "moralis-v1/node.js";
import { ethers } from 'ethers';
import * as dotenv from "dotenv";
dotenv.config();

export async function pay(to, amount) {
  await Moralis.start({
    serverUrl: process.env.serverUrl,
    appId: process.env.appId,
    masterKey: process.env.masterKey,
  });

  const provider = ethers.getDefaultProvider(process.env.rpcUrl);
  const signer = new ethers.Wallet(process.env.privateKey, provider);

  const addressQuery = new Moralis.Query("EngineContract");
  const addressResult = await addressQuery.first();
  const contractAddress = addressResult.attributes.address;
  const contractAbi = addressResult.attributes.abi;

  const contract = new ethers.Contract(contractAddress, contractAbi, signer);

  async function pay(contract, to, amount) {
    try {
      await contract.pay(to, amount, { gasLimit: 5000000 });
    } catch (error) {
      throw new Error(error);
    }
  }
  const receipt = await pay(contract, to, amount);
  return JSON.stringify(receipt);
}

1 Like