Transfer BEP20 token from BSC using Moralis websocket in a non-custodial way

I want to transfer custom token in bsc without the user paying for gas, like a faucet. It requires the signing of the private key. I have some codes below as an example, but looking for a working v2 version.

Much appreciated!

const Moralis = require(‘moralis/node’);
const Web3 = require(‘web3’);

// Initialize Moralis
Moralis.initialize(’<YOUR_APP_ID>’);
Moralis.serverURL = ‘https://<YOUR_SERVER_URL>/server’;

// Initialize a new Web3 instance using Moralis
const web3 = new Web3(Moralis.Web3.getProvider());

// Define the transaction parameters
const privateKey = ‘<YOUR_PRIVATE_KEY>’;
const fromAddress = ‘<FROM_ADDRESS>’;
const toAddress = ‘<TO_ADDRESS>’;
const amount = ‘’;
const gasPrice = web3.utils.toWei(’<GAS_PRICE_GWEI>’, ‘gwei’);
const gasLimit = ‘<GAS_LIMIT>’;

// Get the contract ABI and address for your custom BEP-20 token
const contractABI = <YOUR_TOKEN_ABI>;
const contractAddress = ‘<YOUR_TOKEN_ADDRESS>’;

// Create a new contract instance
const contract = new web3.eth.Contract(contractABI, contractAddress);

// Encode the transfer function and parameters for your custom token
const transferEncoded = contract.methods.transfer(toAddress, amount).encodeABI();

// Create the raw transaction object
const rawTransaction = {
from: fromAddress,
to: contractAddress,
gasPrice: gasPrice,
gas: gasLimit,
data: transferEncoded,
nonce: await web3.eth.getTransactionCount(fromAddress),
};

// Sign the transaction
const signedTransaction = await web3.eth.accounts.signTransaction(rawTransaction, privateKey);

// Send the signed transaction
web3.eth.sendSignedTransaction(signedTransaction.rawTransaction, (error, hash) => {
if (error) {
console.error(error);
} else {
console.log(‘Transaction hash:’, hash);
}
});

HI @sgdev

In v2 sdk Moralis dont have an API to call smart contract write functions. So it is not possible to transfer tokens with Moralis.

We recommend using web3.js or ether.js to interact with smart contracts.

Since you are already using web3.js you continue using the same code.

Thank you sir for your reply.

I realised it now and hence have change to tatum instead.