1inch dex swap nodeJS

Hi,

Is it possible to use Dex Swap from NodeJS script?

I tried as follow:
const serverUrl = process.env.MORALIS_SERVER_URL;
const appId = process.env.MORALIS_APP_ID;
Moralis.start({ serverUrl, appId });

// Set provider
const provider = new Web3.providers.HttpProvider(
https://speedy-nodes-nyc.moralis.io/1a2b3c4d5e6f1a2b3c4d5e6f/bsc/mainnet
);

const web3 = new Web3(provider);

// Set account
const account = web3.eth.accounts.privateKeyToAccount(
process.env.WALLET_PRIVATE_KEY
);

// Swap
await Moralis.initPlugins();
dex = Moralis.Plugins.oneInch;

const options = {
chain: “eth”,
fromTokenAddress: “0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE”,
toTokenAddress: “0x111111111117dc0aa78b770fa6a738034120c302”,
amount: Number(Moralis.Units.ETH(“0.001”)),
fromAddress: account.address,
slippage: 0,
};

var receipt = await dex.swap(options);
console.log(receipt);

But always get this error:
Error: Missing web3 instance, make sure to call Moralis.enableWeb3() or Moralis.authenticate()

I tried different solutions but no luck… Thanks in advance!

1inch PLUG IS OUTDATED moralis use old version.

hey, you have to initiate moralis web3 instance by calling either Moralis.enableWeb3() or Moralis.authenticate()

@0xprof thanks for the answer, problem here is that moralis.enable() relies on window which is only available client side. How can I create a web3 instance server side?

I thought new Web3(provider) would have created this instance…

Have you tried authenticate ?

Yes that would create an instance but not a moralis instance

Moralis authenticate relies also on window…
How can I create a moralis web3 server side instance to use dex.swap?

hey, i dont think moralis.auth or enableweb3 require a window, have you tried it ?
take a look at the docs
https://docs.moralis.io/moralis-server/users/crypto-login#moralis-authentication
https://docs.moralis.io/moralis-server/web3/web3

Yes I tried both and they all need to be called client side.

@cryptokid any idea from you please?

it should be possible to do something similar with this: https://github.com/dani69654/moralis_opensea_nodejs/blob/main/modules/buyOrder.js

Not possible to use 1inch plug-in server side?

it may be possible if you understand how to send it the requests, above you have an example for OpenSea plugin

1 Like