How to run contract write function in Cloud Codes on Self Hosted Server

Hello,

When my server was on Moralis, I could run smart contract write function with private key using Moralis.Web3 in cloud codes. However, that codes did not work on self hosted. I found your document about “How to run contract functions”. But, I couldn’t find any information about for “run the write function”.

Can you help me?
Thanks

Note: How to run contract functions link

My old codes;

  const web3 = new Parse.Web3(new Parse.Web3.providers.HttpProvider(RPC_URL));
  await web3.eth.accounts.privateKeyToAccount(ACCOUNT_PRIVATE_KEY);
  await web3.eth.accounts.wallet.add({
    privateKey: ACCOUNT_PRIVATE_KEY,
    address: ACCOUNT_ADDRESS,
  });
  const contract = await new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS, {
    gas: 3000000,
  });
...

Note: These codes from this link

Hi @ozzyintelly

You can also install and use the ether.js library on your cloud functions. The code from the old docs is just a wrapper function for ether.js which is not available in selfhost server code. So you can use the ether.js library directly.

1 Like

Thank you @johnversus,

I solved my problem with the following code block;

import Web3 from 'web3';

...

const web3 = new Web3(new Web3.providers.HttpProvider(RPC_URL));
await web3.eth.accounts.privateKeyToAccount(ACCOUNT_PRIVATE_KEY);
await web3.eth.accounts.wallet.add({
  privateKey: ACCOUNT_PRIVATE_KEY,
  address: ACCOUNT_ADDRESS,
});

const contract = await new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS, {
  gas: 3000000,
});

...

It’s actually very easy. However, the RPC URL (BSC TESTNET) I used while doing my tests was not responding and I was having problems.

1 Like

Thats great. Thanks for sharing.

If you have issues from the node it should probably fix by changing to a faster node.