|
| 1 | +import { StrKey } from "@stellar/stellar-sdk" |
| 2 | +import { type Request, type Response } from "express" |
| 3 | +import { type Pool } from "pg" |
| 4 | +import { z } from "zod" |
| 5 | +import { SponsorLicenseStore } from "../db/sponsor-license-store" |
| 6 | + |
| 7 | +const BulkLicenseCheckoutSchema = z.object({ |
| 8 | + wallet_address: z.string().min(1, "Sponsor wallet address required"), |
| 9 | + recipients: z |
| 10 | + .array( |
| 11 | + z.object({ |
| 12 | + wallet_address: z.string().min(1, "Recipient wallet address required"), |
| 13 | + amount_usdc: z.number().positive("Amount must be positive"), |
| 14 | + metadata: z.record(z.unknown()).optional(), |
| 15 | + }), |
| 16 | + ) |
| 17 | + .min(1, "At least one recipient required") |
| 18 | + .max(100, "Maximum 100 recipients per batch"), |
| 19 | + license_type: z.string().optional().default("course_access"), |
| 20 | +}) |
| 21 | + |
| 22 | +export class SponsorLicenseCheckoutController { |
| 23 | + private store: SponsorLicenseStore |
| 24 | + |
| 25 | + constructor(private pool: Pool) { |
| 26 | + this.store = new SponsorLicenseStore(pool) |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * POST /api/sponsors/license-checkout |
| 31 | + * Create bulk license grants for multiple recipients |
| 32 | + */ |
| 33 | + create = async (req: Request, res: Response): Promise<void> => { |
| 34 | + try { |
| 35 | + const body = BulkLicenseCheckoutSchema.parse(req.body) |
| 36 | + |
| 37 | + // Validate all wallet addresses are valid Stellar addresses |
| 38 | + const invalidAddresses: string[] = [] |
| 39 | + |
| 40 | + if (!this.isValidStellarAddress(body.wallet_address)) { |
| 41 | + invalidAddresses.push(body.wallet_address) |
| 42 | + } |
| 43 | + |
| 44 | + for (const recipient of body.recipients) { |
| 45 | + if (!this.isValidStellarAddress(recipient.wallet_address)) { |
| 46 | + invalidAddresses.push(recipient.wallet_address) |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + if (invalidAddresses.length > 0) { |
| 51 | + res.status(400).json({ |
| 52 | + error: "Invalid Stellar wallet addresses", |
| 53 | + invalid_addresses: invalidAddresses, |
| 54 | + }) |
| 55 | + return |
| 56 | + } |
| 57 | + |
| 58 | + // Get or create sponsor organization |
| 59 | + const orgResult = await this.pool.query( |
| 60 | + `SELECT id FROM sponsor_organizations WHERE LOWER(wallet_address) = LOWER($1)`, |
| 61 | + [body.wallet_address], |
| 62 | + ) |
| 63 | + |
| 64 | + let organizationId: number |
| 65 | + |
| 66 | + if (orgResult.rows.length === 0) { |
| 67 | + // Auto-create organization if it doesn't exist |
| 68 | + const insertResult = await this.pool.query( |
| 69 | + `INSERT INTO sponsor_organizations (wallet_address, name) |
| 70 | + VALUES ($1, $2) |
| 71 | + RETURNING id`, |
| 72 | + [ |
| 73 | + body.wallet_address, |
| 74 | + `Organization ${body.wallet_address.slice(0, 8)}`, |
| 75 | + ], |
| 76 | + ) |
| 77 | + organizationId = insertResult.rows[0]?.id as number |
| 78 | + } else { |
| 79 | + organizationId = orgResult.rows[0]?.id as number |
| 80 | + } |
| 81 | + |
| 82 | + // Create license grants |
| 83 | + const grants = body.recipients.map((recipient) => ({ |
| 84 | + organization_id: organizationId, |
| 85 | + recipient_wallet_address: recipient.wallet_address, |
| 86 | + license_type: body.license_type, |
| 87 | + amount_usdc: recipient.amount_usdc, |
| 88 | + metadata: recipient.metadata || {}, |
| 89 | + })) |
| 90 | + |
| 91 | + const createdGrants = await this.store.createBulkGrants(grants) |
| 92 | + |
| 93 | + // Calculate total |
| 94 | + const totalAmount = body.recipients.reduce( |
| 95 | + (sum, r) => sum + r.amount_usdc, |
| 96 | + 0, |
| 97 | + ) |
| 98 | + |
| 99 | + // In a real implementation, we would: |
| 100 | + // 1. Queue these grants for on-chain minting via a worker |
| 101 | + // 2. Return immediately with pending status |
| 102 | + // 3. Let the worker update status to 'minted' once tx confirms |
| 103 | + // |
| 104 | + // For now, we'll mark them as pending and generate a placeholder tx hash |
| 105 | + // that will be replaced by the actual tx hash once minted |
| 106 | + |
| 107 | + res.status(201).json({ |
| 108 | + success: true, |
| 109 | + grants: createdGrants, |
| 110 | + summary: { |
| 111 | + total_recipients: body.recipients.length, |
| 112 | + total_amount_usdc: totalAmount.toFixed(2), |
| 113 | + organization_id: organizationId, |
| 114 | + status: "pending", |
| 115 | + message: |
| 116 | + "License grants created successfully. Minting will be processed shortly.", |
| 117 | + }, |
| 118 | + }) |
| 119 | + } catch (error) { |
| 120 | + if (error instanceof z.ZodError) { |
| 121 | + res.status(400).json({ |
| 122 | + error: "Validation failed", |
| 123 | + details: error.errors, |
| 124 | + }) |
| 125 | + return |
| 126 | + } |
| 127 | + |
| 128 | + console.error("Error creating license grants:", error) |
| 129 | + res.status(500).json({ |
| 130 | + error: "Failed to create license grants", |
| 131 | + message: error instanceof Error ? error.message : "Unknown error", |
| 132 | + }) |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * GET /api/sponsors/license-checkout/:walletAddress |
| 138 | + * Get all license grants for a sponsor organization |
| 139 | + */ |
| 140 | + getByOrganization = async (req: Request, res: Response): Promise<void> => { |
| 141 | + try { |
| 142 | + const { walletAddress } = req.params |
| 143 | + |
| 144 | + if (!walletAddress) { |
| 145 | + res.status(400).json({ error: "Wallet address required" }) |
| 146 | + return |
| 147 | + } |
| 148 | + |
| 149 | + // Get organization |
| 150 | + const orgResult = await this.pool.query( |
| 151 | + `SELECT id FROM sponsor_organizations WHERE LOWER(wallet_address) = LOWER($1)`, |
| 152 | + [walletAddress], |
| 153 | + ) |
| 154 | + |
| 155 | + if (orgResult.rows.length === 0) { |
| 156 | + res.status(404).json({ error: "Organization not found" }) |
| 157 | + return |
| 158 | + } |
| 159 | + |
| 160 | + const organizationId = orgResult.rows[0]?.id as number |
| 161 | + const grants = await this.store.getGrantsByOrganization(organizationId) |
| 162 | + const stats = await this.store.getOrganizationGrantStats(organizationId) |
| 163 | + |
| 164 | + res.json({ |
| 165 | + grants, |
| 166 | + stats, |
| 167 | + }) |
| 168 | + } catch (error) { |
| 169 | + console.error("Error fetching license grants:", error) |
| 170 | + res.status(500).json({ |
| 171 | + error: "Failed to fetch license grants", |
| 172 | + }) |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + /** |
| 177 | + * GET /api/sponsors/license-checkout/recipient/:walletAddress |
| 178 | + * Get all license grants received by a specific wallet |
| 179 | + */ |
| 180 | + getByRecipient = async (req: Request, res: Response): Promise<void> => { |
| 181 | + try { |
| 182 | + const { walletAddress } = req.params |
| 183 | + |
| 184 | + if (!walletAddress) { |
| 185 | + res.status(400).json({ error: "Wallet address required" }) |
| 186 | + return |
| 187 | + } |
| 188 | + |
| 189 | + const grants = await this.store.getGrantsByRecipient(walletAddress) |
| 190 | + |
| 191 | + res.json({ |
| 192 | + grants, |
| 193 | + total_received: grants.length, |
| 194 | + }) |
| 195 | + } catch (error) { |
| 196 | + console.error("Error fetching recipient grants:", error) |
| 197 | + res.status(500).json({ |
| 198 | + error: "Failed to fetch recipient grants", |
| 199 | + }) |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + /** |
| 204 | + * Validate if a string is a valid Stellar address |
| 205 | + */ |
| 206 | + private isValidStellarAddress(address: string): boolean { |
| 207 | + try { |
| 208 | + return StrKey.isValidEd25519PublicKey(address) |
| 209 | + } catch { |
| 210 | + return false |
| 211 | + } |
| 212 | + } |
| 213 | +} |
0 commit comments