I am trying to send usdc dev token using code to a wallet address but it kept on showing "Unable to simulate. Make sure you trust this website since approving can lead to loss of funds."
And even if I approve, tx would get rejected.
After hours of debugging, I tried first sending a little of the usdc token to that wallet address and then tried to resend again using my code and it worked fine.
So I was wondering, must the wallet have a bit of that token before being able to send to it using code? If yes, is there a way to do it successfully using code? Because that's my main goal
code below:
import {
createAssociatedTokenAccountInstruction,
createTransferInstruction,
getAssociatedTokenAddress,
TOKEN_PROGRAM_ID,
} from "@solana/spl-token";
import { useConnection, useWallet } from "@solana/wallet-adapter-react";
import { PublicKey, Transaction } from "@solana/web3.js";
//to convert the wallet address to usdc dev
async function convertToUsdcDev(address) {
const mint = new PublicKey("Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr");
const owner = new PublicKey(address);
const tokenAddress = await getAssociatedTokenAddress(mint, owner);
console.log(console.log("tokenAddress.toBase58()", tokenAddress.toBase58()));
return tokenAddress.toBase58();
}
function usePayUSDC() {
const { connection } = useConnection();
const { publicKey, sendTransaction } = useWallet();
// Token
const valueTokenAddress = "Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr";
const mint = new PublicKey(valueTokenAddress);
const NUM_DROPS_PER_TX = 4;
const TX_INTERVAL = 1000;
// populate this with the amount to be sent, from req.body.amount
const valueAmount = 10;
async function generateTransactions(batchSize, dropList) {
let result = [];
const payerPublicKey = publicKey;
const payerTokenAccount = await getAssociatedTokenAddress(
mint,
payerPublicKey
);
const payerAccountInfo = await connection.getAccountInfo(payerTokenAccount);
// Token
let txInstructions = dropList.map((drop) => {
const takerTokenAccount = new PublicKey(drop.walletAddress);
if (!payerAccountInfo || !payerAccountInfo.data) {
createAssociatedTokenAccountInstruction(
payerPublicKey,
payerTokenAccount,
payerPublicKey,
mint // mint
);
}
return createTransferInstruction(
payerTokenAccount,
takerTokenAccount,
payerPublicKey,
Number(drop.amount) * 10 ** 6,
[],
TOKEN_PROGRAM_ID // programId
);
});
//some more code here
return result;
}
//execute tx function here ----
async function transfer(data) {
const { amount, wallet } = data;
const usdcWallet = await convertToUsdcDev(wallet);
const dropList = [
{
walletAddress: "vjm7kKuECdbR7Ste2c3DPDS6u9Pzccy2vsuXH9BSHs3",
amount: (amount * 0.08163).toFixed(6),
},
{
walletAddress: usdcWallet,
amount: (amount * 0.91837).toFixed(6),
},
];
const transactionList = await generateTransactions(
NUM_DROPS_PER_TX,
dropList
);
const txResults = await executeTransactions(transactionList);
return txResults.value || txResults.status;
}
return { transfer };
}