fix(solana): airdrop SOL to mint authority before creating mint

Mint authority had zero SOL balance on devnet, causing
'Attempt to debit an account but found no record of a prior
credit' error. Now getTokenMint() checks balance, airdrops 2 SOL
if needed, then creates the SPL token mint. Also added caching
so mint is only created once.
This commit is contained in:
2026-04-21 15:18:45 -04:00
parent 9b5d477852
commit 871c01c79e
+32 -10
View File
@@ -38,22 +38,41 @@ try {
export const connection = new Connection(RPC_URL, "confirmed"); export const connection = new Connection(RPC_URL, "confirmed");
let cachedMint: PublicKey | null = null;
// Get or create token mint address // Get or create token mint address
export async function getTokenMint(): Promise<PublicKey | null> { export async function getTokenMint(): Promise<PublicKey | null> {
try { try {
// Check env first // Return cached mint
if (process.env.SOLANA_MINT_ADDRESS) { if (cachedMint) {
return new PublicKey(process.env.SOLANA_MINT_ADDRESS); return cachedMint;
} }
// Check database // Check env first
const config = await prisma.systemSettings.findFirst(); if (process.env.SOLANA_MINT_ADDRESS) {
if (config?.id) { cachedMint = new PublicKey(process.env.SOLANA_MINT_ADDRESS);
// Use a fixed mint derived from program ID for determinism return cachedMint;
const mintKeypair = Keypair.generate(); }
// For now, auto-create mint on devnet if authority exists
// Auto-create mint on devnet if authority exists
if (mintAuthority && RPC_URL.includes("devnet")) { if (mintAuthority && RPC_URL.includes("devnet")) {
console.log("Auto-creating token mint on devnet..."); console.log("Auto-creating token mint on devnet...");
// Fund mint authority with SOL first
const balance = await connection.getBalance(mintAuthority.publicKey);
if (balance < 500000000) {
console.log(
`Airdropping SOL to mint authority ${mintAuthority.publicKey.toBase58()}...`,
);
const signature = await connection.requestAirdrop(
mintAuthority.publicKey,
2 * 1000000000,
);
await connection.confirmTransaction(signature);
console.log("Airdrop complete");
}
const mintKeypair = Keypair.generate();
const mint = await createMint( const mint = await createMint(
connection, connection,
mintAuthority, mintAuthority,
@@ -62,10 +81,13 @@ export async function getTokenMint(): Promise<PublicKey | null> {
DECIMALS, DECIMALS,
mintKeypair, mintKeypair,
); );
cachedMint = mint;
console.log(`Token mint created: ${mint.toBase58()}`); console.log(`Token mint created: ${mint.toBase58()}`);
console.log(
`Add SOLANA_MINT_ADDRESS=${mint.toBase58()} to your .env to persist it`,
);
return mint; return mint;
} }
}
return null; return null;
} catch (error) { } catch (error) {
console.error("Failed to get token mint:", error); console.error("Failed to get token mint:", error);