(programmatically) Transferring Avax or ERC20 tokens from C chain of AVAX wallet to Metamask

I recently went over AVAX Datahub tutorial and AVAX documentation to write a .js script transferring AVAX tokens from X chain to Metamask.

I want to write a script to transfer AVAX or ERC20 tokens from C chain of AVAX wallet to Metamask.

It does not appear straightforward though, as all tutorial modules only talk about cross-chain transfers .

C to Metamask transfer is easily done if we just manually do it with the UI of the AVAX wallet but I want to do it programmatically.

Could anyone hlep?

Not sure what you mean by transfer to Metamask but most likely you’ll be using the Ethereum JSON RPC such as eth.sendTransaction

I tried
`var fs = require(‘fs’);
let mnemonic = “word word word…”;
const { ethers } = require(‘ethers’)
var Web3 = require(‘web3’);
const provider = new ethers.providers.JsonRpcProvider(‘https://api.avax-test.network/ext/bc/C/rpc’);
web3 = new Web3(provider);
const wallet = new ethers.Wallet.fromMnemonic(mnemonic);
web3.eth.defaultAccount = wallet.address
eth_privatekey = wallet.privateKey;

async function main(){
console.log(web3.eth.getTransactionCount(wallet.address))
}
main().catch((err) => {
console.log(“We have encountered an error!”)
console.error(err)
})`

but get the following error message

reason: 'processing response error', code: 'SERVER_ERROR', body: '{"jsonrpc":"2.0","id":42,"error":{"code":-32600,"message":"invalid request"}}\n',