|
| 1 | +/** |
| 2 | + * BlockRun Music Client - Generate music tracks via x402 micropayments. |
| 3 | + * |
| 4 | + * SECURITY NOTE - Private Key Handling: |
| 5 | + * Your private key NEVER leaves your machine. Here's what happens: |
| 6 | + * 1. Key stays local - only used to sign an EIP-712 typed data message |
| 7 | + * 2. Only the SIGNATURE is sent in the PAYMENT-SIGNATURE header |
| 8 | + * 3. BlockRun verifies the signature on-chain via Coinbase CDP facilitator |
| 9 | + * |
| 10 | + * Usage: |
| 11 | + * import { MusicClient } from '@blockrun/llm'; |
| 12 | + * |
| 13 | + * const client = new MusicClient({ privateKey: '0x...' }); |
| 14 | + * const result = await client.generate('upbeat synthwave with neon pads'); |
| 15 | + * console.log(result.data[0].url); // CDN URL — download within 24h |
| 16 | + */ |
| 17 | + |
| 18 | +import { privateKeyToAccount } from "viem/accounts"; |
| 19 | +import type { Account } from "viem/accounts"; |
| 20 | +import { |
| 21 | + type MusicClientOptions, |
| 22 | + type MusicResponse, |
| 23 | + type MusicGenerateOptions, |
| 24 | + type Spending, |
| 25 | + APIError, |
| 26 | + PaymentError, |
| 27 | +} from "./types"; |
| 28 | +import { |
| 29 | + createPaymentPayload, |
| 30 | + parsePaymentRequired, |
| 31 | + extractPaymentDetails, |
| 32 | +} from "./x402"; |
| 33 | +import { |
| 34 | + validatePrivateKey, |
| 35 | + validateApiUrl, |
| 36 | + sanitizeErrorResponse, |
| 37 | +} from "./validation"; |
| 38 | + |
| 39 | +const DEFAULT_API_URL = "https://blockrun.ai/api"; |
| 40 | +const DEFAULT_MODEL = "minimax/music-2.5+"; |
| 41 | +const DEFAULT_TIMEOUT = 210_000; // music gen takes 1-3 min |
| 42 | + |
| 43 | +/** |
| 44 | + * BlockRun Music Generation Client. |
| 45 | + * |
| 46 | + * Generate full-length ~3 minute music tracks using MiniMax Music 2.5+ |
| 47 | + * with automatic x402 micropayments on Base chain. |
| 48 | + * |
| 49 | + * Pricing: $0.1575/track |
| 50 | + * Note: Generated URLs expire in ~24h — download immediately if needed. |
| 51 | + */ |
| 52 | +export class MusicClient { |
| 53 | + private account: Account; |
| 54 | + private privateKey: `0x${string}`; |
| 55 | + private apiUrl: string; |
| 56 | + private timeout: number; |
| 57 | + private sessionTotalUsd: number = 0; |
| 58 | + private sessionCalls: number = 0; |
| 59 | + |
| 60 | + constructor(options: MusicClientOptions = {}) { |
| 61 | + const envKey = |
| 62 | + typeof process !== "undefined" && process.env |
| 63 | + ? process.env.BLOCKRUN_WALLET_KEY || process.env.BASE_CHAIN_WALLET_KEY |
| 64 | + : undefined; |
| 65 | + const privateKey = options.privateKey || envKey; |
| 66 | + |
| 67 | + if (!privateKey) { |
| 68 | + throw new Error( |
| 69 | + "Private key required. Pass privateKey in options or set BLOCKRUN_WALLET_KEY environment variable." |
| 70 | + ); |
| 71 | + } |
| 72 | + |
| 73 | + validatePrivateKey(privateKey); |
| 74 | + this.privateKey = privateKey as `0x${string}`; |
| 75 | + this.account = privateKeyToAccount(privateKey as `0x${string}`); |
| 76 | + |
| 77 | + const apiUrl = options.apiUrl || DEFAULT_API_URL; |
| 78 | + validateApiUrl(apiUrl); |
| 79 | + this.apiUrl = apiUrl.replace(/\/$/, ""); |
| 80 | + |
| 81 | + this.timeout = options.timeout || DEFAULT_TIMEOUT; |
| 82 | + } |
| 83 | + |
| 84 | + /** |
| 85 | + * Generate a music track from a text prompt. |
| 86 | + * |
| 87 | + * Takes 1-3 minutes. Returns a CDN URL valid for ~24h. |
| 88 | + * |
| 89 | + * @param prompt - Music style, mood, or description |
| 90 | + * @param options - Optional generation parameters |
| 91 | + * @returns MusicResponse with track URL and metadata |
| 92 | + * |
| 93 | + * @example |
| 94 | + * const result = await client.generate('chill lo-fi beats with piano'); |
| 95 | + * console.log(result.data[0].url); // Download this URL — expires in 24h |
| 96 | + * |
| 97 | + * @example With lyrics |
| 98 | + * const result = await client.generate('upbeat pop song', { |
| 99 | + * instrumental: false, |
| 100 | + * lyrics: 'Hello world, this is my song...' |
| 101 | + * }); |
| 102 | + */ |
| 103 | + async generate( |
| 104 | + prompt: string, |
| 105 | + options?: MusicGenerateOptions |
| 106 | + ): Promise<MusicResponse> { |
| 107 | + const instrumental = options?.instrumental ?? true; |
| 108 | + const lyrics = options?.lyrics?.trim(); |
| 109 | + |
| 110 | + if (instrumental && lyrics) { |
| 111 | + throw new Error("Cannot specify lyrics when instrumental is true"); |
| 112 | + } |
| 113 | + |
| 114 | + const body: Record<string, unknown> = { |
| 115 | + model: options?.model || DEFAULT_MODEL, |
| 116 | + prompt, |
| 117 | + instrumental, |
| 118 | + }; |
| 119 | + if (lyrics) body.lyrics = lyrics; |
| 120 | + |
| 121 | + return this.requestWithPayment("/v1/audio/generations", body); |
| 122 | + } |
| 123 | + |
| 124 | + private async requestWithPayment( |
| 125 | + endpoint: string, |
| 126 | + body: Record<string, unknown> |
| 127 | + ): Promise<MusicResponse> { |
| 128 | + const url = `${this.apiUrl}${endpoint}`; |
| 129 | + |
| 130 | + const response = await this.fetchWithTimeout(url, { |
| 131 | + method: "POST", |
| 132 | + headers: { "Content-Type": "application/json" }, |
| 133 | + body: JSON.stringify(body), |
| 134 | + }); |
| 135 | + |
| 136 | + if (response.status === 402) { |
| 137 | + return this.handlePaymentAndRetry(url, body, response); |
| 138 | + } |
| 139 | + |
| 140 | + if (!response.ok) { |
| 141 | + let errorBody: unknown; |
| 142 | + try { errorBody = await response.json(); } catch { errorBody = { error: "Request failed" }; } |
| 143 | + throw new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(errorBody)); |
| 144 | + } |
| 145 | + |
| 146 | + return response.json() as Promise<MusicResponse>; |
| 147 | + } |
| 148 | + |
| 149 | + private async handlePaymentAndRetry( |
| 150 | + url: string, |
| 151 | + body: Record<string, unknown>, |
| 152 | + response: Response |
| 153 | + ): Promise<MusicResponse> { |
| 154 | + let paymentHeader = response.headers.get("payment-required"); |
| 155 | + |
| 156 | + if (!paymentHeader) { |
| 157 | + try { |
| 158 | + const respBody = (await response.json()) as Record<string, unknown>; |
| 159 | + if (respBody.x402 || respBody.accepts) { |
| 160 | + paymentHeader = btoa(JSON.stringify(respBody)); |
| 161 | + } |
| 162 | + } catch { /* ignore */ } |
| 163 | + } |
| 164 | + |
| 165 | + if (!paymentHeader) { |
| 166 | + throw new PaymentError("402 response but no payment requirements found"); |
| 167 | + } |
| 168 | + |
| 169 | + const paymentRequired = parsePaymentRequired(paymentHeader); |
| 170 | + const details = extractPaymentDetails(paymentRequired); |
| 171 | + |
| 172 | + const paymentPayload = await createPaymentPayload( |
| 173 | + this.privateKey, |
| 174 | + this.account.address, |
| 175 | + details.recipient, |
| 176 | + details.amount, |
| 177 | + details.network || "eip155:8453", |
| 178 | + { |
| 179 | + resourceUrl: details.resource?.url || `${this.apiUrl}/v1/audio/generations`, |
| 180 | + resourceDescription: details.resource?.description || "BlockRun Music Generation", |
| 181 | + maxTimeoutSeconds: details.maxTimeoutSeconds || 300, |
| 182 | + extra: details.extra, |
| 183 | + } |
| 184 | + ); |
| 185 | + |
| 186 | + const retryResponse = await this.fetchWithTimeout(url, { |
| 187 | + method: "POST", |
| 188 | + headers: { |
| 189 | + "Content-Type": "application/json", |
| 190 | + "PAYMENT-SIGNATURE": paymentPayload, |
| 191 | + }, |
| 192 | + body: JSON.stringify(body), |
| 193 | + }); |
| 194 | + |
| 195 | + if (retryResponse.status === 402) { |
| 196 | + throw new PaymentError("Payment was rejected. Check your wallet balance."); |
| 197 | + } |
| 198 | + |
| 199 | + if (!retryResponse.ok) { |
| 200 | + let errorBody: unknown; |
| 201 | + try { errorBody = await retryResponse.json(); } catch { errorBody = { error: "Request failed" }; } |
| 202 | + throw new APIError(`API error after payment: ${retryResponse.status}`, retryResponse.status, sanitizeErrorResponse(errorBody)); |
| 203 | + } |
| 204 | + |
| 205 | + const data = await retryResponse.json() as MusicResponse; |
| 206 | + |
| 207 | + // Track spending |
| 208 | + this.sessionCalls++; |
| 209 | + this.sessionTotalUsd += 0.1575; |
| 210 | + |
| 211 | + // Attach tx hash from response header if present |
| 212 | + const txHash = retryResponse.headers.get("x-payment-receipt") || retryResponse.headers.get("X-Payment-Receipt"); |
| 213 | + if (txHash) data.txHash = txHash; |
| 214 | + |
| 215 | + return data; |
| 216 | + } |
| 217 | + |
| 218 | + private async fetchWithTimeout(url: string, options: RequestInit): Promise<Response> { |
| 219 | + const controller = new AbortController(); |
| 220 | + const timeoutId = setTimeout(() => controller.abort(), this.timeout); |
| 221 | + try { |
| 222 | + return await fetch(url, { ...options, signal: controller.signal }); |
| 223 | + } finally { |
| 224 | + clearTimeout(timeoutId); |
| 225 | + } |
| 226 | + } |
| 227 | + |
| 228 | + getWalletAddress(): string { |
| 229 | + return this.account.address; |
| 230 | + } |
| 231 | + |
| 232 | + getSpending(): Spending { |
| 233 | + return { totalUsd: this.sessionTotalUsd, calls: this.sessionCalls }; |
| 234 | + } |
| 235 | +} |
| 236 | + |
| 237 | +export default MusicClient; |
0 commit comments