diff --git a/backend/src/services/solana.ts b/backend/src/services/solana.ts index cceb9dd..370e0b2 100644 --- a/backend/src/services/solana.ts +++ b/backend/src/services/solana.ts @@ -38,33 +38,55 @@ try { export const connection = new Connection(RPC_URL, "confirmed"); +let cachedMint: PublicKey | null = null; + // Get or create token mint address export async function getTokenMint(): Promise { try { - // Check env first - if (process.env.SOLANA_MINT_ADDRESS) { - return new PublicKey(process.env.SOLANA_MINT_ADDRESS); + // Return cached mint + if (cachedMint) { + return cachedMint; } - // Check database - const config = await prisma.systemSettings.findFirst(); - if (config?.id) { - // Use a fixed mint derived from program ID for determinism - const mintKeypair = Keypair.generate(); - // For now, auto-create mint on devnet if authority exists - if (mintAuthority && RPC_URL.includes("devnet")) { - console.log("Auto-creating token mint on devnet..."); - const mint = await createMint( - connection, - mintAuthority, - mintAuthority.publicKey, - null, - DECIMALS, - mintKeypair, + // Check env first + if (process.env.SOLANA_MINT_ADDRESS) { + cachedMint = new PublicKey(process.env.SOLANA_MINT_ADDRESS); + return cachedMint; + } + + // Auto-create mint on devnet if authority exists + if (mintAuthority && RPC_URL.includes("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()}...`, ); - console.log(`Token mint created: ${mint.toBase58()}`); - return mint; + 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( + connection, + mintAuthority, + mintAuthority.publicKey, + null, + DECIMALS, + mintKeypair, + ); + cachedMint = mint; + console.log(`Token mint created: ${mint.toBase58()}`); + console.log( + `Add SOLANA_MINT_ADDRESS=${mint.toBase58()} to your .env to persist it`, + ); + return mint; } return null; } catch (error) {