|
| 1 | +import { ORPCError } from '@orpc/client' |
| 2 | +import { createORPCClient } from '@orpc/client' |
| 3 | +import { RPCLink } from '@orpc/client/fetch' |
| 4 | +import type { ContractRouterClient } from '@orpc/contract' |
| 5 | +import { contract, type ProgrammaticPayoutResult } from '@moneydevkit/api-contract' |
| 6 | + |
| 7 | +import { MAINNET_MDK_BASE_URL } from './mdk-config' |
| 8 | +import { failure, success, type MdkError, type Result } from './types' |
| 9 | + |
| 10 | +/** |
| 11 | + * Options accepted by the server-only programmatic payout helper. |
| 12 | + */ |
| 13 | +export type ProgrammaticPayoutOptions = { |
| 14 | + /** Amount to send, in sats. */ |
| 15 | + amountSats: number |
| 16 | + /** Lightning destination to pay from this server-side request. */ |
| 17 | + destination: string |
| 18 | + /** |
| 19 | + * Idempotency key used to deduplicate retries of the same logical payout. |
| 20 | + * Pass the same value on retry to avoid double-pays. Typically your own |
| 21 | + * orderId / withdrawalId / requestId. Must be a stable string per logical |
| 22 | + * payout, not a fresh value generated on each call. |
| 23 | + */ |
| 24 | + idempotencyKey: string |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * Errors the SDK classifies as definitely-retryable. The same call with the |
| 29 | + * same idempotency key can safely be sent again; mdk.com will dedupe. |
| 30 | + */ |
| 31 | +const RETRYABLE_CODES = new Set([ |
| 32 | + 'PROGRAMMATIC_PAYOUT_FAILED', |
| 33 | + 'PROGRAMMATIC_PAYOUT_DAILY_LIMIT_EXCEEDED', |
| 34 | +]) |
| 35 | + |
| 36 | +/** |
| 37 | + * Errors the SDK classifies as not retryable without changing inputs or config. |
| 38 | + */ |
| 39 | +const NON_RETRYABLE_CODES = new Set([ |
| 40 | + 'PROGRAMMATIC_PAYOUT_APP_KEY_REQUIRED', |
| 41 | + 'PROGRAMMATIC_PAYOUTS_DISABLED', |
| 42 | + 'PROGRAMMATIC_PAYOUT_TOO_LARGE', |
| 43 | + 'INVALID_PROGRAMMATIC_PAYOUT_AMOUNT', |
| 44 | + 'VALIDATION_ERROR', |
| 45 | + 'NOT_FOUND', |
| 46 | +]) |
| 47 | + |
| 48 | +/** |
| 49 | + * Map a backend error code to a short, actionable reason string the caller |
| 50 | + * can branch on. Returns undefined for unrecognized codes. |
| 51 | + */ |
| 52 | +function reasonForCode(code: string | undefined): string | undefined { |
| 53 | + if (!code) return undefined |
| 54 | + switch (code) { |
| 55 | + case 'PROGRAMMATIC_PAYOUT_DAILY_LIMIT_EXCEEDED': |
| 56 | + return 'daily_limit_exceeded' |
| 57 | + case 'PROGRAMMATIC_PAYOUT_TOO_LARGE': |
| 58 | + return 'amount_too_large' |
| 59 | + case 'PROGRAMMATIC_PAYOUTS_DISABLED': |
| 60 | + return 'programmatic_payouts_disabled' |
| 61 | + case 'PROGRAMMATIC_PAYOUT_APP_KEY_REQUIRED': |
| 62 | + return 'app_scoped_api_key_required' |
| 63 | + case 'PROGRAMMATIC_PAYOUT_FAILED': |
| 64 | + return 'payout_dispatch_failed' |
| 65 | + case 'INVALID_PROGRAMMATIC_PAYOUT_AMOUNT': |
| 66 | + return 'amount_invalid' |
| 67 | + default: |
| 68 | + return undefined |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +function classifyOrpcError(err: ORPCError<string, unknown>): MdkError { |
| 73 | + const data = err.data as { code?: string } | undefined |
| 74 | + const code = data?.code |
| 75 | + const retryable = code |
| 76 | + ? RETRYABLE_CODES.has(code) |
| 77 | + ? true |
| 78 | + : NON_RETRYABLE_CODES.has(code) |
| 79 | + ? false |
| 80 | + : undefined |
| 81 | + : undefined |
| 82 | + return { |
| 83 | + code: code ?? err.code ?? 'payout_failed', |
| 84 | + message: err.message, |
| 85 | + status: err.status, |
| 86 | + retryable, |
| 87 | + reason: reasonForCode(code), |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +/** |
| 92 | + * Trigger a payout from a server function through mdk.com's control plane. |
| 93 | + * |
| 94 | + * This helper accepts a destination because it is intended for trusted server |
| 95 | + * functions. Never expose it through a client-controlled route without your |
| 96 | + * own authorization and business rules. |
| 97 | + * |
| 98 | + * The returned result distinguishes retryable failures (e.g. transient |
| 99 | + * dispatch failures, daily limit) from terminal ones (e.g. app config, validation). |
| 100 | + * Use `result.error.retryable` and `result.error.reason` to drive retries. |
| 101 | + */ |
| 102 | +export async function programmaticPayout( |
| 103 | + options: ProgrammaticPayoutOptions, |
| 104 | +): Promise<Result<ProgrammaticPayoutResult>> { |
| 105 | + if (typeof window !== 'undefined') { |
| 106 | + return failure({ |
| 107 | + code: 'server_only', |
| 108 | + message: 'programmaticPayout() can only be called from a server function.', |
| 109 | + retryable: false, |
| 110 | + }) |
| 111 | + } |
| 112 | + |
| 113 | + if (!Number.isInteger(options.amountSats) || options.amountSats <= 0) { |
| 114 | + return failure({ |
| 115 | + code: 'invalid_amount', |
| 116 | + message: 'Enter a positive whole-sat amount before triggering a payout.', |
| 117 | + retryable: false, |
| 118 | + }) |
| 119 | + } |
| 120 | + const destination = options.destination.trim() |
| 121 | + if (!destination || destination.length > 4096) { |
| 122 | + return failure({ |
| 123 | + code: 'invalid_destination', |
| 124 | + message: 'Enter a valid Lightning destination before triggering a payout.', |
| 125 | + retryable: false, |
| 126 | + }) |
| 127 | + } |
| 128 | + if (/[\u0000-\u001f\u007f]/.test(destination)) { |
| 129 | + return failure({ |
| 130 | + code: 'invalid_destination', |
| 131 | + message: 'Enter a valid Lightning destination before triggering a payout.', |
| 132 | + retryable: false, |
| 133 | + }) |
| 134 | + } |
| 135 | + if (typeof options.idempotencyKey !== 'string' || options.idempotencyKey.length === 0) { |
| 136 | + return failure({ |
| 137 | + code: 'invalid_idempotency_key', |
| 138 | + message: |
| 139 | + 'Pass a stable idempotencyKey (e.g. your orderId) so retries do not double-pay.', |
| 140 | + retryable: false, |
| 141 | + }) |
| 142 | + } |
| 143 | + |
| 144 | + const accessToken = process.env.MDK_ACCESS_TOKEN |
| 145 | + if (!accessToken) { |
| 146 | + return failure({ |
| 147 | + code: 'missing_access_token', |
| 148 | + message: 'Set MDK_ACCESS_TOKEN in your environment before triggering a payout.', |
| 149 | + retryable: false, |
| 150 | + }) |
| 151 | + } |
| 152 | + const baseUrl = process.env.MDK_API_BASE_URL ?? MAINNET_MDK_BASE_URL |
| 153 | + |
| 154 | + try { |
| 155 | + const link = new RPCLink({ |
| 156 | + url: baseUrl, |
| 157 | + headers: () => ({ |
| 158 | + 'x-api-key': accessToken, |
| 159 | + }), |
| 160 | + }) |
| 161 | + const client: ContractRouterClient<typeof contract> = createORPCClient(link) |
| 162 | + const result = await client.checkout.programmaticPayout({ |
| 163 | + amountSats: options.amountSats, |
| 164 | + destination, |
| 165 | + idempotencyKey: options.idempotencyKey, |
| 166 | + }) |
| 167 | + return success(result) |
| 168 | + } catch (err) { |
| 169 | + if (err instanceof ORPCError) { |
| 170 | + return failure(classifyOrpcError(err)) |
| 171 | + } |
| 172 | + return failure({ |
| 173 | + code: 'payout_failed', |
| 174 | + message: err instanceof Error ? err.message : String(err), |
| 175 | + retryable: true, |
| 176 | + }) |
| 177 | + } |
| 178 | +} |
0 commit comments