|
| 1 | +import { NextRequest, NextResponse } from 'next/server' |
| 2 | +import { BALANCE_UPDATE_DELAY } from '@/lib/utils' |
| 3 | +import { initializeNearAccount, depositUSDC, getUSDCBalance } from '@/lib/near' |
| 4 | + |
| 5 | +export async function GET(request: NextRequest) { |
| 6 | + try { |
| 7 | + if (process.env.CRON_SECRET) { |
| 8 | + const authHeader = request.headers.get('Authorization') |
| 9 | + if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) { |
| 10 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 11 | + } |
| 12 | + } |
| 13 | + |
| 14 | + const { searchParams } = new URL(request.url) |
| 15 | + const amount = searchParams.get('amount') ? Number(searchParams.get('amount')) : undefined |
| 16 | + const accountId = process.env.NEXT_PUBLIC_ACCOUNT_ID |
| 17 | + if (!accountId) { |
| 18 | + return NextResponse.json({ error: 'accountId is not configured' }, { status: 500 }) |
| 19 | + } |
| 20 | + |
| 21 | + const depositAmount = amount || 10 |
| 22 | + |
| 23 | + const account = await initializeNearAccount(accountId) |
| 24 | + |
| 25 | + const usdcBalance = await getUSDCBalance(account) |
| 26 | + const usdcBalanceDecimal = Number(usdcBalance) / 1_000_000 |
| 27 | + |
| 28 | + if (usdcBalanceDecimal < depositAmount) { |
| 29 | + return NextResponse.json({ |
| 30 | + error: `Insufficient USDC balance (required: $${depositAmount}, available: $${usdcBalanceDecimal.toFixed(2)})` |
| 31 | + }, { status: 400 }) |
| 32 | + } |
| 33 | + |
| 34 | + const amountToDeposit = BigInt(depositAmount * 1_000_000) |
| 35 | + |
| 36 | + const tx = await depositUSDC(account, amountToDeposit) |
| 37 | + |
| 38 | + await new Promise(resolve => setTimeout(resolve, BALANCE_UPDATE_DELAY)) |
| 39 | + |
| 40 | + return NextResponse.json({ |
| 41 | + message: `Successfully deposited $${depositAmount} USDC`, |
| 42 | + transactionHash: tx.transaction.hash, |
| 43 | + amount: depositAmount |
| 44 | + }) |
| 45 | + |
| 46 | + } catch (error) { |
| 47 | + console.error('Error in deposit endpoint:', error) |
| 48 | + return NextResponse.json({ error: 'Failed to process deposit request' }, { status: 500 }) |
| 49 | + } |
| 50 | +} |
0 commit comments