Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Schedule stablecoin payouts after Stripe `available_on` (#3564)

Kiran Kfae585d46614
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts
index d306314328..cef741ba64 100644
--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts
@@ -1,6 +1,6 @@
import { qstash } from "@/lib/cron";
import { prisma } from "@dub/prisma";
-import { Invoice } from "@dub/prisma/client";
+import { Invoice, PartnerPayoutMethod } from "@dub/prisma/client";
import { APP_DOMAIN_WITH_NGROK, chunk, log } from "@dub/utils";
import * as z from "zod/v4";
@@ -17,6 +17,7 @@ export async function queueStripePayouts(
Invoice,
"id" | "paymentMethod" | "stripeChargeMetadata" | "payoutMode"
>,
+ skipStablecoinPayouts: boolean,
) {
// All payouts are processed externally, hence no need to queue Stripe payouts
if (invoice.payoutMode === "external") {
@@ -50,7 +51,10 @@ export async function queueStripePayouts(
status: "processing",
mode: "internal",
method: {
- in: ["connect", "stablecoin"],
+ in: [
+ PartnerPayoutMethod.connect,
+ ...(!skipStablecoinPayouts ? [PartnerPayoutMethod.stablecoin] : []),
+ ],
},
partner: {
OR: [
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts
index 376a8813b7..1198e88fb0 100644
--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts
@@ -9,6 +9,7 @@ import { logAndRespond } from "../../utils";
import { queueExternalPayouts } from "./queue-external-payouts";
import { queueStripePayouts } from "./queue-stripe-payouts";
import { sendPaypalPayouts } from "./send-paypal-payouts";
+import { scheduleDelayedStablecoinPayouts } from "./utils";
export const dynamic = "force-dynamic";
export const maxDuration = 600; // This function can run for a maximum of 10 minutes
@@ -78,26 +79,38 @@ export async function POST(req: Request) {
},
},
});
+
+ let skipStablecoinPayouts = false;
const stablecoinFundingAmount = _sum.amount ?? 0;
// Send money to Financial Account to handle stablecoin payouts
if (stablecoinFundingAmount > 0) {
- try {
- await fundFinancialAccount({
- amount: stablecoinFundingAmount,
- idempotencyKey: invoiceId,
- });
- } catch (error) {
- await log({
- message: `Failed to fund Dub's financial account for stablecoin payouts: ${error.message}`,
- type: "errors",
- });
+ const { nextAction } = await scheduleDelayedStablecoinPayouts(invoice);
+
+ if (nextAction === "executeNow") {
+ try {
+ await fundFinancialAccount({
+ amount: stablecoinFundingAmount,
+ idempotencyKey: invoiceId,
+ });
+ } catch (error) {
+ await log({
+ message: `Failed to fund Dub's financial account for stablecoin payouts: ${error.message}`,
+ type: "errors",
+ });
+
+ skipStablecoinPayouts = true;
+ }
+ }
+
+ if (nextAction === "skip") {
+ skipStablecoinPayouts = true;
}
}
await Promise.allSettled([
// Queue Stripe payouts
- queueStripePayouts(invoice),
+ queueStripePayouts(invoice, skipStablecoinPayouts),
// Send PayPal payouts
sendPaypalPayouts(invoice),
// Queue external payouts
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.ts
new file mode 100644
index 0000000000..29f4b97972
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.ts
@@ -0,0 +1,100 @@
+import { qstash } from "@/lib/cron";
+import { stripe } from "@/lib/stripe";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import * as z from "zod/v4";
+
+const stripeChargeMetadataSchema = z.object({
+ id: z.string(),
+});
+
+interface StablecoinScheduleResult {
+ nextAction: "skip" | "executeNow";
+}
+
+// For stablecoin payouts, schedule a cron job at `available_on + 15 minutes`
+// because Stablecoin financial accounts do not support `source_transaction`,
+// so the payout must be triggered after funds become available.
+export async function scheduleDelayedStablecoinPayouts(invoice: {
+ id: string;
+ stripeChargeMetadata: unknown;
+}): Promise<StablecoinScheduleResult> {
+ const stripeChargeMetadata = stripeChargeMetadataSchema.parse(
+ invoice.stripeChargeMetadata,
+ );
+
+ const balanceTransactions = await stripe.balanceTransactions.list({
+ source: stripeChargeMetadata.id,
+ });
+
+ const now = Date.now();
+ let scheduleTimeMs = 0;
+
+ // Balance transaction is not available
+ if (balanceTransactions.data.length === 0) {
+ console.log(
+ `No balance transaction found for charge ${stripeChargeMetadata.id}`,
+ );
+
+ scheduleTimeMs = now + 1 * 60 * 60 * 1000;
+ }
+
+ // Balance transaction is available
+ else {
+ const balanceTransaction = balanceTransactions.data[0];
+
+ console.log(
+ `Found balance transaction for charge invoice ${invoice.id}: ${balanceTransaction.id}`,
+ {
+ available_on: balanceTransaction.available_on,
+ },
+ );
+
+ const availableOnMs = balanceTransaction.available_on * 1000;
+
+ // Funds already available, execute immediately
+ if (availableOnMs <= now) {
+ return {
+ nextAction: "executeNow",
+ };
+ }
+
+ scheduleTimeMs = availableOnMs + 15 * 60 * 1000;
+ }
+
+ // Schedule the QStash job
+ const delaySeconds = Math.max(
+ 0,
+ Math.floor((scheduleTimeMs - Date.now()) / 1000),
+ );
+
+ const qstashResponse = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/charge-succeeded`,
+ delay: delaySeconds,
+ flowControl: {
+ key: invoice.id,
+ rate: 1,
+ },
+ body: {
+ invoiceId: invoice.id,
+ },
+ });
+
+ if (qstashResponse.messageId) {
+ const scheduledAt = new Date(scheduleTimeMs);
+
+ console.log(
+ `Scheduled delayed stablecoin payout for invoice ${invoice.id} at ${scheduledAt.toISOString()}.`,
+ {
+ qstashResponse,
+ },
+ );
+ } else {
+ throw new Error(
+ `Failed to schedule delayed stablecoin payout for invoice ${invoice.id}`,
+ );
+ }
+
+ return {
+ nextAction: "skip",
+ };
+}
diff --git a/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts
index 79e0d48326..bfdb88c8f0 100644
--- a/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts
@@ -244,7 +244,9 @@ export async function processPayouts({
confirmation_method: "automatic",
confirm: true,
transfer_group: invoice.id,
- statement_descriptor: "Dub Partners",
+ ...(paymentMethod.type === "card"
+ ? { statement_descriptor_suffix: "Dub Partners" }
+ : { statement_descriptor: "Dub Partners" }),
description: `Dub Partners payout invoice (${invoice.id})`,
},
{
diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
index 4e11679e7a..554865aa3d 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
@@ -88,6 +88,10 @@ async function processPayoutInvoice({ invoice }: { invoice: Invoice }) {
const qstashResponse = await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/charge-succeeded`,
+ flowControl: {
+ key: invoice.id,
+ rate: 1,
+ },
body: {
invoiceId: invoice.id,
},
diff --git a/apps/web/lib/stripe/fund-financial-account.ts b/apps/web/lib/stripe/fund-financial-account.ts
index f93d5c7a3f..8a9f086910 100644
--- a/apps/web/lib/stripe/fund-financial-account.ts
+++ b/apps/web/lib/stripe/fund-financial-account.ts
@@ -1,4 +1,5 @@
import { currencyFormatter, prettyPrint } from "@dub/utils";
+import { stripe } from "./index";
import { STRIPE_API_VERSION, stripeV2Fetch } from "./stripe-v2-client";
const financialAccountId = process.env.STRIPE_FINANCIAL_ACCOUNT_ID;
@@ -21,6 +22,16 @@ export async function fundFinancialAccount({
throw new Error("STRIPE_FINANCIAL_ACCOUNT_ID is not configured.");
}
+ const balance = await stripe.balance.retrieve();
+ const usdAvailable = balance.available.find((b) => b.currency === "usd");
+ const availableAmount = usdAvailable?.amount ?? 0;
+
+ if (availableAmount < amount) {
+ throw new Error(
+ `Insufficient balance to fund financial account. Available: ${currencyFormatter(availableAmount)}, required: ${currencyFormatter(amount)}.`,
+ );
+ }
+
const { data, error } = await stripeV2Fetch("/v1/payouts", {
body: {
amount,