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.

Stablecoins (#3449)

Kiran Kd764f5857d25
diff --git a/apps/web/.env.example b/apps/web/.env.example
index f3abb13b91..b71c704e86 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -63,6 +63,8 @@ UNSUBSCRIBE_TOKEN_SECRET=
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
+STRIPE_CONNECT_WEBHOOK_SECRET=
+STRIPE_CONNECT_V2_WEBHOOK_SECRET=
# Stripe App webhook events
STRIPE_APP_WEBHOOK_SECRET=
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-external-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-external-payouts.ts
index 9b4b2b0d3d..cb4074d457 100644
--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-external-payouts.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-external-payouts.ts
@@ -141,7 +141,7 @@ export async function queueExternalPayouts(
endDate: payout.periodEnd,
mode: "external",
paymentMethod: invoice.paymentMethod ?? "ach",
- payoutMethod: payout.partner.paypalEmail ? "paypal" : "stripe",
+ payoutMethod: payout.method,
},
},
})),
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 cc2a290c5f..d306314328 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
@@ -8,6 +8,10 @@ const stripeChargeMetadataSchema = z.object({
id: z.string(), // Stripe charge id
});
+const queue = qstash.queue({
+ queueName: "send-stripe-payout",
+});
+
export async function queueStripePayouts(
invoice: Pick<
Invoice,
@@ -45,20 +49,28 @@ export async function queueStripePayouts(
invoiceId,
status: "processing",
mode: "internal",
+ method: {
+ in: ["connect", "stablecoin"],
+ },
partner: {
- stripeConnectId: {
- not: null,
- },
+ OR: [
+ {
+ stripeConnectId: {
+ not: null,
+ },
+ },
+ {
+ stripeRecipientId: {
+ not: null,
+ },
+ },
+ ],
// here we're not checking for payoutsEnabledAt since we want visiblity
// if a stripe.transfers.create fails due to restricted Stripe account
},
},
});
- const queue = qstash.queue({
- queueName: "send-stripe-payout",
- });
-
const chunkedPartners = chunk(partnersInCurrentInvoice, 100);
for (let i = 0; i < chunkedPartners.length; i++) {
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 80ac02a084..11744d5b29 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
@@ -1,5 +1,6 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { fundFinancialAccount } from "@/lib/stripe/fund-financial-account";
import { prisma } from "@dub/prisma";
import { log } from "@dub/utils";
import * as z from "zod/v4";
@@ -52,6 +53,41 @@ export async function POST(req: Request) {
);
}
+ // Set the method for each payout in the invoice to the corresponding partner's default payout method
+ await prisma.$executeRaw`
+ UPDATE Payout p
+ INNER JOIN Partner pr ON p.partnerId = pr.id
+ SET p.method = pr.defaultPayoutMethod
+ WHERE p.invoiceId = ${invoice.id}
+ AND pr.defaultPayoutMethod IS NOT NULL
+ AND p.status = 'processing'
+ `;
+
+ // Fund the total stablecoin payout amount for this invoice
+ const { _sum } = await prisma.payout.aggregate({
+ _sum: { amount: true },
+ where: {
+ invoiceId: invoice.id,
+ method: "stablecoin",
+ },
+ });
+ const stablecoinFundingAmount = _sum.amount ?? 0;
+
+ // Send money to Dub's 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",
+ });
+ }
+ }
+
await Promise.allSettled([
// Queue Stripe payouts
queueStripePayouts(invoice),
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts
index 60b6ac4147..f1683e3cc8 100644
--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts
@@ -11,6 +11,7 @@ export async function sendPaypalPayouts(invoice: Pick<Invoice, "id">) {
invoiceId: invoice.id,
status: "processing",
mode: "internal",
+ method: "paypal",
partner: {
payoutsEnabledAt: {
not: null,
@@ -71,7 +72,6 @@ export async function sendPaypalPayouts(invoice: Pick<Invoice, "id">) {
email: payout.partner.email!,
program: payout.program,
payout,
- variant: "paypal",
},
})),
);
diff --git a/apps/web/app/(ee)/api/cron/payouts/process/updates/route.ts b/apps/web/app/(ee)/api/cron/payouts/process/updates/route.ts
index 5753d59d24..d275ac98d3 100644
--- a/apps/web/app/(ee)/api/cron/payouts/process/updates/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/process/updates/route.ts
@@ -61,8 +61,7 @@ export async function POST(req: Request) {
}
const auditLogResponse = await recordAuditLog(
- payouts.map((p) => {
- const { program, partner, invoice, ...payout } = p;
+ payouts.map(({ program, partner, invoice, ...payout }) => {
return {
workspaceId: program.workspaceId,
programId: program.id,
@@ -113,7 +112,7 @@ export async function POST(req: Request) {
endDate: payout.periodEnd,
mode: payout.mode,
paymentMethod: invoice.paymentMethod ?? "ach",
- payoutMethod: payout.partner.paypalEmail ? "paypal" : "stripe",
+ payoutMethod: payout.partner.defaultPayoutMethod ?? null,
},
}),
})),
diff --git a/apps/web/app/(ee)/api/cron/payouts/send-stripe-payout/route.ts b/apps/web/app/(ee)/api/cron/payouts/send-stripe-payout/route.ts
index da730b8e2a..54b2eb2f77 100644
--- a/apps/web/app/(ee)/api/cron/payouts/send-stripe-payout/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/send-stripe-payout/route.ts
@@ -1,6 +1,8 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { createStablecoinPayout } from "@/lib/partners/create-stablecoin-payout";
import { createStripeTransfer } from "@/lib/partners/create-stripe-transfer";
+import { prisma } from "@dub/prisma";
import { log } from "@dub/utils";
import * as z from "zod/v4";
import { logAndRespond } from "../../utils";
@@ -27,12 +29,41 @@ export async function POST(req: Request) {
JSON.parse(rawBody),
);
- await createStripeTransfer({
- partnerId,
- invoiceId,
- chargeId,
+ const payout = await prisma.payout.findFirst({
+ where: {
+ partnerId,
+ invoiceId,
+ status: "processing",
+ mode: "internal",
+ method: {
+ in: ["connect", "stablecoin"],
+ },
+ },
+ select: {
+ method: true,
+ },
});
+ if (!payout) {
+ return logAndRespond(
+ `No payout found for partner ${partnerId} and invoice ${invoiceId}`,
+ );
+ }
+
+ // Run the appropriate payout creation function based on the payout method
+ if (payout.method === "connect") {
+ await createStripeTransfer({
+ partnerId,
+ invoiceId,
+ chargeId,
+ });
+ } else if (payout.method === "stablecoin") {
+ await createStablecoinPayout({
+ partnerId,
+ invoiceId,
+ });
+ }
+
return logAndRespond(
`Processed send-stripe-payout job for partner ${partnerId} and invoice ${invoiceId}`,
);
diff --git a/apps/web/app/(ee)/api/partner-profile/payouts/settings/route.ts b/apps/web/app/(ee)/api/partner-profile/payouts/settings/route.ts
index f81e33ab75..95e55428cc 100644
--- a/apps/web/app/(ee)/api/partner-profile/payouts/settings/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/payouts/settings/route.ts
@@ -1,14 +1,10 @@
import { withPartnerProfile } from "@/lib/auth/partner";
-import { getPartnerBankAccount } from "@/lib/partners/get-partner-bank-account";
+import { getPartnerPayoutMethods } from "@/lib/payouts/api/get-partner-payout-methods";
import { NextResponse } from "next/server";
// GET /api/partner-profile/payouts/settings
export const GET = withPartnerProfile(async ({ partner }) => {
- if (!partner.stripeConnectId) {
- return NextResponse.json({});
- }
+ const payoutMethods = await getPartnerPayoutMethods(partner);
- const bankAccount = await getPartnerBankAccount(partner.stripeConnectId);
-
- return NextResponse.json(bankAccount);
+ return NextResponse.json(payoutMethods);
});
diff --git a/apps/web/app/(ee)/api/stripe/connect/v2/webhook/outbound-payment-failed.ts b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/outbound-payment-failed.ts
new file mode 100644
index 0000000000..c5065e0193
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/outbound-payment-failed.ts
@@ -0,0 +1,37 @@
+import { getStripeOutboundPayment } from "@/lib/stripe/get-stripe-outbound-payment";
+import { OUTBOUND_PAYMENT_FAILURE_REASONS } from "@/lib/stripe/stripe-v2-schemas";
+import { prisma } from "@dub/prisma";
+import { pluralize } from "@dub/utils";
+import Stripe from "stripe";
+
+export async function outboundPaymentFailed(event: Stripe.ThinEvent) {
+ const { related_object: relatedObject } = event;
+
+ if (!relatedObject) {
+ return "No related object found in event, skipping...";
+ }
+
+ const { id: outboundPaymentId } = relatedObject;
+
+ const outboundPayment = await getStripeOutboundPayment(outboundPaymentId);
+
+ const rawFailureReason = outboundPayment.status_details?.failed?.reason;
+ const failureReason = rawFailureReason
+ ? OUTBOUND_PAYMENT_FAILURE_REASONS[rawFailureReason]
+ : undefined;
+
+ const updatedPayouts = await prisma.payout.updateMany({
+ where: {
+ stripePayoutId: outboundPaymentId,
+ },
+ data: {
+ status: "failed",
+ failureReason,
+ },
+ });
+
+ // TODO:
+ // Send email notification
+
+ return `Updated ${updatedPayouts.count} ${pluralize("payout", updatedPayouts.count)} to failed status.`;
+}
diff --git a/apps/web/app/(ee)/api/stripe/connect/v2/webhook/outbound-payment-posted.ts b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/outbound-payment-posted.ts
new file mode 100644
index 0000000000..24eeaa2514
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/outbound-payment-posted.ts
@@ -0,0 +1,37 @@
+import { getStripeOutboundPayment } from "@/lib/stripe/get-stripe-outbound-payment";
+import { prisma } from "@dub/prisma";
+import { pluralize } from "@dub/utils";
+import Stripe from "stripe";
+
+export async function outboundPaymentPosted(event: Stripe.ThinEvent) {
+ const { related_object: relatedObject } = event;
+
+ if (!relatedObject) {
+ return "No related object found in event, skipping...";
+ }
+
+ const { id: outboundPaymentId } = relatedObject;
+
+ const outboundPayment = await getStripeOutboundPayment(outboundPaymentId);
+
+ const stripePayoutTraceId = outboundPayment.trace_id?.value;
+
+ const updatedPayouts = await prisma.payout.updateMany({
+ where: {
+ stripePayoutId: outboundPaymentId,
+ },
+ data: {
+ status: "completed",
+ paidAt: new Date(),
+ failureReason: null,
+ ...(stripePayoutTraceId && {
+ stripePayoutTraceId: stripePayoutTraceId,
+ }),
+ },
+ });
+
+ // TODO:
+ // Send email notification
+
+ return `Updated ${updatedPayouts.count} ${pluralize("payout", updatedPayouts.count)} to completed status.`;
+}
diff --git a/apps/web/app/(ee)/api/stripe/connect/v2/webhook/outbound-payment-returned.ts b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/outbound-payment-returned.ts
new file mode 100644
index 0000000000..21520d4612
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/outbound-payment-returned.ts
@@ -0,0 +1,37 @@
+import { getStripeOutboundPayment } from "@/lib/stripe/get-stripe-outbound-payment";
+import { OUTBOUND_PAYMENT_RETURNED_REASONS } from "@/lib/stripe/stripe-v2-schemas";
+import { prisma } from "@dub/prisma";
+import { pluralize } from "@dub/utils";
+import Stripe from "stripe";
+
+export async function outboundPaymentReturned(event: Stripe.ThinEvent) {
+ const { related_object: relatedObject } = event;
+
+ if (!relatedObject) {
+ return "No related object found in event, skipping...";
+ }
+
+ const { id: outboundPaymentId } = relatedObject;
+
+ const outboundPayment = await getStripeOutboundPayment(outboundPaymentId);
+
+ const rawReturnedReason = outboundPayment.status_details?.returned?.reason;
+ const failureReason = rawReturnedReason
+ ? OUTBOUND_PAYMENT_RETURNED_REASONS[rawReturnedReason]
+ : undefined;
+
+ const updatedPayouts = await prisma.payout.updateMany({
+ where: {
+ stripePayoutId: outboundPaymentId,
+ },
+ data: {
+ status: "failed",
+ failureReason,
+ },
+ });
+
+ // TODO:
+ // Send email notification
+
+ return `Updated ${updatedPayouts.count} ${pluralize("payout", updatedPayouts.count)} to failed status.`;
+}
diff --git a/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-account-closed.ts b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-account-closed.ts
new file mode 100644
index 0000000000..ad2e947af2
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-account-closed.ts
@@ -0,0 +1,52 @@
+import { recomputePartnerPayoutState } from "@/lib/partners/api/recompute-partner-payout-state";
+
+import { prisma } from "@dub/prisma";
+import type Stripe from "stripe";
+
+export async function recipientAccountClosed(event: Stripe.ThinEvent) {
+ const { related_object: relatedObject } = event;
+
+ if (!relatedObject) {
+ return "No related object found in event, skipping...";
+ }
+
+ const { id: stripeRecipientId } = relatedObject;
+
+ const partner = await prisma.partner.findUnique({
+ where: {
+ stripeRecipientId,
+ },
+ select: {
+ id: true,
+ email: true,
+ stripeConnectId: true,
+ stripeRecipientId: true,
+ paypalEmail: true,
+ payoutsEnabledAt: true,
+ defaultPayoutMethod: true,
+ },
+ });
+
+ if (!partner) {
+ return `Partner with stripeRecipientId ${stripeRecipientId} not found, skipping...`;
+ }
+
+ const { payoutsEnabledAt, defaultPayoutMethod } =
+ await recomputePartnerPayoutState({
+ ...partner,
+ stripeRecipientId: null,
+ });
+
+ await prisma.partner.update({
+ where: {
+ id: partner.id,
+ },
+ data: {
+ stripeRecipientId: null,
+ payoutsEnabledAt,
+ defaultPayoutMethod,
+ },
+ });
+
+ return `Recipient account ${stripeRecipientId} closed, removed stripeRecipientId for partner ${partner.email} (${partner.id})`;
+}
diff --git a/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-configuration-updated.ts b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-configuration-updated.ts
new file mode 100644
index 0000000000..566d1138d2
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/recipient-configuration-updated.ts
@@ -0,0 +1,94 @@
+import { detectDuplicatePayoutMethodFraud } from "@/lib/api/fraud/detect-duplicate-payout-method-fraud";
+import { recomputePartnerPayoutState } from "@/lib/partners/api/recompute-partner-payout-state";
+import { getStripeStablecoinPayoutMethod } from "@/lib/stripe/get-stripe-recipient-payout-method";
+
+import { sendEmail } from "@dub/email";
+import ConnectedPayoutMethod from "@dub/email/templates/connected-payout-method";
+import { prisma } from "@dub/prisma";
+import Stripe from "stripe";
+
+export async function recipientConfigurationUpdated(event: Stripe.ThinEvent) {
+ const { related_object: relatedObject } = event;
+
+ if (!relatedObject) {
+ return "No related object found in event, skipping...";
+ }
+
+ const { id: stripeRecipientId } = relatedObject;
+
+ const partner = await prisma.partner.findUnique({
+ where: {
+ stripeRecipientId,
+ },
+ select: {
+ id: true,
+ email: true,
+ stripeConnectId: true,
+ stripeRecipientId: true,
+ paypalEmail: true,
+ payoutsEnabledAt: true,
+ defaultPayoutMethod: true,
+ cryptoWalletAddress: true,
+ },
+ });
+
+ if (!partner) {
+ return `Partner with stripeRecipientId ${stripeRecipientId} not found, skipping...`;
+ }
+
+ const { payoutsEnabledAt, defaultPayoutMethod } =
+ await recomputePartnerPayoutState(partner);
+
+ const stablecoinPayoutMethod =
+ await getStripeStablecoinPayoutMethod(stripeRecipientId);
+
+ const cryptoWalletAddress =
+ stablecoinPayoutMethod?.crypto_wallet?.address ?? null;
+ const cryptoWalletNetwork =
+ stablecoinPayoutMethod?.crypto_wallet?.network ?? null;
+
+ await prisma.partner.update({
+ where: {
+ id: partner.id,
+ },
+ data: {
+ payoutsEnabledAt,
+ defaultPayoutMethod,
+ cryptoWalletAddress: cryptoWalletAddress,
+ },
+ });
+
+ const maskedCryptoWalletAddress = cryptoWalletAddress
+ ? cryptoWalletAddress.length > 10
+ ? `${cryptoWalletAddress.slice(0, 6)}••••${cryptoWalletAddress.slice(-4)}`
+ : cryptoWalletAddress
+ : null;
+
+ if (
+ partner.email &&
+ cryptoWalletAddress &&
+ cryptoWalletAddress !== partner.cryptoWalletAddress
+ ) {
+ await sendEmail({
+ variant: "notifications",
+ subject: "Successfully connected payout method",
+ to: partner.email,
+ react: ConnectedPayoutMethod({
+ email: partner.email,
+ payoutMethod: {
+ type: "stablecoin",
+ wallet_address: maskedCryptoWalletAddress,
+ wallet_network: cryptoWalletNetwork,
+ },
+ }),
+ });
+ }
+
+ if (cryptoWalletAddress) {
+ await detectDuplicatePayoutMethodFraud({
+ cryptoWalletAddress: cryptoWalletAddress,
+ });
+ }
+
+ return `Updated partner ${partner.email} (${stripeRecipientId}) with payoutsEnabledAt ${payoutsEnabledAt ? "set" : "cleared"}, defaultPayoutMethod ${defaultPayoutMethod ?? "cleared"}`;
+}
diff --git a/apps/web/app/(ee)/api/stripe/connect/v2/webhook/route.ts b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/route.ts
new file mode 100644
index 0000000000..9fa388ec3d
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/connect/v2/webhook/route.ts
@@ -0,0 +1,92 @@
+import { stripe } from "@/lib/stripe";
+import { log } from "@dub/utils";
+import { logAndRespond } from "app/(ee)/api/cron/utils";
+import Stripe from "stripe";
+import { outboundPaymentFailed } from "./outbound-payment-failed";
+import { outboundPaymentPosted } from "./outbound-payment-posted";
+import { outboundPaymentReturned } from "./outbound-payment-returned";
+import { recipientAccountClosed } from "./recipient-account-closed";
+import { recipientConfigurationUpdated } from "./recipient-configuration-updated";
+
+const relevantEvents = new Set([
+ "v2.core.account.closed",
+ "v2.core.account[configuration.recipient].updated",
+ "v2.money_management.outbound_payment.posted",
+ "v2.money_management.outbound_payment.returned",
+ "v2.money_management.outbound_payment.failed",
+]);
+
+const webhookSecret = process.env.STRIPE_CONNECT_V2_WEBHOOK_SECRET;
+
+// POST /api/stripe/connect/v2/webhook – Stripe Connect Account v2 webhooks
+export const POST = async (req: Request) => {
+ const body = await req.text();
+ const signature = req.headers.get("Stripe-Signature");
+
+ if (!signature) {
+ return logAndRespond("Missing Stripe-Signature header.");
+ }
+
+ if (!webhookSecret) {
+ return logAndRespond(
+ "STRIPE_CONNECT_V2_WEBHOOK_SECRET environment variable is not set.",
+ {
+ status: 500,
+ },
+ );
+ }
+
+ let event: Stripe.ThinEvent;
+
+ try {
+ event = stripe.parseThinEvent(body, signature, webhookSecret);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+
+ return logAndRespond(`[Webhook error]: ${message}`, {
+ status: 400,
+ });
+ }
+
+ if (!relevantEvents.has(event.type)) {
+ return logAndRespond(`Unsupported event ${event.type}, skipping...`);
+ }
+
+ let response = "OK";
+ try {
+ switch (event.type) {
+ // @ts-ignore
+ case "v2.core.account.closed":
+ response = await recipientAccountClosed(event);
+ break;
+ // @ts-ignore
+ case "v2.core.account[configuration.recipient].updated":
+ response = await recipientConfigurationUpdated(event);
+ break;
+ // @ts-ignore
+ case "v2.money_management.outbound_payment.posted":
+ response = await outboundPaymentPosted(event);
+ break;
+ // @ts-ignore
+ case "v2.money_management.outbound_payment.returned":
+ response = await outboundPaymentReturned(event);
+ break;
+ // @ts-ignore
+ case "v2.money_management.outbound_payment.failed":
+ response = await outboundPaymentFailed(event);
+ break;
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ await log({
+ message: `/api/stripe/connect/v2/webhook webhook failed (${event.type}). Error: ${message}`,
+ type: "errors",
+ });
+
+ return logAndRespond(`[Webhook error]: ${message}`, {
+ status: 400,
+ });
+ }
+
+ return logAndRespond(`[${event.type}]: ${response}`);
+};
diff --git a/apps/web/app/(ee)/api/stripe/connect/webhook/account-application-deauthorized.ts b/apps/web/app/(ee)/api/stripe/connect/webhook/account-application-deauthorized.ts
index ac6bafa054..2dbab55999 100644
--- a/apps/web/app/(ee)/api/stripe/connect/webhook/account-application-deauthorized.ts
+++ b/apps/web/app/(ee)/api/stripe/connect/webhook/account-application-deauthorized.ts
@@ -1,3 +1,4 @@
+import { recomputePartnerPayoutState } from "@/lib/partners/api/recompute-partner-payout-state";
import { prisma } from "@dub/prisma";
import type Stripe from "stripe";
@@ -12,20 +13,35 @@ export async function accountApplicationDeauthorized(event: Stripe.Event) {
where: {
stripeConnectId: stripeAccount,
},
+ select: {
+ id: true,
+ email: true,
+ stripeConnectId: true,
+ stripeRecipientId: true,
+ paypalEmail: true,
+ payoutsEnabledAt: true,
+ defaultPayoutMethod: true,
+ },
});
if (!partner) {
return `Partner with stripeConnectId ${stripeAccount} not found, skipping...`;
}
+ const { payoutsEnabledAt, defaultPayoutMethod } =
+ await recomputePartnerPayoutState({
+ ...partner,
+ stripeConnectId: null,
+ });
+
await prisma.partner.update({
where: {
id: partner.id,
},
data: {
stripeConnectId: null,
- payoutsEnabledAt: null,
- payoutMethodHash: null,
+ payoutsEnabledAt,
+ defaultPayoutMethod,
},
});
diff --git a/apps/web/app/(ee)/api/stripe/connect/webhook/account-updated.ts b/apps/web/app/(ee)/api/stripe/connect/webhook/account-updated.ts
index 2a64f2c2aa..b0d58be6c4 100644
--- a/apps/web/app/(ee)/api/stripe/connect/webhook/account-updated.ts
+++ b/apps/web/app/(ee)/api/stripe/connect/webhook/account-updated.ts
@@ -1,5 +1,6 @@
import { detectDuplicatePayoutMethodFraud } from "@/lib/api/fraud/detect-duplicate-payout-method-fraud";
import { qstash } from "@/lib/cron";
+import { recomputePartnerPayoutState } from "@/lib/partners/api/recompute-partner-payout-state";
import { getPartnerBankAccount } from "@/lib/partners/get-partner-bank-account";
import { sendEmail } from "@dub/email";
import ConnectedPayoutMethod from "@dub/email/templates/connected-payout-method";
@@ -18,8 +19,7 @@ const balanceAvailableQueue = qstash.queue({
export async function accountUpdated(event: Stripe.Event) {
const account = event.data.object as Stripe.Account;
-
- const { country, payouts_enabled: payoutsEnabled, capabilities } = account;
+ const { country } = account;
const partner = await prisma.partner.findUnique({
where: {
@@ -27,9 +27,12 @@ export async function accountUpdated(event: Stripe.Event) {
},
select: {
id: true,
- stripeConnectId: true,
email: true,
+ stripeConnectId: true,
+ stripeRecipientId: true,
+ paypalEmail: true,
payoutsEnabledAt: true,
+ defaultPayoutMethod: true,
payoutMethodHash: true,
},
});
@@ -38,24 +41,29 @@ export async function accountUpdated(event: Stripe.Event) {
return `Partner with stripeConnectId ${account.id} not found, skipping...`;
}
- if (
- !payoutsEnabled ||
- !capabilities?.transfers ||
- capabilities.transfers === "inactive"
- ) {
- if (partner.payoutsEnabledAt) {
- await prisma.partner.update({
- where: {
- id: partner.id,
- },
- data: {
- payoutsEnabledAt: null,
- },
- });
- // TODO: notify partner about the change
- return `Payouts disabled, updated partner ${partner.email} (${partner.stripeConnectId}) with payoutsEnabledAt null`;
- }
- return `No change in payout status for ${partner.email} (${partner.stripeConnectId}), skipping...`;
+ const { payoutsEnabledAt, defaultPayoutMethod } =
+ await recomputePartnerPayoutState(partner);
+
+ const payoutStateChanged =
+ partner.payoutsEnabledAt !== payoutsEnabledAt ||
+ partner.defaultPayoutMethod !== defaultPayoutMethod;
+
+ if (!payoutStateChanged) {
+ return `No change in payout state for partner ${partner.email} (${partner.stripeConnectId}), skipping...`;
+ }
+
+ await prisma.partner.update({
+ where: {
+ id: partner.id,
+ },
+ data: {
+ payoutsEnabledAt,
+ defaultPayoutMethod,
+ },
+ });
+
+ if (partner.payoutsEnabledAt && !payoutsEnabledAt) {
+ return `Payouts disabled, updated partner ${partner.email} (${partner.stripeConnectId}) with payoutsEnabledAt null`;
}
const bankAccount = await getPartnerBankAccount(partner.stripeConnectId!);
@@ -89,7 +97,9 @@ export async function accountUpdated(event: Stripe.Event) {
},
}),
- detectDuplicatePayoutMethodFraud(payoutMethodHash),
+ detectDuplicatePayoutMethodFraud({
+ payoutMethodHash,
+ }),
]);
// Send confirmation email only if this is the first time connecting a bank account
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-details-sheet.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-details-sheet.tsx
index 6ce0394488..4fc898f32a 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-details-sheet.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-details-sheet.tsx
@@ -9,7 +9,7 @@ import { CommissionTypeBadge } from "@/ui/partners/commission-type-badge";
import { PayoutStatusBadges } from "@/ui/partners/payout-status-badges";
import { ConditionalLink } from "@/ui/shared/conditional-link";
import { X } from "@/ui/shared/icons";
-import { PayoutStatus } from "@dub/prisma/client";
+import { PartnerPayoutMethod, PayoutStatus } from "@dub/prisma/client";
import {
Button,
CircleArrowRight,
@@ -35,7 +35,7 @@ import {
pluralize,
} from "@dub/utils";
import { formatPeriod } from "@dub/utils/src/functions/datetime";
-import { addBusinessDays } from "date-fns";
+import { addBusinessDays, addMinutes } from "date-fns";
import Link from "next/link";
import { Dispatch, Fragment, SetStateAction, useMemo } from "react";
import useSWR from "swr";
@@ -45,8 +45,17 @@ type PayoutDetailsSheetProps = {
setIsOpen: Dispatch<SetStateAction<boolean>>;
};
+const failureTooltips: Record<PartnerPayoutMethod, string> = {
+ connect:
+ "Payout failures are usually due to invalid bank account details. Once you've [updated your account](/payouts?settings=true), the payout will be retried automatically.",
+ stablecoin:
+ "Payout failures are usually due to incorrect wallet configuration. Once you've [updated your account](/payouts?settings=true), you can retry the payout.",
+ paypal:
+ "Payout failures are usually due to incorrect PayPal account configuration. Once you've [updated your account](/payouts?settings=true), you can retry the payout.",
+};
+
function PayoutDetailsSheetContent({ payout }: PayoutDetailsSheetProps) {
- const { partner, payoutMethod } = usePartnerProfile();
+ const { partner } = usePartnerProfile();
const {
data: earnings,
@@ -143,11 +152,9 @@ function PayoutDetailsSheetContent({ payout }: PayoutDetailsSheetProps) {
value: (
<span className="text-red-600">{payout.failureReason}</span>
),
- tooltip: `Payout failures are usually due to ${payoutMethod === "paypal" ? "incorrect PayPal account configuration" : "invalid bank account details"}. Once you've [updated your account](/payouts?settings=true), ${
- payoutMethod === "paypal"
- ? "you can retry the payout"
- : "the payout will be retried automatically"
- }.`,
+ tooltip: payout.method
+ ? failureTooltips[payout.method]
+ : undefined,
},
]
: []),
@@ -201,7 +208,10 @@ function PayoutDetailsSheetContent({ payout }: PayoutDetailsSheetProps) {
{payout.traceId}
</CopyText>
),
- tooltip: `Banks can take up to 5 business days to process payouts. If you haven't received your payout${payout.paidAt ? ` by \`${formatDateTimeSmart(addBusinessDays(payout.paidAt, 5))}\`` : ""}, you can contact your bank and provide the following trace ID as reference.`,
+ tooltip:
+ payout.method === "stablecoin"
+ ? `Stablecoin payouts typically arrive within minutes. If you haven't received your payout${payout.paidAt ? ` by \`${formatDateTimeSmart(addMinutes(payout.paidAt, 60))}\`` : ""}, you can contact support and provide the following trace ID as reference.`
+ : `Banks can take up to 5 business days to process payouts. If you haven't received your payout${payout.paidAt ? ` by \`${formatDateTimeSmart(addBusinessDays(payout.paidAt, 5))}\`` : ""}, you can contact your bank and provide the following trace ID as reference.`,
},
]
: []),
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-settings-button.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-settings-button.tsx
index 9a28ba48bf..49faff7f56 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-settings-button.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-settings-button.tsx
@@ -1,17 +1,21 @@
"use client";
import { hasPermission } from "@/lib/auth/partner-users/partner-user-permissions";
+import usePartnerPayoutSettings from "@/lib/swr/use-partner-payout-settings";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
-import { ConnectPayoutButton } from "@/ui/partners/connect-payout-button";
+import { ConnectPayoutButton } from "@/ui/partners/payouts/connect-payout-button";
import { Button } from "@dub/ui";
import { usePartnerPayoutSettingsSheet } from "./partner-payout-settings-sheet";
export function PartnerPayoutSettingsButton() {
const { partner } = usePartnerProfile();
+ const { payoutMethods } = usePartnerPayoutSettings();
const { PartnerPayoutSettingsSheet, openSettings } =
usePartnerPayoutSettingsSheet();
+ const hasConnectedPayoutMethod = payoutMethods.some((m) => m.connected);
+
if (partner && !hasPermission(partner.role, "payout_settings.update")) {
return null;
}
@@ -20,7 +24,7 @@ export function PartnerPayoutSettingsButton() {
<>
<PartnerPayoutSettingsSheet />
- {!partner?.payoutsEnabledAt && (
+ {!partner?.payoutsEnabledAt && !hasConnectedPayoutMethod && (
<ConnectPayoutButton className="h-9 px-3" />
)}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-settings-sheet.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-settings-sheet.tsx
index bd6a64813d..94888062cd 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-settings-sheet.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/partner-payout-settings-sheet.tsx
@@ -3,11 +3,15 @@
import { updatePartnerPayoutSettingsAction } from "@/lib/actions/partners/update-partner-payout-settings";
import { getEffectivePayoutMode } from "@/lib/api/payouts/get-effective-payout-mode";
import { mutatePrefix } from "@/lib/swr/mutate";
+import usePartnerPayoutSettings from "@/lib/swr/use-partner-payout-settings";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
import useProgramEnrollments from "@/lib/swr/use-program-enrollments";
import { partnerPayoutSettingsSchema } from "@/lib/zod/schemas/partners";
-import { ConnectPayoutButton } from "@/ui/partners/connect-payout-button";
-import { PayoutMethodsDropdown } from "@/ui/partners/payout-methods-dropdown";
+import {
+ PAYOUT_METHODS,
+ PayoutMethodSelector,
+} from "@/ui/partners/payouts/payout-method-cards";
+import { PayoutMethodDropdown } from "@/ui/partners/payouts/payout-method-dropdown";
import {
BlurImage,
Button,
@@ -16,16 +20,11 @@ import {
useRouterStuff,
useScrollProgress,
} from "@dub/ui";
-import {
- CONNECT_SUPPORTED_COUNTRIES,
- COUNTRIES,
- OG_AVATAR_URL,
-} from "@dub/utils";
-import { COUNTRY_CURRENCY_CODES } from "@dub/utils/src";
+import { OG_AVATAR_URL } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { useForm } from "react-hook-form";
+import { useForm, type UseFormRegister } from "react-hook-form";
import TextareaAutosize from "react-textarea-autosize";
import { toast } from "sonner";
import * as z from "zod/v4";
@@ -106,9 +105,7 @@ function PartnerPayoutSettingsSheetInner() {
{
onSuccess: async () => {
toast.success("Payout settings updated successfully!");
- queryParams({
- del: "settings",
- });
+ queryParams({ del: "settings" });
mutatePrefix("/api/partner-profile");
},
onError({ error }) {
@@ -143,96 +140,10 @@ function PartnerPayoutSettingsSheetInner() {
onScroll={updateScrollProgress}
className="scrollbar-hide h-full space-y-10 overflow-y-auto bg-neutral-50 p-4 sm:p-6"
>
- <div className="divide-y divide-neutral-200">
- {/* Connected payout account */}
- <div className="space-y-3 pb-6">
- <h4 className="text-base font-semibold leading-6 text-neutral-900">
- Connected payout account
- </h4>
-
- {!partner?.payoutsEnabledAt ? (
- <ConnectPayoutButton className="h-10 rounded-lg px-4 py-2" />
- ) : (
- <PayoutMethodsDropdown />
- )}
-
- {partner?.country &&
- CONNECT_SUPPORTED_COUNTRIES.includes(partner.country) && (
- <p className="text-xs text-neutral-500">
- For compliance reasons, your payout bank account must match
- your local currency. Since you're based in{" "}
- <Link
- href="/profile"
- target="_blank"
- className="font-medium text-neutral-900 underline decoration-dotted underline-offset-2"
- >
- {COUNTRIES[partner.country]}
- </Link>{" "}
- , you will need to connect a{" "}
- <span className="font-medium text-neutral-900">
- {COUNTRY_CURRENCY_CODES[partner.country]} bank account
- </span>{" "}
- to receive payouts.{" "}
- <Link
- href="https://dub.co/help/article/receiving-payouts"
- target="_blank"
- className="font-medium text-neutral-900 underline decoration-dotted underline-offset-2"
- >
- Learn more ↗
- </Link>
- </p>
- )}
- </div>
-
- {/* Connected external accounts */}
+ <div className="space-y-8 divide-y divide-neutral-200">
+ <PayoutMethodsSection />
<ConnectedExternalAccounts />
-
- {/* Invoice details */}
- <div className="space-y-6 py-6">
- <div>
- <h4 className="text-base font-semibold leading-6 text-neutral-900">
- Invoice details (optional)
- </h4>
- <p className="text-sm font-medium text-neutral-500">
- This information is added to your payout invoices.
- </p>
- </div>
-
- <div>
- <label className="text-sm font-medium text-neutral-900">
- Business name
- </label>
- <div className="relative mt-1.5 rounded-md shadow-sm">
- <input
- className="block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
- {...register("companyName")}
- />
- </div>
- </div>
-
- <div>
- <label className="text-sm font-medium text-neutral-900">
- Business address
- </label>
- <TextareaAutosize
- className="mt-1.5 block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
- minRows={3}
- {...register("address")}
- />
- </div>
-
- <div>
- <label className="text-sm font-medium text-neutral-900">
- Business tax ID
- </label>
- <div className="relative mt-1.5 rounded-md shadow-sm">
- <input
- className="block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
- {...register("taxId")}
- />
- </div>
- </div>
- </div>
+ <InvoiceDetailsSection register={register} />
</div>
</div>
<div
@@ -266,6 +177,173 @@ function PartnerPayoutSettingsSheetInner() {
);
}
+function PayoutMethodsSectionSkeleton() {
+ return (
+ <div
+ className="flex w-full cursor-default items-center justify-between rounded-lg border border-neutral-200 bg-white p-2"
+ aria-hidden
+ >
+ <div className="flex min-w-0 items-center gap-x-2.5 pr-2">
+ <div className="size-8 shrink-0 animate-pulse rounded-lg bg-neutral-200" />
+ <div className="min-w-0">
+ <div className="h-3 w-24 animate-pulse rounded bg-neutral-200" />
+ <div className="mt-1 h-3 w-44 animate-pulse rounded bg-neutral-200" />
+ </div>
+ </div>
+ <div className="size-4 shrink-0 animate-pulse rounded bg-neutral-200" />
+ </div>
+ );
+}
+
+function PayoutMethodsSection() {
+ const { availablePayoutMethods } = usePartnerProfile();
+ const [selectedMethodId, setSelectedMethodId] = useState<string | null>(null);
+
+ const {
+ payoutMethods: payoutMethodsData,
+ isLoading: isPayoutMethodsLoading,
+ } = usePartnerPayoutSettings();
+
+ const hasConnectedAccount =
+ payoutMethodsData?.some((m) => m.connected) ?? false;
+
+ const filteredMethods = PAYOUT_METHODS.filter((m) =>
+ availablePayoutMethods.includes(m.id),
+ );
+
+ const currentMethod = selectedMethodId
+ ? filteredMethods.find((m) => m.id === selectedMethodId) ||
+ filteredMethods[0]
+ : filteredMethods[0];
+
+ const otherMethods = filteredMethods.filter(
+ (m) => m.id !== currentMethod?.id,
+ );
+
+ if (availablePayoutMethods.length === 0) {
+ return null;
+ }
+
+ // Show stablecoin as a recommended option when available but not yet connected, to encourage partners to add it
+ const showStablecoinRecommended =
+ availablePayoutMethods.includes("stablecoin") &&
+ !payoutMethodsData?.some((m) => m.type === "stablecoin" && m.connected);
+
+ return (
+ <div>
+ <h4 className="text-content-emphasis mb-3 text-base font-semibold leading-6">
+ Payout account
+ </h4>
+ {isPayoutMethodsLoading ? (
+ <PayoutMethodsSectionSkeleton />
+ ) : hasConnectedAccount ? (
+ <div className="space-y-3">
+ <PayoutMethodDropdown />
+ {showStablecoinRecommended &&
+ payoutMethodsData?.some((m) => m.type === "stablecoin") && (
+ <PayoutMethodSelector
+ payoutMethods={payoutMethodsData!.filter(
+ (m) => m.type === "stablecoin",
+ )}
+ variant="compact"
+ allowConnectWhenPayoutsEnabled
+ />
+ )}
+ </div>
+ ) : (
+ <PayoutMethodSelector
+ payoutMethods={
+ currentMethod && payoutMethodsData
+ ? payoutMethodsData.filter((m) => m.type === currentMethod.id)
+ : []
+ }
+ variant="compact"
+ actionFooter={(_setting) =>
+ otherMethods.length > 0 ? (
+ <div className="mt-1 flex justify-center">
+ {otherMethods.map((method) => (
+ <button
+ key={method.id}
+ type="button"
+ onClick={() => setSelectedMethodId(method.id)}
+ className="text-xs font-medium text-neutral-400 transition-colors hover:text-neutral-600"
+ >
+ Connect {method.title}
+ {method.recommended ? " (recommended)" : ""}
+ </button>
+ ))}
+ </div>
+ ) : null
+ }
+ />
+ )}
+ </div>
+ );
+}
+
+function InvoiceDetailsSection({
+ register,
+}: {
+ register: UseFormRegister<PartnerPayoutSettingsFormData>;
+}) {
+ return (
+ <div className="space-y-4 py-6">
+ <div>
+ <h4 className="text-base font-semibold leading-6 text-neutral-900">
+ Invoice details (optional)
+ </h4>
+ <p className="text-sm font-medium text-neutral-500">
+ This information is added to your payout invoices.
+ </p>
+ </div>
+
+ <div>
+ <label
+ htmlFor="companyName"
+ className="text-sm font-medium text-neutral-900"
+ >
+ Business name
+ </label>
+ <div className="relative mt-1.5 rounded-md shadow-sm">
+ <input
+ id="companyName"
+ className="block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ {...register("companyName")}
+ />
+ </div>
+ </div>
+
+ <div>
+ <label
+ htmlFor="address"
+ className="text-sm font-medium text-neutral-900"
+ >
+ Business address
+ </label>
+ <TextareaAutosize
+ id="address"
+ className="mt-1.5 block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ minRows={3}
+ {...register("address")}
+ />
+ </div>
+
+ <div>
+ <label htmlFor="taxId" className="text-sm font-medium text-neutral-900">
+ Business tax ID
+ </label>
+ <div className="relative mt-1.5 rounded-md shadow-sm">
+ <input
+ id="taxId"
+ className="block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ {...register("taxId")}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
function ConnectedExternalAccounts() {
const { externalPayoutEnrollments } = useExternalPayoutEnrollments();
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/payout-stats.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/payout-stats.tsx
index 3499d4c743..796d474b3a 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/payout-stats.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/payouts/payout-stats.tsx
@@ -5,6 +5,7 @@ import {
BELOW_MIN_WITHDRAWAL_FEE_CENTS,
MIN_FORCE_WITHDRAWAL_AMOUNT_CENTS,
MIN_WITHDRAWAL_AMOUNT_CENTS,
+ STABLECOIN_PAYOUT_FEE_RATE,
} from "@/lib/constants/payouts";
import usePartnerPayoutsCount from "@/lib/swr/use-partner-payouts-count";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
@@ -13,7 +14,7 @@ import { useConfirmModal } from "@/ui/modals/confirm-modal";
import { PayoutStatusBadges } from "@/ui/partners/payout-status-badges";
import { PAYOUT_STATUS_DESCRIPTIONS } from "@/ui/partners/payout-status-descriptions";
import { AlertCircleFill } from "@/ui/shared/icons";
-import { PayoutStatus } from "@dub/prisma/client";
+import { PartnerPayoutMethod, PayoutStatus } from "@dub/prisma/client";
import { Button, Tooltip } from "@dub/ui";
import { cn, currencyFormatter } from "@dub/utils";
import { HelpCircle } from "lucide-react";
@@ -112,7 +113,7 @@ function PayoutStatsCard({
}
export function PayoutStats() {
- const { payoutMethod } = usePartnerProfile();
+ const { partner } = usePartnerProfile();
const { payoutsCount, error } = usePartnerPayoutsCount<PayoutsCount[]>({
groupBy: "status",
@@ -122,8 +123,8 @@ export function PayoutStats() {
payoutsCount?.map((p) => [p.status, p]) || [],
) as Record<PayoutStatus, PayoutsCount>;
- const tooltip = payoutMethod
- ? PAYOUT_STATUS_DESCRIPTIONS[payoutMethod]
+ const tooltip = partner?.defaultPayoutMethod
+ ? PAYOUT_STATUS_DESCRIPTIONS[partner?.defaultPayoutMethod]
: undefined;
const payoutStats = [
@@ -145,7 +146,7 @@ export function PayoutStats() {
error: !!error,
},
- ...(payoutMethod === "stripe"
+ ...(["stablecoin", "connect"].includes(partner?.defaultPayoutMethod ?? "")
? [
{
label: "Processed",
@@ -206,28 +207,10 @@ export function PayoutStats() {
} = useConfirmModal({
title: "Pay out funds instantly",
description: (
- <>
- Since your total processed earnings (
- <strong className="text-black">{processedPayoutAmountInUsd}</strong>)
- are below the minimum requirement of{" "}
- <strong className="text-black">
- {currencyFormatter(MIN_WITHDRAWAL_AMOUNT_CENTS, {
- trailingZeroDisplay: "stripIfInteger",
- })}
- </strong>
- , you will be charged a fee of{" "}
- <strong className="text-black">
- {currencyFormatter(BELOW_MIN_WITHDRAWAL_FEE_CENTS)}
- </strong>{" "}
- for this payout, which means you will receive{" "}
- <strong className="text-black">
- {currencyFormatter(
- payoutStatusMap?.processed?.amount - BELOW_MIN_WITHDRAWAL_FEE_CENTS,
- { trailingZeroDisplay: "stripIfInteger" },
- )}
- </strong>
- .
- </>
+ <ForceWithdrawalModalDescription
+ defaultPayoutMethod={partner?.defaultPayoutMethod}
+ processedAmount={payoutStatusMap?.processed?.amount}
+ />
),
onConfirm: async () => {
await executeForceWithdrawal();
@@ -266,7 +249,10 @@ export function PayoutStats() {
<div
className={cn(
"hidden divide-x divide-neutral-200 overflow-hidden rounded-lg border border-neutral-200 bg-white md:grid",
- payoutMethod === "stripe" ? "md:grid-cols-5" : "md:grid-cols-3",
+ partner?.defaultPayoutMethod === "connect" ||
+ partner?.defaultPayoutMethod === "stablecoin"
+ ? "md:grid-cols-5"
+ : "md:grid-cols-3",
)}
>
{payoutStats.map((stat) => (
@@ -280,3 +266,63 @@ export function PayoutStats() {
</>
);
}
+
+function ForceWithdrawalModalDescription({
+ defaultPayoutMethod,
+ processedAmount,
+}: {
+ defaultPayoutMethod: PartnerPayoutMethod | null | undefined;
+ processedAmount: number | undefined;
+}) {
+ const processedPayoutAmountInUsd = currencyFormatter(processedAmount ?? 0, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ if (defaultPayoutMethod === "stablecoin") {
+ const finalAmount =
+ processedAmount != null
+ ? Math.floor(processedAmount * (1 - STABLECOIN_PAYOUT_FEE_RATE))
+ : 0;
+
+ return (
+ <>
+ Your processed earnings (
+ <strong className="text-black">{processedPayoutAmountInUsd}</strong>)
+ will be sent to your crypto wallet. A{" "}
+ {STABLECOIN_PAYOUT_FEE_RATE * 100}% fee applies, so you will
+ receive{" "}
+ <strong className="text-black">
+ {currencyFormatter(finalAmount, {
+ trailingZeroDisplay: "stripIfInteger",
+ })}
+ </strong>
+ .
+ </>
+ );
+ }
+
+ return (
+ <>
+ Since your total processed earnings (
+ <strong className="text-black">{processedPayoutAmountInUsd}</strong>) are
+ below the minimum requirement of{" "}
+ <strong className="text-black">
+ {currencyFormatter(MIN_WITHDRAWAL_AMOUNT_CENTS, {
+ trailingZeroDisplay: "stripIfInteger",
+ })}
+ </strong>
+ , you will be charged a fee of{" "}
+ <strong className="text-black">
+ {currencyFormatter(BELOW_MIN_WITHDRAWAL_FEE_CENTS)}
+ </strong>{" "}
+ for this payout, which means you will receive{" "}
+ <strong className="text-black">
+ {currencyFormatter(
+ (processedAmount ?? 0) - BELOW_MIN_WITHDRAWAL_FEE_CENTS,
+ { trailingZeroDisplay: "stripIfInteger" },
+ )}
+ </strong>
+ .
+ </>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/page.tsx b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/page.tsx
index b14305bd38..97a229156a 100644
--- a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/page.tsx
@@ -1,20 +1,21 @@
import { getSession } from "@/lib/auth";
+import { getPartnerPayoutMethods } from "@/lib/payouts/api/get-partner-payout-methods";
+import { PayoutMethodSelector } from "@/ui/partners/payouts/payout-method-cards";
import { prisma } from "@dub/prisma";
-import {
- CONNECT_SUPPORTED_COUNTRIES,
- PAYPAL_SUPPORTED_COUNTRIES,
-} from "@dub/utils";
+import Link from "next/link";
import { redirect } from "next/navigation";
import { Suspense } from "react";
-import { PayoutProvider } from "./payout-provider";
export default function OnboardingVerificationPage() {
return (
- <div className="relative mx-auto my-10 flex w-full max-w-[416px] flex-col items-center text-center md:mt-6">
- <h1 className="animate-slide-up-fade text-content-emphasis text-lg font-medium [--offset:8px] [animation-delay:250ms] [animation-duration:1s] [animation-fill-mode:both]">
+ <div className="relative mx-auto my-10 flex w-full max-w-[600px] flex-col items-center px-4 text-center sm:px-6 md:mt-6">
+ <h1 className="animate-slide-up-fade text-content-emphasis text-xl font-semibold [--offset:8px] [animation-delay:250ms] [animation-duration:1s] [animation-fill-mode:both]">
Payout information
</h1>
- <div className="animate-slide-up-fade relative mt-8 w-full [--offset:10px] [animation-delay:500ms] [animation-duration:1s] [animation-fill-mode:both]">
+ <p className="animate-slide-up-fade mt-1 text-base font-medium text-neutral-500 [--offset:8px] [animation-delay:250ms] [animation-duration:1s] [animation-fill-mode:both]">
+ Connect your preferred payout method to receive payments.
+ </p>
+ <div className="animate-slide-up-fade relative mt-12 w-full [--offset:10px] [animation-delay:500ms] [animation-duration:1s] [animation-fill-mode:both]">
<Suspense fallback={<PayoutSkeleton />}>
<PayoutRSC />
</Suspense>
@@ -52,24 +53,43 @@ function PayoutSkeleton() {
async function PayoutRSC() {
const { user } = await getSession();
+
const partner = await prisma.partner.findUnique({
where: {
email: user.email,
},
+ select: {
+ id: true,
+ country: true,
+ stripeConnectId: true,
+ stripeRecipientId: true,
+ paypalEmail: true,
+ defaultPayoutMethod: true,
+ },
});
+
if (!partner?.country) {
redirect("/");
}
- const provider = CONNECT_SUPPORTED_COUNTRIES.includes(partner.country)
- ? "stripe"
- : PAYPAL_SUPPORTED_COUNTRIES.includes(partner.country)
- ? "paypal"
- : null;
+ const payoutMethods = await getPartnerPayoutMethods(partner);
- if (!provider) {
+ if (payoutMethods.length === 0) {
redirect("/");
}
- return <PayoutProvider provider={provider} />;
+ return (
+ <>
+ <PayoutMethodSelector
+ payoutMethods={payoutMethods}
+ allowConnectWhenPayoutsEnabled
+ />
+ <Link
+ href="/programs"
+ className="mt-6 block text-center text-sm font-semibold text-neutral-800 transition-colors hover:text-neutral-950"
+ >
+ I'll complete this later
+ </Link>
+ </>
+ );
}
diff --git a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/payout-provider.tsx b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/payout-provider.tsx
index 408d21f789..98eabb17b9 100644
--- a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/payout-provider.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/payouts/payout-provider.tsx
@@ -1,7 +1,7 @@
"use client";
import { getValidInternalRedirectPath } from "@/lib/middleware/utils/is-valid-internal-redirect";
-import { ConnectPayoutButton } from "@/ui/partners/connect-payout-button";
+import { ConnectPayoutButton } from "@/ui/partners/payouts/connect-payout-button";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
diff --git a/apps/web/lib/actions/partners/force-withdrawal.ts b/apps/web/lib/actions/partners/force-withdrawal.ts
index 44363a2557..063c45a44e 100644
--- a/apps/web/lib/actions/partners/force-withdrawal.ts
+++ b/apps/web/lib/actions/partners/force-withdrawal.ts
@@ -1,8 +1,9 @@
"use server";
import { throwIfNoPermission } from "@/lib/auth/partner-users/throw-if-no-permission";
+import { createStablecoinPayout } from "@/lib/partners/create-stablecoin-payout";
import { createStripeTransfer } from "@/lib/partners/create-stripe-transfer";
-import { ratelimit } from "@/lib/upstash";
+import { redis } from "@/lib/upstash";
import { authPartnerActionClient } from "../safe-action";
// Force a withdrawal for a partner (even if the total amount is below the minimum withdrawal amount)
@@ -15,19 +16,45 @@ export const forceWithdrawalAction = authPartnerActionClient.action(
permission: "payout_settings.update",
});
- const { success } = await ratelimit(10, "24 h").limit(
- `force-withdrawal:${partner.id}`,
- );
+ if (!partner.defaultPayoutMethod) {
+ throw new Error(
+ "No default payout method found. Please contact support to set one.",
+ );
+ }
- if (!success) {
+ if (!["connect", "stablecoin"].includes(partner.defaultPayoutMethod)) {
throw new Error(
- "You've reached the maximum number of retry attempts for the past 24 hours. Please wait and try again later.",
+ "Invalid default payout method found. Please contact support to set one.",
);
}
- await createStripeTransfer({
- partnerId: partner.id,
- forceWithdrawal: true,
- });
+ const lockKey = `force-withdrawal:lock:${partner.id}`;
+ const acquired = await redis.set(lockKey, "1", { nx: true, ex: 60 });
+
+ if (!acquired) {
+ throw new Error(
+ "A withdrawal is already in progress. Please wait for it to complete.",
+ );
+ }
+
+ try {
+ if (partner.defaultPayoutMethod === "connect") {
+ await createStripeTransfer({
+ partnerId: partner.id,
+ forceWithdrawal: true,
+ });
+ return;
+ }
+
+ if (partner.defaultPayoutMethod === "stablecoin") {
+ await createStablecoinPayout({
+ partnerId: partner.id,
+ forceWithdrawal: true,
+ });
+ return;
+ }
+ } finally {
+ await redis.del(lockKey);
+ }
},
);
diff --git a/apps/web/lib/actions/partners/generate-paypal-oauth-url.ts b/apps/web/lib/actions/partners/generate-paypal-oauth-url.ts
index e9cf9eca54..305279911f 100644
--- a/apps/web/lib/actions/partners/generate-paypal-oauth-url.ts
+++ b/apps/web/lib/actions/partners/generate-paypal-oauth-url.ts
@@ -1,8 +1,10 @@
"use server";
import { throwIfNoPermission } from "@/lib/auth/partner-users/throw-if-no-permission";
+import { getPayoutMethodsForCountry } from "@/lib/partners/get-payout-methods-for-country";
import { paypalOAuthProvider } from "@/lib/paypal/oauth";
-import { COUNTRIES, PAYPAL_SUPPORTED_COUNTRIES } from "@dub/utils";
+import { PartnerPayoutMethod } from "@dub/prisma/client";
+import { COUNTRIES } from "@dub/utils";
import { authPartnerActionClient } from "../safe-action";
export const generatePaypalOAuthUrl = authPartnerActionClient.action(
@@ -20,7 +22,11 @@ export const generatePaypalOAuthUrl = authPartnerActionClient.action(
);
}
- if (!PAYPAL_SUPPORTED_COUNTRIES.includes(partner.country)) {
+ const availablePayoutMethods = getPayoutMethodsForCountry({
+ country: partner.country,
+ });
+
+ if (!availablePayoutMethods.includes(PartnerPayoutMethod.paypal)) {
throw new Error(
`Your current country (${COUNTRIES[partner.country]}) is not supported for PayPal payouts. Please go to partners.dub.co/settings to update your country, or contact support.`,
);
diff --git a/apps/web/lib/actions/partners/generate-stripe-account-link.ts b/apps/web/lib/actions/partners/generate-stripe-account-link.ts
index cd5cfa794a..78e5973d2a 100644
--- a/apps/web/lib/actions/partners/generate-stripe-account-link.ts
+++ b/apps/web/lib/actions/partners/generate-stripe-account-link.ts
@@ -1,14 +1,12 @@
"use server";
import { throwIfNoPermission } from "@/lib/auth/partner-users/throw-if-no-permission";
+import { getPayoutMethodsForCountry } from "@/lib/partners/get-payout-methods-for-country";
import { stripe } from "@/lib/stripe";
import { createConnectedAccount } from "@/lib/stripe/create-connected-account";
import { prisma } from "@dub/prisma";
-import {
- CONNECT_SUPPORTED_COUNTRIES,
- COUNTRIES,
- PARTNERS_DOMAIN,
-} from "@dub/utils";
+import { PartnerPayoutMethod } from "@dub/prisma/client";
+import { COUNTRIES, PARTNERS_DOMAIN } from "@dub/utils";
import { authPartnerActionClient } from "../safe-action";
export const generateStripeAccountLink = authPartnerActionClient.action(
@@ -34,12 +32,16 @@ export const generateStripeAccountLink = authPartnerActionClient.action(
);
}
- // guard against unsupported countries
- if (!CONNECT_SUPPORTED_COUNTRIES.includes(partner.country)) {
+ const availablePayoutMethods = getPayoutMethodsForCountry({
+ country: partner.country,
+ });
+
+ if (!availablePayoutMethods.includes(PartnerPayoutMethod.connect)) {
throw new Error(
`Your current country (${COUNTRIES[partner.country]}) is not supported for Stripe payouts. Please go to partners.dub.co/settings to update your country, or contact support.`,
);
}
+
// create a new account
const connectedAccount = await createConnectedAccount({
country: partner.country,
@@ -55,15 +57,24 @@ export const generateStripeAccountLink = authPartnerActionClient.action(
});
}
- const { url } = partner.payoutsEnabledAt
- ? await stripe.accounts.createLoginLink(partner.stripeConnectId)
- : await stripe.accountLinks.create({
- account: partner.stripeConnectId,
- refresh_url: `${PARTNERS_DOMAIN}/payouts`,
- return_url: `${PARTNERS_DOMAIN}/payouts`,
- type: "account_onboarding",
- collect: "eventually_due",
- });
+ if (!partner.stripeConnectId) {
+ throw new Error(
+ "Failed to create a new Stripe connect account. Please contact support.",
+ );
+ }
+
+ const account = await stripe.accounts.retrieve(partner.stripeConnectId);
+
+ const { url } =
+ account.details_submitted === true
+ ? await stripe.accounts.createLoginLink(partner.stripeConnectId)
+ : await stripe.accountLinks.create({
+ account: partner.stripeConnectId,
+ refresh_url: `${PARTNERS_DOMAIN}/payouts`,
+ return_url: `${PARTNERS_DOMAIN}/payouts`,
+ type: "account_onboarding",
+ collect: "eventually_due",
+ });
return {
url,
diff --git a/apps/web/lib/actions/partners/generate-stripe-recipient-account-link.ts b/apps/web/lib/actions/partners/generate-stripe-recipient-account-link.ts
new file mode 100644
index 0000000000..698c011501
--- /dev/null
+++ b/apps/web/lib/actions/partners/generate-stripe-recipient-account-link.ts
@@ -0,0 +1,84 @@
+"use server";
+
+import { throwIfNoPermission } from "@/lib/auth/partner-users/throw-if-no-permission";
+import { getPartnerFeatureFlags } from "@/lib/edge-config";
+import { getPayoutMethodsForCountry } from "@/lib/partners/get-payout-methods-for-country";
+import { createStripeRecipientAccount } from "@/lib/stripe/create-stripe-recipient-account";
+import { createStripeRecipientAccountLink } from "@/lib/stripe/create-stripe-recipient-account-link";
+import { prisma } from "@dub/prisma";
+import { PartnerPayoutMethod } from "@dub/prisma/client";
+import { COUNTRIES } from "@dub/utils";
+import { authPartnerActionClient } from "../safe-action";
+
+export const generateStripeRecipientAccountLink =
+ authPartnerActionClient.action(async ({ ctx }) => {
+ const { partner, partnerUser } = ctx;
+
+ throwIfNoPermission({
+ role: partnerUser.role,
+ permission: "payout_settings.update",
+ });
+
+ const featureFlags = await getPartnerFeatureFlags(partner.id);
+
+ if (!featureFlags.stablecoin) {
+ throw new Error(
+ "Stablecoin payouts are not enabled for your account yet. Please contact support.",
+ );
+ }
+
+ let useCase: "account_onboarding" | "account_update" = "account_update";
+
+ if (!partner.stripeRecipientId) {
+ if (!partner.email) {
+ throw new Error(
+ "Partner does not have a valid email. Please contact support to update your email.",
+ );
+ }
+
+ if (!partner.country) {
+ throw new Error(
+ "You haven't set your country yet. Please go to partners.dub.co/settings to set your country.",
+ );
+ }
+
+ const availablePayoutMethods = getPayoutMethodsForCountry({
+ country: partner.country,
+ });
+
+ if (!availablePayoutMethods.includes(PartnerPayoutMethod.stablecoin)) {
+ throw new Error(
+ `Your current country (${COUNTRIES[partner.country]}) is not supported for Stablecoin payouts. Please go to partners.dub.co/settings to update your country, or contact support.`,
+ );
+ }
+
+ const recipientAccount = await createStripeRecipientAccount({
+ name: partner.name,
+ email: partner.email,
+ country: partner.country,
+ profileType: partner.profileType,
+ });
+
+ partner.stripeRecipientId = recipientAccount.id;
+
+ await prisma.partner.update({
+ where: {
+ id: partner.id,
+ },
+ data: {
+ stripeRecipientId: recipientAccount.id,
+ },
+ });
+
+ useCase = "account_onboarding";
+ }
+
+ const accountLink = await createStripeRecipientAccountLink({
+ stripeRecipientId: partner.stripeRecipientId!,
+ useCase,
+ });
+
+ return {
+ url: accountLink.url,
+ };
+ });
diff --git a/apps/web/lib/actions/partners/update-partner-payout-settings.ts b/apps/web/lib/actions/partners/update-partner-payout-settings.ts
index fb4ebdcda8..538f31b097 100644
--- a/apps/web/lib/actions/partners/update-partner-payout-settings.ts
+++ b/apps/web/lib/actions/partners/update-partner-payout-settings.ts
@@ -2,7 +2,6 @@
import { throwIfNoPermission } from "@/lib/auth/partner-users/throw-if-no-permission";
import { prisma } from "@dub/prisma";
-import { Prisma } from "@dub/prisma/client";
import { partnerPayoutSettingsSchema } from "../../zod/schemas/partners";
import { authPartnerActionClient } from "../safe-action";
@@ -18,10 +17,7 @@ export const updatePartnerPayoutSettingsAction = authPartnerActionClient
permission: "payout_settings.update",
});
- const invoiceSettings = {
- address: address || undefined,
- taxId: taxId || undefined,
- } as Prisma.JsonObject;
+ const hasInvoiceUpdate = address !== undefined || taxId !== undefined;
await prisma.partner.update({
where: {
@@ -29,7 +25,16 @@ export const updatePartnerPayoutSettingsAction = authPartnerActionClient
},
data: {
companyName,
- invoiceSettings,
+ ...(hasInvoiceUpdate && {
+ invoiceSettings: {
+ ...(address !== undefined && {
+ address: address || null,
+ }),
+ ...(taxId !== undefined && {
+ taxId: taxId || null,
+ }),
+ },
+ }),
},
});
});
diff --git a/apps/web/lib/api/activity-log/track-reward-activity-log.ts b/apps/web/lib/api/activity-log/track-reward-activity-log.ts
index 8c03fae79d..7ec069c752 100644
--- a/apps/web/lib/api/activity-log/track-reward-activity-log.ts
+++ b/apps/web/lib/api/activity-log/track-reward-activity-log.ts
@@ -1,15 +1,11 @@
import { serializeReward } from "@/lib/api/partners/serialize-reward";
import type { RewardConditions, RewardProps } from "@/lib/types";
import { REWARD_EVENT_TO_RESOURCE_TYPE } from "@/lib/zod/schemas/activity-log";
-import { rewardConditionsSchema } from "@/lib/zod/schemas/rewards";
import type { Reward } from "@dub/prisma/client";
-import type { z } from "zod/v4";
import { getResourceDiff } from "./get-resource-diff";
import type { TrackActivityLogInput } from "./track-activity-log";
import { trackActivityLog } from "./track-activity-log";
-type RewardConditionModifier = z.infer<typeof rewardConditionsSchema>;
-
interface TrackRewardActivityLogParams
extends Omit<
TrackActivityLogInput,
@@ -32,10 +28,7 @@ function toRewardActivitySnapshot(reward: RewardProps) {
};
}
-function modifierEquals(
- a: RewardConditionModifier,
- b: RewardConditionModifier,
-): boolean {
+function modifierEquals(a: RewardConditions, b: RewardConditions): boolean {
return JSON.stringify(a) === JSON.stringify(b);
}
diff --git a/apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts b/apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts
index 1b5ca7e5c8..0be2d21bd9 100644
--- a/apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts
+++ b/apps/web/lib/api/fraud/detect-duplicate-payout-method-fraud.ts
@@ -4,19 +4,25 @@ import { prisma } from "@dub/prisma";
import { FraudRuleType, ProgramEnrollment } from "@dub/prisma/client";
import { createFraudEvents } from "./create-fraud-events";
+type DetectDuplicatePayoutMethodFraudOptions =
+ | { payoutMethodHash: string; cryptoWalletAddress?: never }
+ | { cryptoWalletAddress: string; payoutMethodHash?: never };
+
// Check for duplicate payout methods: if multiple partners share the same payout method hash,
// create fraud events for all their active program enrollments to flag potential fraud
-export async function detectDuplicatePayoutMethodFraud(
- payoutMethodHash: string,
-): Promise<void> {
- if (!payoutMethodHash) {
+export async function detectDuplicatePayoutMethodFraud({
+ payoutMethodHash,
+ cryptoWalletAddress,
+}: DetectDuplicatePayoutMethodFraudOptions) {
+ if (!payoutMethodHash && !cryptoWalletAddress) {
return;
}
const programEnrollments = await prisma.programEnrollment.findMany({
where: {
partner: {
- payoutMethodHash,
+ ...(payoutMethodHash ? { payoutMethodHash } : {}),
+ ...(cryptoWalletAddress ? { cryptoWalletAddress } : {}),
},
},
select: {
@@ -35,7 +41,9 @@ export async function detectDuplicatePayoutMethodFraud(
if (!map.has(e.programId)) {
map.set(e.programId, []);
}
+
map.get(e.programId)!.push({ partnerId: e.partnerId, status: e.status });
+
return map;
}, new Map<string, Pick<ProgramEnrollment, "partnerId" | "status">[]>());
@@ -64,7 +72,8 @@ export async function detectDuplicatePayoutMethodFraud(
partnerId: sourcePartner.partnerId,
type: FraudRuleType.partnerDuplicatePayoutMethod,
metadata: {
- payoutMethodHash,
+ ...(payoutMethodHash ? { payoutMethodHash } : {}),
+ ...(cryptoWalletAddress ? { cryptoWalletAddress } : {}),
duplicatePartnerId: enrolledPartner.partnerId,
},
});
diff --git a/apps/web/lib/api/fraud/utils.ts b/apps/web/lib/api/fraud/utils.ts
index 6e31bf1f6a..ec977849d1 100644
--- a/apps/web/lib/api/fraud/utils.ts
+++ b/apps/web/lib/api/fraud/utils.ts
@@ -120,6 +120,7 @@ export function sanitizeFraudEventMetadata(
delete sanitized.duplicatePartnerId;
delete sanitized.payoutMethodHash;
+ delete sanitized.cryptoWalletAddress;
return Object.keys(sanitized).length > 0 ? sanitized : undefined;
}
diff --git a/apps/web/lib/constants/payouts.ts b/apps/web/lib/constants/payouts.ts
index b935922e3b..8273ac1b8c 100644
--- a/apps/web/lib/constants/payouts.ts
+++ b/apps/web/lib/constants/payouts.ts
@@ -11,6 +11,7 @@ export const ALLOWED_MIN_PAYOUT_AMOUNTS = [0, 1000, 2000, 5000, 10000];
export const INVOICE_MIN_PAYOUT_AMOUNT_CENTS = 1000; // $10
export const MIN_WITHDRAWAL_AMOUNT_CENTS = 1000; // $10
export const BELOW_MIN_WITHDRAWAL_FEE_CENTS = 50; // $0.50
+export const STABLECOIN_PAYOUT_FEE_RATE = 0.01; // 1%
export const MIN_FORCE_WITHDRAWAL_AMOUNT_CENTS = 100; // $1 (doesn't make sense to force a withdrawal for less than $1)
export const ELIGIBLE_PAYOUTS_MAX_PAGE_SIZE = 500;
diff --git a/apps/web/lib/edge-config/get-partner-feature-flags.ts b/apps/web/lib/edge-config/get-partner-feature-flags.ts
index 93ca991a6c..aa00441d7a 100644
--- a/apps/web/lib/edge-config/get-partner-feature-flags.ts
+++ b/apps/web/lib/edge-config/get-partner-feature-flags.ts
@@ -1,11 +1,12 @@
import { get } from "@vercel/edge-config";
import { PartnerBetaFeatures } from "../types";
-type PartnerBetaFeaturesRecord = Record<PartnerBetaFeatures, string[]>;
+type PartnerBetaFeaturesRecord = Partial<Record<PartnerBetaFeatures, string[]>>;
export const getPartnerFeatureFlags = async (partnerId: string) => {
const partnerFeatures: Record<PartnerBetaFeatures, boolean> = {
postbacks: false,
+ stablecoin: false,
};
// Return all features as true if edge config is not available
@@ -27,9 +28,10 @@ export const getPartnerFeatureFlags = async (partnerId: string) => {
return partnerFeatures;
}
- // It should be in the format of { postbacks: ["pn_1", "pn_2"] }
+ // It should be in the format of
+ // { postbacks: ["pn_1", "pn_2"], stablecoin: ["pn_1"] }
for (const [featureFlag, partnerIds] of Object.entries(betaFeatures)) {
- if (partnerIds.includes(partnerId)) {
+ if (partnerIds?.includes(partnerId)) {
partnerFeatures[featureFlag] = true;
}
}
diff --git a/apps/web/lib/partners/api/recompute-partner-payout-state.ts b/apps/web/lib/partners/api/recompute-partner-payout-state.ts
new file mode 100644
index 0000000000..979d29781b
--- /dev/null
+++ b/apps/web/lib/partners/api/recompute-partner-payout-state.ts
@@ -0,0 +1,86 @@
+import { stripe } from "@/lib/stripe";
+import { getStripeRecipientAccount } from "@/lib/stripe/get-stripe-recipient-account";
+import { Partner, PartnerPayoutMethod } from "@dub/prisma/client";
+import { prettyPrint } from "@dub/utils";
+
+const PAYOUT_METHOD_PRIORITY: PartnerPayoutMethod[] = [
+ PartnerPayoutMethod.stablecoin,
+ PartnerPayoutMethod.connect,
+ PartnerPayoutMethod.paypal,
+];
+
+/**
+ * Computes payoutsEnabledAt and defaultPayoutMethod based on currently active
+ * payout methods. The default is always selected from priority order:
+ * stablecoin > connect > paypal.
+ */
+export async function recomputePartnerPayoutState(
+ partner: Pick<
+ Partner,
+ | "stripeConnectId"
+ | "stripeRecipientId"
+ | "paypalEmail"
+ | "payoutsEnabledAt"
+ | "defaultPayoutMethod"
+ >,
+) {
+ const [connectAccount, stablecoinAccount] = await Promise.all([
+ partner.stripeConnectId
+ ? stripe.accounts.retrieve(partner.stripeConnectId)
+ : Promise.resolve(null),
+
+ partner.stripeRecipientId
+ ? getStripeRecipientAccount(partner.stripeRecipientId)
+ : Promise.resolve(null),
+ ]);
+
+ const connectActive = Boolean(
+ connectAccount?.payouts_enabled === true &&
+ connectAccount?.capabilities?.transfers === "active",
+ );
+
+ const stablecoinActive = Boolean(
+ stablecoinAccount?.configuration?.recipient?.capabilities?.crypto_wallets
+ ?.status === "active",
+ );
+
+ const paypalActive = Boolean(partner.paypalEmail);
+
+ const activePayoutMethods = PAYOUT_METHOD_PRIORITY.filter((method) => {
+ switch (method) {
+ case PartnerPayoutMethod.stablecoin:
+ return stablecoinActive;
+ case PartnerPayoutMethod.connect:
+ return connectActive;
+ case PartnerPayoutMethod.paypal:
+ return paypalActive;
+ default:
+ return false;
+ }
+ });
+
+ const defaultPayoutMethod = activePayoutMethods[0] ?? null;
+ let payoutsEnabledAt: Date | null = null;
+
+ if (defaultPayoutMethod) {
+ payoutsEnabledAt = partner.payoutsEnabledAt ?? new Date();
+ } else {
+ payoutsEnabledAt = null;
+ }
+
+ console.log(
+ "[recomputePartnerPayoutState]",
+ prettyPrint({
+ connectActive,
+ stablecoinActive,
+ paypalActive,
+ payoutsEnabledAt,
+ defaultPayoutMethod,
+ }),
+ );
+
+ return {
+ payoutsEnabledAt,
+ defaultPayoutMethod,
+ };
+}
diff --git a/apps/web/lib/partners/create-stablecoin-payout.ts b/apps/web/lib/partners/create-stablecoin-payout.ts
new file mode 100644
index 0000000000..ebfdce327d
--- /dev/null
+++ b/apps/web/lib/partners/create-stablecoin-payout.ts
@@ -0,0 +1,267 @@
+import { sendEmail } from "@dub/email";
+import PartnerPayoutProcessed from "@dub/email/templates/partner-payout-processed";
+import { prisma } from "@dub/prisma";
+import { PartnerPayoutMethod, Prisma } from "@dub/prisma/client";
+import { currencyFormatter, prettyPrint } from "@dub/utils";
+import { STABLECOIN_PAYOUT_FEE_RATE } from "../constants/payouts";
+import { createPayoutsIdempotencyKey } from "../payouts/api/create-payouts-idempotency-key";
+import { markPayoutsAsProcessed } from "../payouts/api/mark-payouts-as-processed";
+import { createStripeOutboundPayment } from "../stripe/create-stripe-outbound-payment";
+import { fundFinancialAccount } from "../stripe/fund-financial-account";
+import { getStripeRecipientAccount } from "../stripe/get-stripe-recipient-account";
+
+interface CreateStablecoinPayoutParams {
+ partnerId: string;
+ invoiceId?: string;
+ forceWithdrawal?: boolean;
+}
+
+export const createStablecoinPayout = async ({
+ partnerId,
+ invoiceId,
+ forceWithdrawal = false,
+}: CreateStablecoinPayoutParams) => {
+ const partner = await prisma.partner.findUniqueOrThrow({
+ where: {
+ id: partnerId,
+ },
+ select: {
+ id: true,
+ email: true,
+ stripeRecipientId: true,
+ payoutsEnabledAt: true,
+ },
+ });
+
+ if (!partner.payoutsEnabledAt) {
+ console.warn(`Partner ${partner.email} does not have payouts enabled.`);
+ return;
+ }
+
+ if (!partner.stripeRecipientId) {
+ console.warn(
+ `Partner ${partner.email} does not have a stripeRecipientId set.`,
+ );
+ return;
+ }
+
+ const commonInclude: Prisma.PayoutInclude = {
+ program: {
+ select: {
+ name: true,
+ logo: true,
+ },
+ },
+ };
+
+ const [previouslyProcessedPayouts, currentInvoicePayouts] = await Promise.all(
+ [
+ prisma.payout.findMany({
+ where: {
+ partnerId: partner.id,
+ status: "processed",
+ stripePayoutId: null,
+ method: {
+ in: [PartnerPayoutMethod.stablecoin, PartnerPayoutMethod.connect],
+ },
+ },
+ orderBy: {
+ id: "asc",
+ },
+ include: commonInclude,
+ }),
+
+ invoiceId
+ ? prisma.payout.findMany({
+ where: {
+ partnerId: partner.id,
+ status: "processing",
+ stripePayoutId: null,
+ method: "stablecoin",
+ invoiceId,
+ },
+ orderBy: {
+ id: "asc",
+ },
+ include: commonInclude,
+ })
+ : Promise.resolve([]),
+ ],
+ );
+
+ if (forceWithdrawal && previouslyProcessedPayouts.length === 0) {
+ throw new Error(
+ "No previously processed payouts found. Please try again or contact support.",
+ );
+ }
+
+ const allPayouts = [...previouslyProcessedPayouts, ...currentInvoicePayouts];
+
+ if (allPayouts.length === 0) {
+ console.warn(`No available payouts found for partner ${partner.email}.`);
+ return;
+ }
+
+ const idempotencyKey = createPayoutsIdempotencyKey({
+ partnerId: partner.id,
+ invoiceId,
+ payoutIds: allPayouts.map((p) => p.id),
+ });
+
+ let totalTransferableAmount = allPayouts.reduce(
+ (acc, payout) => acc + payout.amount,
+ 0,
+ );
+
+ if (totalTransferableAmount <= 0) {
+ console.warn(
+ `Total transferable amount for partner ${partner.email} is less than 0.`,
+ );
+ return;
+ }
+
+ // Stablecoin payouts incur an outbound fee that is passed along to partners.
+ totalTransferableAmount -=
+ totalTransferableAmount * STABLECOIN_PAYOUT_FEE_RATE;
+
+ // Round down to the nearest integer
+ totalTransferableAmount = Math.floor(totalTransferableAmount);
+
+ if (totalTransferableAmount <= 0) {
+ console.warn(
+ `Total transferable amount for partner ${partner.email} is less than 0.`,
+ );
+ return;
+ }
+
+ const stripeRecipientAccount = await getStripeRecipientAccount(
+ partner.stripeRecipientId,
+ );
+
+ // Stripe recipient account is closed
+ if (stripeRecipientAccount.closed) {
+ await prisma.partner.update({
+ where: {
+ id: partner.id,
+ },
+ data: {
+ stripeRecipientId: null,
+ payoutsEnabledAt: null,
+ },
+ });
+
+ await markPayoutsAsProcessed(allPayouts);
+
+ console.warn(
+ `Stripe recipient account for partner ${partner.email} is closed.`,
+ );
+ return;
+ }
+
+ // Stripe recipient account does not have crypto wallet capabilities
+ if (
+ stripeRecipientAccount.configuration?.recipient?.capabilities
+ ?.crypto_wallets?.status !== "active"
+ ) {
+ await prisma.partner.update({
+ where: {
+ id: partner.id,
+ },
+ data: {
+ payoutsEnabledAt: null,
+ },
+ });
+
+ await markPayoutsAsProcessed(allPayouts);
+
+ throw new Error(
+ `Stripe recipient account for partner ${partner.email} does not have crypto wallet capabilities.`,
+ );
+ }
+
+ const allPayoutsProgramNames = [
+ ...new Set(allPayouts.map((p) => p.program.name)),
+ ];
+
+ // Find the total amount to transfer to Dub's FA
+ let amountToTransferToFA = 0;
+
+ for (const payout of previouslyProcessedPayouts) {
+ if (payout.method === "connect") {
+ amountToTransferToFA += payout.amount;
+ }
+ }
+
+ if (amountToTransferToFA > 0) {
+ await fundFinancialAccount({
+ amount: amountToTransferToFA,
+ idempotencyKey,
+ });
+ }
+
+ const outboundPayment = await createStripeOutboundPayment({
+ stripeRecipientId: partner.stripeRecipientId,
+ amount: totalTransferableAmount,
+ description: `Dub Partners payout (${allPayoutsProgramNames.join(", ")})`,
+ idempotencyKey,
+ });
+
+ if (!outboundPayment.id) {
+ console.error(
+ `Failed to create outbound payment for partner ${partner.email}.`,
+ );
+ return;
+ }
+
+ await prisma.$transaction([
+ prisma.payout.updateMany({
+ where: {
+ id: {
+ in: allPayouts.map((p) => p.id),
+ },
+ },
+ data: {
+ stripePayoutId: outboundPayment.id,
+ status: "sent",
+ paidAt: new Date(),
+ method: "stablecoin",
+ },
+ }),
+
+ prisma.commission.updateMany({
+ where: {
+ payoutId: {
+ in: allPayouts.map((p) => p.id),
+ },
+ },
+ data: {
+ status: "paid",
+ },
+ }),
+ ]);
+
+ if (!partner.email) {
+ console.warn(
+ `Partner ${partner.email} does not have an email address to send the payout email to.`,
+ );
+ return;
+ }
+
+ const payout = allPayouts[0];
+
+ const emailResponse = await sendEmail({
+ variant: "notifications",
+ to: partner.email,
+ subject: `You've received a ${currencyFormatter(payout.amount)} payout from ${payout.program.name}`,
+ react: PartnerPayoutProcessed({
+ email: partner.email,
+ program: payout.program,
+ payout,
+ }),
+ });
+
+ console.log(
+ `Payout processed email sent to partner ${partner.email}:`,
+ prettyPrint(emailResponse),
+ );
+};
diff --git a/apps/web/lib/partners/create-stripe-transfer.ts b/apps/web/lib/partners/create-stripe-transfer.ts
index 8f1c48a834..a56605a906 100644
--- a/apps/web/lib/partners/create-stripe-transfer.ts
+++ b/apps/web/lib/partners/create-stripe-transfer.ts
@@ -7,17 +7,10 @@ import { stripe } from "@/lib/stripe";
import { sendEmail } from "@dub/email";
import PartnerPayoutProcessed from "@dub/email/templates/partner-payout-processed";
import { prisma } from "@dub/prisma";
-import { Payout, Prisma } from "@dub/prisma/client";
+import { Prisma } from "@dub/prisma/client";
import { currencyFormatter, pluralize } from "@dub/utils";
-
-export type PayoutWithProgramName = Pick<
- Payout,
- "id" | "amount" | "invoiceId"
-> & {
- program: {
- name: string;
- };
-};
+import { createPayoutsIdempotencyKey } from "../payouts/api/create-payouts-idempotency-key";
+import { markPayoutsAsProcessed } from "../payouts/api/mark-payouts-as-processed";
export const createStripeTransfer = async ({
partnerId,
@@ -65,6 +58,10 @@ export const createStripeTransfer = async ({
partnerId: partner.id,
status: "processed",
stripeTransferId: null,
+ method: "connect",
+ },
+ orderBy: {
+ id: "asc",
},
include: commonInclude,
}),
@@ -73,6 +70,10 @@ export const createStripeTransfer = async ({
partnerId: partner.id,
invoiceId,
status: "processing",
+ method: "connect",
+ },
+ orderBy: {
+ id: "asc",
},
include: commonInclude,
}),
@@ -104,7 +105,7 @@ export const createStripeTransfer = async ({
withdrawalFee = BELOW_MIN_WITHDRAWAL_FEE_CENTS;
// else, we will just update current invoice payouts to "processed" status
} else {
- await updateCurrentInvoicePayoutsToProcessed(currentInvoicePayouts);
+ await markPayoutsAsProcessed(currentInvoicePayouts);
console.log(
`Total processed payouts (${currencyFormatter(totalTransferableAmount)}) for partner ${partner.id} are below ${currencyFormatter(MIN_WITHDRAWAL_AMOUNT_CENTS)}, skipping...`,
@@ -147,16 +148,22 @@ export const createStripeTransfer = async ({
});
console.log(`Updated partner ${partner.email} with payoutsEnabledAt null`);
- await updateCurrentInvoicePayoutsToProcessed(currentInvoicePayouts);
+ await markPayoutsAsProcessed(currentInvoicePayouts);
throw new Error(
`Partner's Stripe Express account (${partner.stripeConnectId}) is not configured to receive transfers`,
);
}
- // will be used for transfer_group and idempotencyKey
+ // will be used for transfer_group
const finalPayoutInvoiceId = allPayouts[allPayouts.length - 1].invoiceId;
+ const idempotencyKey = createPayoutsIdempotencyKey({
+ partnerId: partner.id,
+ invoiceId,
+ payoutIds: allPayouts.map((p) => p.id),
+ });
+
// Create a transfer for the partner combined payouts and update it as sent
const transfer = await stripe.transfers.create(
{
@@ -175,7 +182,7 @@ export const createStripeTransfer = async ({
}),
},
{
- idempotencyKey: `${finalPayoutInvoiceId}-${partner.id}`,
+ idempotencyKey,
},
);
@@ -197,6 +204,7 @@ export const createStripeTransfer = async ({
stripeTransferId: transfer.id,
status: "sent",
paidAt: new Date(),
+ method: "connect",
},
}),
@@ -222,7 +230,6 @@ export const createStripeTransfer = async ({
email: partner.email,
program: payout.program,
payout,
- variant: "stripe",
}),
});
@@ -231,24 +238,3 @@ export const createStripeTransfer = async ({
return transfer;
};
-
-const updateCurrentInvoicePayoutsToProcessed = async (
- currentInvoicePayouts: Pick<Payout, "id">[],
-) => {
- if (currentInvoicePayouts.length > 0) {
- const res = await prisma.payout.updateMany({
- where: {
- id: {
- in: currentInvoicePayouts.map((p) => p.id),
- },
- },
- data: {
- status: "processed",
- paidAt: new Date(),
- },
- });
- console.log(
- `Updated ${res.count} payouts in current invoice to "processed" status`,
- );
- }
-};
diff --git a/apps/web/lib/partners/get-payout-methods-for-country.ts b/apps/web/lib/partners/get-payout-methods-for-country.ts
new file mode 100644
index 0000000000..2657dd9b7f
--- /dev/null
+++ b/apps/web/lib/partners/get-payout-methods-for-country.ts
@@ -0,0 +1,34 @@
+import { PartnerPayoutMethod } from "@dub/prisma/client";
+import {
+ CONNECT_SUPPORTED_COUNTRIES,
+ PAYPAL_SUPPORTED_COUNTRIES,
+ STABLECOIN_SUPPORTED_COUNTRIES,
+} from "@dub/utils";
+
+export function getPayoutMethodsForCountry({
+ country,
+ stablecoinEnabled = true,
+}: {
+ country: string | null | undefined;
+ stablecoinEnabled?: boolean;
+}) {
+ if (!country) {
+ return [];
+ }
+
+ const methods: PartnerPayoutMethod[] = [];
+
+ if (stablecoinEnabled && STABLECOIN_SUPPORTED_COUNTRIES.includes(country)) {
+ methods.push("stablecoin");
+ }
+
+ if (CONNECT_SUPPORTED_COUNTRIES.includes(country)) {
+ methods.push("connect");
+ }
+
+ if (PAYPAL_SUPPORTED_COUNTRIES.includes(country)) {
+ methods.push("paypal");
+ }
+
+ return methods;
+}
diff --git a/apps/web/lib/payouts/api/create-payouts-idempotency-key.ts b/apps/web/lib/payouts/api/create-payouts-idempotency-key.ts
new file mode 100644
index 0000000000..4ba0e82efc
--- /dev/null
+++ b/apps/web/lib/payouts/api/create-payouts-idempotency-key.ts
@@ -0,0 +1,27 @@
+import { createHash } from "crypto";
+
+interface CreatePayoutsIdempotencyKeyParams {
+ partnerId: string;
+ invoiceId: string | null | undefined;
+ payoutIds: string[];
+}
+
+// Create deterministic idempotency key for payouts
+export function createPayoutsIdempotencyKey({
+ partnerId,
+ invoiceId,
+ payoutIds,
+}: CreatePayoutsIdempotencyKeyParams): string {
+ if (invoiceId) {
+ return `payouts-${invoiceId}-${partnerId}`;
+ }
+
+ const sortedPayoutIds = [...payoutIds].sort((a, b) => a.localeCompare(b));
+
+ const hash = createHash("sha256")
+ .update(sortedPayoutIds.join(","))
+ .digest("hex")
+ .slice(0, 32);
+
+ return `payouts-${partnerId}-${hash}`;
+}
diff --git a/apps/web/lib/payouts/api/get-partner-payout-methods.ts b/apps/web/lib/payouts/api/get-partner-payout-methods.ts
new file mode 100644
index 0000000000..0f902524ec
--- /dev/null
+++ b/apps/web/lib/payouts/api/get-partner-payout-methods.ts
@@ -0,0 +1,102 @@
+import { getPartnerFeatureFlags } from "@/lib/edge-config/get-partner-feature-flags";
+import { getPartnerBankAccount } from "@/lib/partners/get-partner-bank-account";
+import { getPayoutMethodsForCountry } from "@/lib/partners/get-payout-methods-for-country";
+import { getStripeStablecoinPayoutMethod } from "@/lib/stripe/get-stripe-recipient-payout-method";
+import { PartnerPayoutMethodSetting } from "@/lib/types";
+import { Partner, PartnerPayoutMethod } from "@dub/prisma/client";
+
+export async function getPartnerPayoutMethods(
+ partner: Pick<
+ Partner,
+ | "id"
+ | "country"
+ | "stripeConnectId"
+ | "stripeRecipientId"
+ | "paypalEmail"
+ | "defaultPayoutMethod"
+ >,
+) {
+ const featureFlags = await getPartnerFeatureFlags(partner.id);
+
+ const availablePayoutMethods = getPayoutMethodsForCountry({
+ country: partner.country,
+ stablecoinEnabled: featureFlags.stablecoin,
+ });
+
+ const [bankAccount, stripePayoutMethod] = await Promise.all([
+ partner.stripeConnectId
+ ? getPartnerBankAccount(partner.stripeConnectId)
+ : Promise.resolve(null),
+
+ partner.stripeRecipientId
+ ? getStripeStablecoinPayoutMethod(partner.stripeRecipientId)
+ : Promise.resolve(null),
+ ]);
+
+ let payoutMethods: PartnerPayoutMethodSetting[] = [];
+
+ // Stablecoin
+ if (availablePayoutMethods.includes(PartnerPayoutMethod.stablecoin)) {
+ let identifier: string | null = null;
+
+ if (stripePayoutMethod?.crypto_wallet) {
+ const { address } = stripePayoutMethod.crypto_wallet;
+
+ identifier =
+ address.length > 10
+ ? `${address.slice(0, 6)}••••${address.slice(-4)}`
+ : address;
+ }
+
+ payoutMethods.push({
+ type: PartnerPayoutMethod.stablecoin,
+ label: "Stablecoin",
+ default: partner.defaultPayoutMethod === PartnerPayoutMethod.stablecoin,
+ connected: Boolean(stripePayoutMethod?.crypto_wallet),
+ identifier,
+ });
+ }
+
+ // Connect
+ if (availablePayoutMethods.includes(PartnerPayoutMethod.connect)) {
+ let identifier: string | null = null;
+
+ if (bankAccount) {
+ identifier = bankAccount.routing_number
+ ? `${bankAccount.routing_number}••••${bankAccount.last4}`
+ : `••••${bankAccount.last4}`;
+ }
+
+ payoutMethods.push({
+ type: PartnerPayoutMethod.connect,
+ label: "Bank Account",
+ default: partner.defaultPayoutMethod === PartnerPayoutMethod.connect,
+ connected: Boolean(bankAccount),
+ identifier,
+ });
+ }
+
+ // PayPal
+ if (availablePayoutMethods.includes(PartnerPayoutMethod.paypal)) {
+ payoutMethods.push({
+ type: PartnerPayoutMethod.paypal,
+ label: "PayPal",
+ default: partner.defaultPayoutMethod === PartnerPayoutMethod.paypal,
+ connected: Boolean(partner.paypalEmail),
+ identifier: partner.paypalEmail ?? null,
+ });
+ }
+
+ const stablecoinConnected = payoutMethods.some(
+ (m) => m.type === PartnerPayoutMethod.stablecoin && m.connected,
+ );
+
+ // When Stablecoin is connected: Show only Stablecoin + any other method that is already connected
+ if (stablecoinConnected) {
+ payoutMethods = payoutMethods.filter(
+ (m) => m.type === PartnerPayoutMethod.stablecoin || m.connected,
+ );
+ }
+
+ return payoutMethods;
+}
diff --git a/apps/web/lib/payouts/api/mark-payouts-as-processed.ts b/apps/web/lib/payouts/api/mark-payouts-as-processed.ts
new file mode 100644
index 0000000000..721cf15cb8
--- /dev/null
+++ b/apps/web/lib/payouts/api/mark-payouts-as-processed.ts
@@ -0,0 +1,20 @@
+import { prisma } from "@dub/prisma";
+import { Payout } from "@dub/prisma/client";
+
+export const markPayoutsAsProcessed = async (payouts: Pick<Payout, "id">[]) => {
+ if (payouts.length === 0) {
+ return;
+ }
+
+ await prisma.payout.updateMany({
+ where: {
+ id: {
+ in: payouts.map((p) => p.id),
+ },
+ },
+ data: {
+ status: "processed",
+ paidAt: new Date(),
+ },
+ });
+};
diff --git a/apps/web/lib/stripe/create-stripe-outbound-payment.ts b/apps/web/lib/stripe/create-stripe-outbound-payment.ts
new file mode 100644
index 0000000000..06a5baafb3
--- /dev/null
+++ b/apps/web/lib/stripe/create-stripe-outbound-payment.ts
@@ -0,0 +1,53 @@
+import { STRIPE_API_VERSION, stripeV2Fetch } from "./stripe-v2-client";
+
+export interface CreateStripeOutboundPaymentParams {
+ stripeRecipientId: string;
+ amount: number;
+ description: string;
+ idempotencyKey: string;
+}
+
+export async function createStripeOutboundPayment({
+ stripeRecipientId,
+ amount,
+ description,
+ idempotencyKey,
+}: CreateStripeOutboundPaymentParams) {
+ const financialAccountId = process.env.STRIPE_FINANCIAL_ACCOUNT_ID;
+
+ if (!financialAccountId) {
+ throw new Error("STRIPE_FINANCIAL_ACCOUNT_ID is not configured.");
+ }
+
+ const { data, error } = await stripeV2Fetch(
+ "/v2/money_management/outbound_payments",
+ {
+ headers: {
+ Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
+ "Stripe-Version": STRIPE_API_VERSION,
+ "Idempotency-Key": idempotencyKey,
+ },
+ body: {
+ from: {
+ financial_account: financialAccountId,
+ currency: "usd",
+ },
+ to: {
+ recipient: stripeRecipientId,
+ currency: "usdc",
+ },
+ amount: {
+ value: amount,
+ currency: "usd",
+ },
+ description,
+ },
+ },
+ );
+
+ if (error) {
+ throw new Error(error.message);
+ }
+
+ return data;
+}
diff --git a/apps/web/lib/stripe/create-stripe-recipient-account-link.ts b/apps/web/lib/stripe/create-stripe-recipient-account-link.ts
new file mode 100644
index 0000000000..8a2d0f7878
--- /dev/null
+++ b/apps/web/lib/stripe/create-stripe-recipient-account-link.ts
@@ -0,0 +1,35 @@
+import { PARTNERS_DOMAIN } from "@dub/utils";
+import { stripeV2Fetch } from "./stripe-v2-client";
+
+interface CreateStripeRecipientAccountLinkParams {
+ stripeRecipientId: string;
+ useCase: "account_onboarding" | "account_update";
+}
+
+export async function createStripeRecipientAccountLink({
+ stripeRecipientId,
+ useCase,
+}: CreateStripeRecipientAccountLinkParams) {
+ const { data, error } = await stripeV2Fetch("/v2/core/account_links", {
+ body: {
+ account: stripeRecipientId,
+ use_case: {
+ type: useCase,
+ [useCase]: {
+ configurations: ["recipient"],
+ return_url: `${PARTNERS_DOMAIN}/payouts`,
+ refresh_url: `${PARTNERS_DOMAIN}/payouts`,
+ collection_options: {
+ fields: "eventually_due",
+ },
+ },
+ },
+ },
+ });
+
+ if (error) {
+ throw new Error(error.message);
+ }
+
+ return data;
+}
diff --git a/apps/web/lib/stripe/create-stripe-recipient-account.ts b/apps/web/lib/stripe/create-stripe-recipient-account.ts
new file mode 100644
index 0000000000..d6c3931f18
--- /dev/null
+++ b/apps/web/lib/stripe/create-stripe-recipient-account.ts
@@ -0,0 +1,42 @@
+import type { Partner } from "@dub/prisma/client";
+import { stripeV2Fetch } from "./stripe-v2-client";
+
+interface CreateStripeRecipientAccountParams
+ extends Pick<Partner, "name" | "profileType"> {
+ email: NonNullable<Partner["email"]>;
+ country: NonNullable<Partner["country"]>;
+}
+
+export async function createStripeRecipientAccount({
+ name,
+ email,
+ country,
+ profileType,
+}: CreateStripeRecipientAccountParams) {
+ const { data, error } = await stripeV2Fetch("/v2/core/accounts", {
+ body: {
+ contact_email: email,
+ display_name: name,
+ identity: {
+ country: country.toLowerCase(),
+ entity_type: profileType,
+ },
+ configuration: {
+ recipient: {
+ capabilities: {
+ crypto_wallets: {
+ requested: true,
+ },
+ },
+ },
+ },
+ include: ["configuration.recipient"],
+ },
+ });
+
+ if (error) {
+ throw new Error(error.message);
+ }
+
+ return data;
+}
diff --git a/apps/web/lib/stripe/fund-financial-account.ts b/apps/web/lib/stripe/fund-financial-account.ts
new file mode 100644
index 0000000000..9349af7acf
--- /dev/null
+++ b/apps/web/lib/stripe/fund-financial-account.ts
@@ -0,0 +1,50 @@
+import { currencyFormatter, prettyPrint } from "@dub/utils";
+import { STRIPE_API_VERSION, stripeV2Fetch } from "./stripe-v2-client";
+
+const financialAccountId = process.env.STRIPE_FINANCIAL_ACCOUNT_ID;
+
+interface FundFinancialAccountParams {
+ amount: number;
+ idempotencyKey: string;
+}
+
+// Fund the Dub's financial account for Global payouts
+export async function fundFinancialAccount({
+ amount,
+ idempotencyKey,
+}: FundFinancialAccountParams) {
+ if (amount <= 0) {
+ throw new Error("Amount must be greater than 0.");
+ }
+
+ if (!financialAccountId) {
+ throw new Error("STRIPE_FINANCIAL_ACCOUNT_ID is not configured.");
+ }
+
+ const { data, error } = await stripeV2Fetch("/v1/payouts", {
+ body: {
+ amount,
+ currency: "usd",
+ payout_method: financialAccountId,
+ },
+ headers: {
+ Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
+ "Stripe-Version": STRIPE_API_VERSION,
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Idempotency-Key": idempotencyKey,
+ },
+ });
+
+ if (error) {
+ throw new Error(`Failed to fund Dub's financial account: ${error.message}`);
+ }
+
+ console.log(
+ `Transferred ${currencyFormatter(amount)} to Dub's financial account`,
+ prettyPrint(data),
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+
+ return data;
+}
diff --git a/apps/web/lib/stripe/get-stripe-outbound-payment.ts b/apps/web/lib/stripe/get-stripe-outbound-payment.ts
new file mode 100644
index 0000000000..506211963a
--- /dev/null
+++ b/apps/web/lib/stripe/get-stripe-outbound-payment.ts
@@ -0,0 +1,18 @@
+import { stripeV2Fetch } from "./stripe-v2-client";
+
+export async function getStripeOutboundPayment(outboundPaymentId: string) {
+ const { data, error } = await stripeV2Fetch(
+ "/v2/money_management/outbound_payments/:id",
+ {
+ params: {
+ id: outboundPaymentId,
+ },
+ },
+ );
+
+ if (error) {
+ throw new Error(error.message);
+ }
+
+ return data;
+}
diff --git a/apps/web/lib/stripe/get-stripe-recipient-account.ts b/apps/web/lib/stripe/get-stripe-recipient-account.ts
new file mode 100644
index 0000000000..b230fed6e2
--- /dev/null
+++ b/apps/web/lib/stripe/get-stripe-recipient-account.ts
@@ -0,0 +1,18 @@
+import { stripeV2Fetch } from "./stripe-v2-client";
+
+export async function getStripeRecipientAccount(stripeRecipientId: string) {
+ const { data, error } = await stripeV2Fetch("/v2/core/accounts/:id", {
+ params: {
+ id: stripeRecipientId,
+ },
+ query: {
+ "include[0]": "configuration.recipient",
+ },
+ });
+
+ if (error) {
+ throw new Error(error.message);
+ }
+
+ return data;
+}
diff --git a/apps/web/lib/stripe/get-stripe-recipient-payout-method.ts b/apps/web/lib/stripe/get-stripe-recipient-payout-method.ts
new file mode 100644
index 0000000000..a2a82a4218
--- /dev/null
+++ b/apps/web/lib/stripe/get-stripe-recipient-payout-method.ts
@@ -0,0 +1,25 @@
+import { STRIPE_API_VERSION, stripeV2Fetch } from "./stripe-v2-client";
+
+export async function getStripeStablecoinPayoutMethod(
+ stripeRecipientId: string,
+) {
+ const { data, error } = await stripeV2Fetch(
+ "/v2/money_management/payout_methods",
+ {
+ query: {
+ limit: 1,
+ },
+ headers: {
+ Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
+ "Stripe-Version": STRIPE_API_VERSION,
+ "Stripe-Context": stripeRecipientId,
+ },
+ },
+ );
+
+ if (error) {
+ throw new Error(error.message);
+ }
+
+ return data.data?.[0] ?? null;
+}
diff --git a/apps/web/lib/stripe/stripe-v2-client.ts b/apps/web/lib/stripe/stripe-v2-client.ts
new file mode 100644
index 0000000000..d812a3eecb
--- /dev/null
+++ b/apps/web/lib/stripe/stripe-v2-client.ts
@@ -0,0 +1,86 @@
+import { createFetch, createSchema } from "@better-fetch/fetch";
+import { prettyPrint } from "@dub/utils";
+import {
+ createAccountLinkInputSchema,
+ createAccountLinkOutputSchema,
+ createOutboundPaymentInputSchema,
+ createPayoutInputSchema,
+ createPayoutOutputSchema,
+ createRecipientAccountInputSchema,
+ createRecipientAccountOutputSchema,
+ listPayoutMethodsOutputSchema,
+ listPayoutMethodsQuerySchema,
+ outboundPaymentSchema,
+ retrieveAccountOutputSchema,
+ retrieveAccountQuerySchema,
+} from "./stripe-v2-schemas";
+
+export const STRIPE_API_VERSION = "2025-09-30.preview";
+
+// TODO:
+// Replace this with new Stripe SDK when it becomes stable
+
+export const stripeV2Fetch = createFetch({
+ baseURL: "https://api.stripe.com",
+ headers: {
+ Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
+ "Stripe-Version": STRIPE_API_VERSION,
+ },
+ schema: createSchema(
+ {
+ "/v2/core/accounts": {
+ method: "post",
+ input: createRecipientAccountInputSchema,
+ output: createRecipientAccountOutputSchema,
+ },
+ "/v2/core/accounts/:id": {
+ method: "get",
+ query: retrieveAccountQuerySchema,
+ output: retrieveAccountOutputSchema,
+ },
+ "/v2/core/account_links": {
+ method: "post",
+ input: createAccountLinkInputSchema,
+ output: createAccountLinkOutputSchema,
+ },
+ "/v2/money_management/outbound_payments": {
+ method: "post",
+ input: createOutboundPaymentInputSchema,
+ output: outboundPaymentSchema,
+ },
+ "/v2/money_management/outbound_payments/:id": {
+ method: "get",
+ output: outboundPaymentSchema,
+ },
+ "/v2/money_management/payout_methods": {
+ method: "get",
+ query: listPayoutMethodsQuerySchema,
+ output: listPayoutMethodsOutputSchema,
+ },
+ // payout_method is a preview feature and not currently available in our current SDK version
+ "/v1/payouts": {
+ method: "post",
+ input: createPayoutInputSchema,
+ output: createPayoutOutputSchema,
+ },
+ },
+ {
+ strict: true,
+ },
+ ),
+ onError: ({ error }) => {
+ console.error("[Stripe V2] Error", prettyPrint(error));
+ },
+ // onResponse: async (context) => {
+ // const cloned = context.response.clone();
+
+ // try {
+ // const raw = await cloned.json();
+ // console.log("[Stripe V2] Raw response", prettyPrint(raw));
+ // } catch {
+ // //
+ // }
+
+ // return context.response;
+ // },
+});
diff --git a/apps/web/lib/stripe/stripe-v2-schemas.ts b/apps/web/lib/stripe/stripe-v2-schemas.ts
new file mode 100644
index 0000000000..19a283c8e4
--- /dev/null
+++ b/apps/web/lib/stripe/stripe-v2-schemas.ts
@@ -0,0 +1,224 @@
+import * as z from "zod/v4";
+
+export const createRecipientAccountInputSchema = z.object({
+ contact_email: z.string(),
+ display_name: z.string(),
+ identity: z.object({
+ country: z.string(),
+ entity_type: z.enum(["individual", "company"]),
+ }),
+ configuration: z.object({
+ recipient: z.object({
+ capabilities: z.object({
+ crypto_wallets: z.object({
+ requested: z.literal(true),
+ }),
+ }),
+ }),
+ }),
+ include: z.array(z.string()),
+});
+
+export const createRecipientAccountOutputSchema = z.object({
+ id: z.string(),
+ livemode: z.boolean(),
+});
+
+export const createAccountLinkInputSchema = z.object({
+ account: z.string(),
+ use_case: z.object({
+ type: z.enum(["account_onboarding", "account_update"]),
+ account_onboarding: z
+ .object({
+ configurations: z.array(z.literal("recipient")),
+ refresh_url: z.url(),
+ return_url: z.url().optional(),
+ collection_options: z.object({
+ fields: z.enum(["currently_due", "eventually_due"]),
+ }),
+ })
+ .optional(),
+ account_update: z
+ .object({
+ configurations: z.array(z.literal("recipient")),
+ refresh_url: z.url(),
+ return_url: z.url().optional(),
+ })
+ .optional(),
+ }),
+});
+
+export const createAccountLinkOutputSchema = z.object({
+ url: z.string(),
+ expires_at: z.union([z.number(), z.string()]),
+});
+
+export const createOutboundPaymentInputSchema = z.object({
+ amount: z.object({
+ currency: z.string(),
+ value: z.number(),
+ }),
+ from: z.object({
+ financial_account: z.string(),
+ currency: z.string(),
+ }),
+ to: z.object({
+ recipient: z.string(),
+ payout_method: z.string().optional(),
+ currency: z.string().optional(),
+ }),
+ description: z.string().optional(),
+ metadata: z.record(z.string(), z.string()).optional(),
+ delivery_options: z
+ .object({
+ bank_account: z.enum(["automatic", "local", "wire"]).optional(),
+ })
+ .optional(),
+ recipient_notification: z
+ .object({
+ setting: z.enum(["configured", "none"]),
+ })
+ .optional(),
+});
+
+export const outboundPaymentSchema = z.object({
+ id: z.string(),
+ object: z.literal("v2.money_management.outbound_payment"),
+ amount: z.object({
+ currency: z.string(),
+ value: z.number(),
+ }),
+ status: z.enum(["processing", "failed", "posted", "returned", "canceled"]),
+ from: z.object({
+ financial_account: z.string(),
+ debited: z
+ .object({
+ currency: z.string(),
+ value: z.number(),
+ })
+ .optional(),
+ }),
+ to: z.object({
+ recipient: z.string(),
+ payout_method: z.string().optional(),
+ credited: z
+ .object({
+ currency: z.string(),
+ value: z.number(),
+ })
+ .optional(),
+ }),
+ cancelable: z.boolean(),
+ description: z.string().nullable().optional(),
+ created: z.string(),
+ status_details: z
+ .object({
+ failed: z
+ .object({
+ reason: z.string().default("unknown_failure"),
+ })
+ .optional(),
+ returned: z
+ .object({
+ reason: z.string().default("unknown_failure"),
+ })
+ .optional(),
+ })
+ .nullable()
+ .optional(),
+ trace_id: z
+ .object({
+ value: z.string(),
+ })
+ .nullable()
+ .optional(),
+});
+
+export const listPayoutMethodsQuerySchema = z.object({
+ limit: z.number(),
+});
+
+export const listPayoutMethodsOutputSchema = z.object({
+ data: z.array(
+ z.object({
+ id: z.string(),
+ object: z.string(),
+ type: z.enum(["crypto_wallet"]),
+ crypto_wallet: z
+ .object({
+ address: z.string(),
+ archived: z.boolean(),
+ network: z.string(),
+ })
+ .nullable(),
+ }),
+ ),
+});
+
+export const retrieveAccountQuerySchema = z.object({
+ "include[0]": z.string(),
+});
+
+export const retrieveAccountOutputSchema = z.object({
+ id: z.string(),
+ closed: z.boolean().nullable().optional(),
+ configuration: z
+ .object({
+ recipient: z
+ .object({
+ applied: z.boolean(),
+ capabilities: z.record(z.string(), z.any()).nullable(),
+ })
+ .nullable(),
+ })
+ .nullable(),
+});
+
+export const createPayoutInputSchema = z.object({
+ amount: z.number(),
+ currency: z.literal("usd"),
+ payout_method: z.string(),
+});
+
+export const createPayoutOutputSchema = z.object({
+ id: z.string(),
+ amount: z.number(),
+ currency: z.string(),
+ status: z.enum(["pending", "paid", "in_transit", "canceled", "failed"]),
+});
+
+export const OUTBOUND_PAYMENT_FAILURE_REASONS = {
+ payout_method_declined:
+ "The outbound flow to this payout method was declined.",
+ payout_method_does_not_exist:
+ "Payout method used for this outbound flow does not exist.",
+ payout_method_expired: "Payout method used for this outbound flow expired.",
+ payout_method_unsupported:
+ "Payout method used for this outbound flow is unsupported.",
+ payout_method_usage_frequency_limit_exceeded:
+ "The usage frequency limit for this payout method was exceeded.",
+ unknown_failure: "Unknown failure",
+} as const;
+
+export const OUTBOUND_PAYMENT_RETURNED_REASONS = {
+ payout_method_canceled_by_customer:
+ "The outbound flow to this payout method was canceled by customer.",
+ payout_method_closed:
+ "Payout method account used for this outbound flow is closed.",
+ payout_method_currency_unsupported:
+ "Currency is not supported by the payout method account.",
+ payout_method_does_not_exist:
+ "Payout method account used for this outbound flow does not exist.",
+ payout_method_holder_address_incorrect:
+ "Address on the payout method account is incorrect.",
+ payout_method_holder_details_incorrect:
+ "The payout method account holder's details are incorrect.",
+ payout_method_holder_name_incorrect:
+ "Name on the payout method account is incorrect.",
+ payout_method_invalid_account_number:
+ "The outbound flow to this payout method has an invalid account number.",
+ payout_method_restricted:
+ "Payout method account used for this outbound flow is restricted.",
+ recalled: "The outbound flow to this payout method was recalled.",
+ unknown_failure: "Unknown failure",
+} as const;
diff --git a/apps/web/lib/swr/use-partner-payout-settings.ts b/apps/web/lib/swr/use-partner-payout-settings.ts
new file mode 100644
index 0000000000..48b6620cd0
--- /dev/null
+++ b/apps/web/lib/swr/use-partner-payout-settings.ts
@@ -0,0 +1,29 @@
+import type { PartnerPayoutMethodSetting } from "@/lib/types";
+import { fetcher } from "@dub/utils";
+import { useSession } from "next-auth/react";
+import useSWR from "swr";
+
+export default function usePartnerPayoutSettings() {
+ const { data: session } = useSession();
+ const partnerId = session?.user?.["defaultPartnerId"];
+
+ const {
+ data: payoutMethods = [],
+ error,
+ isLoading,
+ mutate,
+ } = useSWR<PartnerPayoutMethodSetting[]>(
+ partnerId ? "/api/partner-profile/payouts/settings" : null,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ payoutMethods,
+ error,
+ isLoading,
+ mutate,
+ };
+}
diff --git a/apps/web/lib/swr/use-partner-profile.ts b/apps/web/lib/swr/use-partner-profile.ts
index 96c4511c4d..e4ab64022a 100644
--- a/apps/web/lib/swr/use-partner-profile.ts
+++ b/apps/web/lib/swr/use-partner-profile.ts
@@ -1,10 +1,7 @@
-import {
- CONNECT_SUPPORTED_COUNTRIES,
- fetcher,
- PAYPAL_SUPPORTED_COUNTRIES,
-} from "@dub/utils";
+import { fetcher } from "@dub/utils";
import { useSession } from "next-auth/react";
import useSWR from "swr";
+import { getPayoutMethodsForCountry } from "../partners/get-payout-methods-for-country";
import { PartnerBetaFeatures, PartnerProps } from "../types";
interface PartnerProfile extends PartnerProps {
@@ -35,18 +32,17 @@ export default function usePartnerProfile() {
)
: undefined;
+ const availablePayoutMethods = getPayoutMethodsForCountry({
+ country: partner?.country,
+ stablecoinEnabled: Boolean(partner?.featureFlags?.stablecoin),
+ });
+
return {
partner,
platformsVerified,
- payoutMethod: partner?.country
- ? PAYPAL_SUPPORTED_COUNTRIES.includes(partner.country)
- ? "paypal"
- : CONNECT_SUPPORTED_COUNTRIES.includes(partner.country)
- ? "stripe"
- : undefined
- : undefined,
error,
loading: status === "loading" || isLoading,
mutate,
+ availablePayoutMethods,
};
}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index cd9f26f094..dbe514e1c3 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -1,6 +1,7 @@
import {
PartnerBountySchema,
PartnerEarningsSchema,
+ partnerPayoutMethodSchema,
PartnerProfileCustomerSchema,
PartnerProfileLinkSchema,
partnerReferralsCountByStatusSchema,
@@ -15,6 +16,7 @@ import {
FraudRuleType,
Link,
PartnerGroup,
+ PartnerPayoutMethod,
PartnerReferral,
PartnerRole,
PayoutStatus,
@@ -245,7 +247,7 @@ export type PlanProps = (typeof plans)[number];
export type BetaFeatures = "noDubLink" | "analyticsSettingsSiteVisitTracking";
-export type PartnerBetaFeatures = "postbacks";
+export type PartnerBetaFeatures = "postbacks" | "stablecoin";
export interface WorkspaceProps extends Project {
logo: string | null;
@@ -491,6 +493,7 @@ export type PartnerProps = z.infer<typeof PartnerSchema> & {
role: PartnerRole;
userId: string;
platforms: PartnerPlatformProps[];
+ defaultPayoutMethod: PartnerPayoutMethod | null;
};
export type PartnerRewindProps = z.infer<typeof PartnerRewindSchema>;
@@ -502,6 +505,10 @@ export type PartnerProfileCustomerProps = z.infer<
export type PartnerProfileLinkProps = z.infer<typeof PartnerProfileLinkSchema>;
+export type PartnerPayoutMethodSetting = z.infer<
+ typeof partnerPayoutMethodSchema
+>;
+
export type PartnerProfileReferralsCountByStatus = z.infer<
typeof partnerReferralsCountByStatusSchema
>;
diff --git a/apps/web/lib/webhook/sample-events/payout-confirmed.json b/apps/web/lib/webhook/sample-events/payout-confirmed.json
index d082d2dff1..a1c11be09c 100644
--- a/apps/web/lib/webhook/sample-events/payout-confirmed.json
+++ b/apps/web/lib/webhook/sample-events/payout-confirmed.json
@@ -4,6 +4,7 @@
"amount": 5000,
"currency": "USD",
"status": "completed",
+ "method": null,
"description": "Dub Partners payout (Acme)",
"periodStart": "2025-10-22T15:49:33.343Z",
"periodEnd": "2025-10-31T18:29:59.999Z",
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index 7d8ca9f038..0ad18dfbfc 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -5,6 +5,7 @@ import {
import { PARTNER_CUSTOMERS_MAX_PAGE_SIZE } from "@/lib/constants/partner-profile";
import {
CommissionType,
+ PartnerPayoutMethod,
PartnerProfileType,
PartnerRole,
ProgramEnrollmentStatus,
@@ -207,6 +208,14 @@ export const partnerProfileChangeHistoryLogSchema = z.array(
]),
);
+export const partnerPayoutMethodSchema = z.object({
+ type: z.enum(PartnerPayoutMethod),
+ label: z.string(),
+ default: z.boolean(),
+ connected: z.boolean(),
+ identifier: z.string().nullable(),
+});
+
export const partnerProfilePayoutsQuerySchema = payoutsQuerySchema.extend({
programId: z.string().optional(),
sortBy: payoutsQuerySchema.shape.sortBy.default("initiatedAt"),
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index 82ac0027ab..f4b6f7d45c 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -313,6 +313,12 @@ export const PartnerSchema = z
.describe(
"The partner's Stripe Connect ID (for receiving payouts via Stripe).",
),
+ stripeRecipientId: z
+ .string()
+ .nullable()
+ .describe(
+ "The partner's Stripe Recipient ID (for stablecoin/outbound payouts).",
+ ),
paypalEmail: z
.string()
.nullable()
diff --git a/apps/web/lib/zod/schemas/payouts.ts b/apps/web/lib/zod/schemas/payouts.ts
index c5f483e767..f2c8d0abfe 100644
--- a/apps/web/lib/zod/schemas/payouts.ts
+++ b/apps/web/lib/zod/schemas/payouts.ts
@@ -1,6 +1,10 @@
import { ELIGIBLE_PAYOUTS_MAX_PAGE_SIZE } from "@/lib/constants/payouts";
import { CUTOFF_PERIOD_ENUM } from "@/lib/partners/cutoff-period";
-import { PayoutMode, PayoutStatus } from "@dub/prisma/client";
+import {
+ PartnerPayoutMethod,
+ PayoutMode,
+ PayoutStatus,
+} from "@dub/prisma/client";
import * as z from "zod/v4";
import { getPaginationQuerySchema } from "./misc";
import { EnrolledPartnerSchema } from "./partners";
@@ -85,6 +89,7 @@ export const PayoutSchema = z.object({
paidAt: z.date().nullable(),
failureReason: z.string().nullish(),
mode: z.enum(PayoutMode).nullable(),
+ method: z.enum(PartnerPayoutMethod).nullable(),
traceId: z.string().nullish(),
});
diff --git a/apps/web/scripts/migrations/backfill-default-payout-method.ts b/apps/web/scripts/migrations/backfill-default-payout-method.ts
new file mode 100644
index 0000000000..3e9338a62f
--- /dev/null
+++ b/apps/web/scripts/migrations/backfill-default-payout-method.ts
@@ -0,0 +1,86 @@
+import { prisma } from "@dub/prisma";
+import { Partner, PartnerPayoutMethod } from "@dub/prisma/client";
+import "dotenv-flow/config";
+
+const BATCH_SIZE = 500;
+
+async function main() {
+ while (true) {
+ const partners = await prisma.partner.findMany({
+ where: {
+ defaultPayoutMethod: null,
+ OR: [
+ {
+ stripeConnectId: {
+ not: null,
+ },
+ },
+ {
+ paypalEmail: {
+ not: null,
+ },
+ },
+ ],
+ },
+ select: {
+ id: true,
+ stripeConnectId: true,
+ paypalEmail: true,
+ },
+ take: BATCH_SIZE,
+ });
+
+ if (partners.length === 0) {
+ break;
+ }
+
+ const connectPartners: Pick<Partner, "id" | "stripeConnectId">[] = [];
+ const paypalPartners: Pick<Partner, "id" | "paypalEmail">[] = [];
+
+ for (const partner of partners) {
+ if (partner.stripeConnectId) {
+ connectPartners.push(partner);
+ } else if (partner.paypalEmail) {
+ paypalPartners.push(partner);
+ }
+ }
+
+ const promise1 =
+ connectPartners.length > 0
+ ? prisma.partner.updateMany({
+ where: {
+ id: {
+ in: connectPartners.map((partner) => partner.id),
+ },
+ defaultPayoutMethod: null,
+ },
+ data: {
+ defaultPayoutMethod: PartnerPayoutMethod.connect,
+ },
+ })
+ : Promise.resolve({ count: 0 });
+
+ const promise2 =
+ paypalPartners.length > 0
+ ? prisma.partner.updateMany({
+ where: {
+ id: {
+ in: paypalPartners.map((partner) => partner.id),
+ },
+ defaultPayoutMethod: null,
+ },
+ data: {
+ defaultPayoutMethod: PartnerPayoutMethod.paypal,
+ },
+ })
+ : Promise.resolve({ count: 0 });
+
+ const [connectRes, paypalRes] = await Promise.all([promise1, promise2]);
+
+ console.log(
+ `Updated ${connectRes.count} connect partners and ${paypalRes.count} paypal partners`,
+ );
+ }
+}
+
+main();
diff --git a/apps/web/scripts/migrations/backfill-payout-method.ts b/apps/web/scripts/migrations/backfill-payout-method.ts
new file mode 100644
index 0000000000..d4e3b54553
--- /dev/null
+++ b/apps/web/scripts/migrations/backfill-payout-method.ts
@@ -0,0 +1,85 @@
+import { prisma } from "@dub/prisma";
+import { PartnerPayoutMethod } from "@dub/prisma/client";
+import "dotenv-flow/config";
+
+const BATCH_SIZE = 500;
+
+async function main() {
+ while (true) {
+ const payouts = await prisma.payout.findMany({
+ where: {
+ method: null,
+ OR: [
+ {
+ stripeTransferId: {
+ not: null,
+ },
+ },
+ {
+ paypalTransferId: {
+ not: null,
+ },
+ },
+ ],
+ },
+ select: {
+ id: true,
+ stripeTransferId: true,
+ stripePayoutId: true,
+ paypalTransferId: true,
+ },
+ take: BATCH_SIZE,
+ });
+
+ if (payouts.length === 0) {
+ break;
+ }
+
+ const connectPayoutIds: string[] = [];
+ const paypalPayoutIds: string[] = [];
+
+ for (const payout of payouts) {
+ if (payout.stripeTransferId || payout.stripePayoutId) {
+ connectPayoutIds.push(payout.id);
+ } else if (payout.paypalTransferId) {
+ paypalPayoutIds.push(payout.id);
+ }
+ }
+
+ const [connectRes, paypalRes] = await Promise.all([
+ connectPayoutIds.length > 0
+ ? prisma.payout.updateMany({
+ where: {
+ id: {
+ in: connectPayoutIds,
+ },
+ },
+ data: {
+ method: PartnerPayoutMethod.connect,
+ },
+ })
+ : Promise.resolve({ count: 0 }),
+
+ paypalPayoutIds.length > 0
+ ? prisma.payout.updateMany({
+ where: {
+ id: {
+ in: paypalPayoutIds,
+ },
+ },
+ data: {
+ method: PartnerPayoutMethod.paypal,
+ },
+ })
+ : Promise.resolve({ count: 0 }),
+ ]);
+
+ console.log(
+ `Updated ${connectRes.count} connect payouts and ${paypalRes.count} paypal payouts`,
+ );
+ }
+
+ console.log("Backfill finished.");
+}
+
+main();
diff --git a/apps/web/scripts/seed-fraud-events.ts b/apps/web/scripts/seed-fraud-events.ts
deleted file mode 100644
index 47f82f4627..0000000000
--- a/apps/web/scripts/seed-fraud-events.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { detectDuplicatePayoutMethodFraud } from "@/lib/api/fraud/detect-duplicate-payout-method-fraud";
-import "dotenv-flow/config";
-
-async function main() {
- await detectDuplicatePayoutMethodFraud("2");
-}
-
-main();
diff --git a/apps/web/ui/layout/sidebar/payout-stats.tsx b/apps/web/ui/layout/sidebar/payout-stats.tsx
index c02ffbdcfe..85a228dcd0 100644
--- a/apps/web/ui/layout/sidebar/payout-stats.tsx
+++ b/apps/web/ui/layout/sidebar/payout-stats.tsx
@@ -3,7 +3,7 @@
import usePartnerPayoutsCount from "@/lib/swr/use-partner-payouts-count";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
import { PayoutsCount } from "@/lib/types";
-import { ConnectPayoutButton } from "@/ui/partners/connect-payout-button";
+import { ConnectPayoutButton } from "@/ui/partners/payouts/connect-payout-button";
import { AlertCircleFill } from "@/ui/shared/icons";
import { PayoutStatus } from "@dub/prisma/client";
import {
diff --git a/apps/web/ui/partners/connect-payout-button.tsx b/apps/web/ui/partners/connect-payout-button.tsx
deleted file mode 100644
index 7dd32af8f0..0000000000
--- a/apps/web/ui/partners/connect-payout-button.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-"use client";
-
-import { generatePaypalOAuthUrl } from "@/lib/actions/partners/generate-paypal-oauth-url";
-import { generateStripeAccountLink } from "@/lib/actions/partners/generate-stripe-account-link";
-import { hasPermission } from "@/lib/auth/partner-users/partner-user-permissions";
-import usePartnerProfile from "@/lib/swr/use-partner-profile";
-import { useBankAccountRequirementsModal } from "@/ui/partners/bank-account-requirements-modal";
-import { Button, ButtonProps, TooltipContent } from "@dub/ui";
-import { COUNTRIES } from "@dub/utils";
-import { useAction } from "next-safe-action/hooks";
-import { useRouter } from "next/navigation";
-import { useCallback, useMemo } from "react";
-import { toast } from "sonner";
-
-export function ConnectPayoutButton(props: ButtonProps) {
- const router = useRouter();
- const { partner, payoutMethod } = usePartnerProfile();
-
- const { executeAsync: executeStripeAsync, isPending: isStripePending } =
- useAction(generateStripeAccountLink, {
- onSuccess: ({ data }) => {
- if (!data?.url) {
- toast.error("Unable to create account link. Please contact support.");
- return;
- }
- router.push(data.url);
- },
- onError: ({ error }) => {
- toast.error(error.serverError);
- },
- });
-
- const { executeAsync: executePaypalAsync, isPending: isPaypalPending } =
- useAction(generatePaypalOAuthUrl, {
- onSuccess: ({ data }) => {
- if (!data?.url) {
- toast.error("Unable to redirect to Paypal. Please contact support.");
- return;
- }
- router.push(data.url);
- },
- onError: ({ error }) => {
- toast.error(error.serverError);
- },
- });
-
- const connectPayout = useCallback(async () => {
- if (!partner) {
- toast.error("Invalid partner profile. Please log out and log back in.");
- return;
- }
-
- if (!partner.country) {
- toast.error(
- "You haven't set your country yet. Please go to partners.dub.co/settings to set your country.",
- );
- return;
- }
-
- if (payoutMethod === "paypal") {
- await executePaypalAsync();
- } else if (payoutMethod === "stripe") {
- await executeStripeAsync();
- } else {
- toast.error(
- "Your country is not supported for payout. Please go to partners.dub.co/settings to update your country, or contact support.",
- );
- return;
- }
- }, [executeStripeAsync, executePaypalAsync, partner, payoutMethod]);
-
- const { setShowBankAccountRequirementsModal, BankAccountRequirementsModal } =
- useBankAccountRequirementsModal({
- onContinue: connectPayout,
- });
-
- const errorMessage = useMemo(
- () =>
- !partner?.country
- ? "You haven't set your country yet. Please update your country or contact support."
- : !payoutMethod
- ? `Your current country (${COUNTRIES[partner.country]}) is not supported for payout. Please update your country or contact support.`
- : undefined,
- [partner, payoutMethod],
- );
-
- if (partner && !hasPermission(partner.role, "payout_settings.update")) {
- return null;
- }
-
- return (
- <>
- {BankAccountRequirementsModal}
- <Button
- onClick={() => {
- if (payoutMethod === "stripe") {
- setShowBankAccountRequirementsModal(true);
- } else {
- connectPayout();
- }
- }}
- loading={isStripePending || isPaypalPending}
- text={
- payoutMethod === "paypal" ? "Connect PayPal" : "Connect bank account"
- }
- disabledTooltip={
- errorMessage && (
- <TooltipContent
- title={errorMessage}
- cta="Update profile settings"
- href="/profile"
- />
- )
- }
- {...props}
- />
- </>
- );
-}
diff --git a/apps/web/ui/partners/payout-methods-dropdown.tsx b/apps/web/ui/partners/payout-methods-dropdown.tsx
deleted file mode 100644
index ddb8a3f149..0000000000
--- a/apps/web/ui/partners/payout-methods-dropdown.tsx
+++ /dev/null
@@ -1,336 +0,0 @@
-"use client";
-
-import { generatePaypalOAuthUrl } from "@/lib/actions/partners/generate-paypal-oauth-url";
-import { generateStripeAccountLink } from "@/lib/actions/partners/generate-stripe-account-link";
-import { BANK_ACCOUNT_STATUS_DESCRIPTIONS } from "@/lib/constants/payouts";
-import { bankAccountSchema } from "@/lib/partners/get-partner-bank-account";
-import usePartnerProfile from "@/lib/swr/use-partner-profile";
-import { PartnerProps } from "@/lib/types";
-import {
- Button,
- DynamicTooltipWrapper,
- MatrixLines,
- Paypal,
- Popover,
- StripeIcon,
-} from "@dub/ui";
-import { cn, fetcher } from "@dub/utils";
-import { AlertCircle, CheckCircle2, ChevronsUpDown } from "lucide-react";
-import { useAction } from "next-safe-action/hooks";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { toast } from "sonner";
-import useSWR from "swr";
-import * as z from "zod/v4";
-
-export function PayoutMethodsDropdown() {
- const router = useRouter();
- const [openPopover, setOpenPopover] = useState(false);
- const {
- partner,
- payoutMethod,
- loading: isPartnerLoading,
- } = usePartnerProfile();
-
- const { data: bankAccount, isLoading: isBankAccountLoading } = useSWR<
- z.infer<typeof bankAccountSchema>
- >(
- partner?.stripeConnectId ? "/api/partner-profile/payouts/settings" : null,
- fetcher,
- );
-
- const { executeAsync: executeStripeAsync, isPending: isStripePending } =
- useAction(generateStripeAccountLink, {
- onSuccess: ({ data }) => {
- if (!data?.url) {
- toast.error("Unable to create account link. Please contact support.");
- return;
- }
- router.push(data.url);
- },
- onError: ({ error }) => {
- toast.error(error.serverError);
- },
- });
-
- const { executeAsync: executePaypalAsync, isPending: isPaypalPending } =
- useAction(generatePaypalOAuthUrl, {
- onSuccess: ({ data }) => {
- if (!data?.url) {
- toast.error("Unable to redirect to Paypal. Please contact support.");
- return;
- }
- router.push(data.url);
- },
- onError: ({ error }) => {
- toast.error(error.serverError);
- },
- });
-
- if (!partner) {
- return null;
- }
-
- const payoutMethods = [
- {
- id: "paypal",
- label: "PayPal",
- color: "bg-blue-100",
- icon: <Paypal />,
- getAccountDetails: (partner: Pick<PartnerProps, "paypalEmail">) =>
- partner?.paypalEmail
- ? `Account ${partner.paypalEmail}`
- : "Not connected",
- isVisible: (partner: Pick<PartnerProps, "country" | "paypalEmail">) =>
- payoutMethod === "paypal" || partner.paypalEmail,
- },
- {
- id: "stripe",
- label: bankAccount?.bank_name || "Stripe",
- color: "bg-purple-100",
- icon: <StripeIcon />,
- status: bankAccount?.status,
- getAccountDetails: (partner: Pick<PartnerProps, "stripeConnectId">) => {
- if (!partner?.stripeConnectId || !bankAccount) {
- return "Not connected";
- }
-
- return (
- <div className="flex items-center gap-1.5">
- <MatrixLines className="size-3" />
- {bankAccount.routing_number}
- <MatrixLines className="size-3" />
- ••••{bankAccount.last4}
- </div>
- );
- },
- isVisible: (partner: Pick<PartnerProps, "country" | "stripeConnectId">) =>
- payoutMethod === "stripe" || partner.stripeConnectId,
- },
- ];
-
- const connectPayout = async (method: string) => {
- if (!partner) {
- return;
- }
-
- if (method === "paypal") {
- await executePaypalAsync();
- } else if (method === "stripe") {
- await executeStripeAsync();
- }
-
- setOpenPopover(false);
- };
-
- const selectedMethod = (() => {
- if (partner?.stripeConnectId) {
- return payoutMethods.find(({ id }) => id === "stripe");
- } else if (partner?.paypalEmail) {
- return payoutMethods.find(({ id }) => id === "paypal");
- }
-
- return null;
- })();
-
- const isConnected = (method: string) => {
- if (method === "paypal") {
- return !!partner?.paypalEmail;
- }
-
- if (method === "stripe") {
- return !!partner?.stripeConnectId;
- }
-
- return false;
- };
-
- return (
- <div>
- <Popover
- popoverContentClassName="w-[var(--radix-popover-trigger-width)]"
- content={
- <div className="relative w-full">
- <div className="w-full space-y-0.5 rounded-lg bg-white p-1 text-sm">
- <div className="flex flex-col gap-2">
- {payoutMethods
- .filter(({ isVisible }) => isVisible(partner))
- .map(
- ({ id, label, color, icon, status, getAccountDetails }) => {
- return (
- <div
- key={id}
- className="flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5 transition-all duration-75"
- >
- <div className="flex items-center gap-x-2">
- <PayoutMethodStatusIndicator
- className={cn(
- "size-8 shrink-0 rounded-lg",
- id === "paypal" && "p-2",
- color,
- )}
- icon={icon}
- partner={partner}
- bankAccount={bankAccount}
- isLoading={
- isBankAccountLoading || isPartnerLoading
- }
- />
- <div>
- <div className="flex items-center gap-1">
- <span className="text-xs font-medium text-neutral-900">
- {label}
- </span>
- </div>
- <span className="block w-44 truncate text-xs text-neutral-500">
- {getAccountDetails(partner)}
- </span>
- </div>
- </div>
-
- <Button
- variant={isConnected(id) ? "secondary" : "primary"}
- text={
- isConnected(id)
- ? id === "paypal"
- ? "Switch account"
- : "Manage"
- : "Connect"
- }
- onClick={() => connectPayout(id)}
- loading={isStripePending || isPaypalPending}
- className="h-7 w-fit text-xs"
- />
- </div>
- );
- },
- )}
- </div>
- </div>
- </div>
- }
- align="start"
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- >
- <button
- onClick={() => setOpenPopover(!openPopover)}
- className={cn(
- "flex w-full items-center justify-between rounded-lg bg-white p-2 text-left text-sm transition-all duration-75",
- "border border-neutral-200 outline-none focus-visible:ring-2 focus-visible:ring-black/50",
- )}
- >
- {isBankAccountLoading || isPartnerLoading ? (
- <PayoutMethodSkeleton />
- ) : (
- <>
- <div className="flex min-w-0 items-center gap-x-2.5 pr-2">
- <PayoutMethodStatusIndicator
- className={cn(
- "size-8 shrink-0 rounded-lg",
- selectedMethod?.id === "paypal" && "p-2",
- selectedMethod?.color,
- )}
- icon={selectedMethod?.icon}
- partner={partner}
- bankAccount={bankAccount}
- isLoading={isBankAccountLoading || isPartnerLoading}
- />
- <div className="min-w-0">
- <div className="flex items-center gap-1">
- <span className="block text-xs font-medium text-neutral-900">
- {selectedMethod?.label}
- </span>
- </div>
- <span className="block w-44 truncate text-xs text-neutral-500">
- {selectedMethod?.getAccountDetails(partner)}
- </span>
- </div>
- </div>
- <ChevronsUpDown
- className="size-4 shrink-0 text-neutral-400"
- aria-hidden="true"
- />
- </>
- )}
- </button>
- </Popover>
- </div>
- );
-}
-
-function PayoutMethodSkeleton() {
- return (
- <>
- <div className="flex min-w-0 items-center gap-x-2.5 pr-2">
- <div className="size-8 shrink-0 animate-pulse rounded-lg bg-neutral-200" />
- <div className="min-w-0">
- <div className="h-3 w-24 animate-pulse rounded bg-neutral-200" />
- <div className="mt-1 h-3 w-44 animate-pulse rounded bg-neutral-200" />
- </div>
- </div>
- <div className="size-4 shrink-0 animate-pulse rounded bg-neutral-200" />
- </>
- );
-}
-
-function PayoutMethodStatusIndicator({
- icon,
- className,
- partner,
- bankAccount,
- isLoading,
-}: {
- icon: React.ReactNode;
- className?: string;
- partner: Pick<PartnerProps, "paypalEmail" | "stripeConnectId"> | null;
- bankAccount?: z.infer<typeof bankAccountSchema> | null;
- isLoading?: boolean;
-}) {
- if (isLoading || !partner?.stripeConnectId || !bankAccount?.status) {
- return <div className={className}>{icon}</div>;
- }
-
- const statusInfo = BANK_ACCOUNT_STATUS_DESCRIPTIONS[bankAccount.status];
-
- return (
- <DynamicTooltipWrapper
- tooltipProps={{
- content: statusInfo ? (
- <div className="grid max-w-xs gap-2 p-4">
- <div className="flex items-center gap-2 text-sm font-medium">
- {statusInfo.title}
- <div
- className={cn(
- statusInfo.variant === "invalid"
- ? "border-red-300 bg-red-200 text-red-800"
- : "border-green-300 bg-green-200 text-green-800",
- "flex size-5 items-center justify-center rounded-md border",
- )}
- >
- {statusInfo.variant === "invalid" ? (
- <AlertCircle className="size-3" />
- ) : (
- <CheckCircle2 className="size-3" />
- )}
- </div>
- </div>
- <div className="text-pretty text-sm text-neutral-500">
- {statusInfo.description}
- </div>
- </div>
- ) : undefined,
- }}
- >
- <div className={cn("relative shrink-0", className)}>
- {icon}
- <div
- className={cn(
- "absolute -bottom-0.5 -right-0.5 size-2.5 rounded-full",
- statusInfo.variant === "invalid" ? "bg-red-500" : "bg-green-500",
- )}
- />
- </div>
- </DynamicTooltipWrapper>
- );
-}
diff --git a/apps/web/ui/partners/payout-row-menu.tsx b/apps/web/ui/partners/payout-row-menu.tsx
index 710975c1aa..536cdbc5ff 100644
--- a/apps/web/ui/partners/payout-row-menu.tsx
+++ b/apps/web/ui/partners/payout-row-menu.tsx
@@ -12,7 +12,7 @@ import { useState } from "react";
import { toast } from "sonner";
export function PayoutRowMenu({ row }: { row: Row<PartnerPayoutResponse> }) {
- const { payoutMethod } = usePartnerProfile();
+ const { partner } = usePartnerProfile();
const [isOpen, setIsOpen] = useState(false);
const { executeAsync: executeRetryPayout, isPending: isRetryPayoutPending } =
@@ -42,7 +42,8 @@ export function PayoutRowMenu({ row }: { row: Row<PartnerPayoutResponse> }) {
});
const canRetry =
- row.original.status === "failed" && payoutMethod === "paypal";
+ row.original.status === "failed" &&
+ partner?.defaultPayoutMethod === "paypal";
if (!canRetry) {
return null;
diff --git a/apps/web/ui/partners/payout-status-badge-partner.tsx b/apps/web/ui/partners/payout-status-badge-partner.tsx
index e653bf32c1..4c0ccba6c3 100644
--- a/apps/web/ui/partners/payout-status-badge-partner.tsx
+++ b/apps/web/ui/partners/payout-status-badge-partner.tsx
@@ -10,7 +10,7 @@ export const PayoutStatusBadgePartner = ({
payout,
program,
}: {
- payout: Pick<Payout, "status" | "amount"> & {
+ payout: Pick<Payout, "status" | "amount" | "method"> & {
failureReason?: string | null;
};
program: Pick<Program, "minPayoutAmount">;
@@ -23,9 +23,11 @@ export const PayoutStatusBadgePartner = ({
if (!partner) {
return undefined;
}
+
if (payout.status === "failed" && payout.failureReason) {
return payout.failureReason;
}
+
if (
payout.status === "pending" &&
payout.amount < program.minPayoutAmount
@@ -35,11 +37,14 @@ export const PayoutStatusBadgePartner = ({
{ trailingZeroDisplay: "stripIfInteger" },
)}. This payout will be accrued and processed during the next payout period.`;
}
- return (
- PAYOUT_STATUS_DESCRIPTIONS?.[
- partner?.paypalEmail ? "paypal" : "stripe"
- ]?.[payout.status] || PAYOUT_STATUS_DESCRIPTIONS?.paypal?.[payout.status]
- );
+
+ const payoutMethod = payout.method ?? partner?.defaultPayoutMethod;
+
+ if (!payoutMethod) {
+ return undefined;
+ }
+
+ return PAYOUT_STATUS_DESCRIPTIONS[payoutMethod][payout.status];
}, [payout, program, partner]);
return badge ? (
diff --git a/apps/web/ui/partners/payout-status-descriptions.ts b/apps/web/ui/partners/payout-status-descriptions.ts
index cccb36bd28..0432a4c6b3 100644
--- a/apps/web/ui/partners/payout-status-descriptions.ts
+++ b/apps/web/ui/partners/payout-status-descriptions.ts
@@ -1,8 +1,12 @@
import { MIN_WITHDRAWAL_AMOUNT_CENTS } from "@/lib/constants/payouts";
+import { PartnerPayoutMethod, PayoutStatus } from "@dub/prisma/client";
import { currencyFormatter } from "@dub/utils";
-export const PAYOUT_STATUS_DESCRIPTIONS = {
- stripe: {
+export const PAYOUT_STATUS_DESCRIPTIONS: Record<
+ PartnerPayoutMethod,
+ Record<Exclude<PayoutStatus, "failed" | "canceled">, string>
+> = {
+ connect: {
pending:
"Payouts that have passed the [program's holding period](https://dub.co/help/article/commissions-payouts#what-does-holding-period-mean) and are awaiting payment from the program (as long as it reaches the [program's minimum payout amount](https://dub.co/help/article/commissions-payouts#what-does-minimum-payout-amount-mean)).",
processing:
@@ -13,6 +17,18 @@ export const PAYOUT_STATUS_DESCRIPTIONS = {
"Payouts that have been paid out to your connected bank account.",
},
+ stablecoin: {
+ pending:
+ "Payouts that have passed the [program's holding period](https://dub.co/help/article/commissions-payouts#what-does-holding-period-mean) and are awaiting payment from the program (as long as it reaches the [program's minimum payout amount](https://dub.co/help/article/commissions-payouts#what-does-minimum-payout-amount-mean)).",
+ processing:
+ "Payouts that are being processed by the program – this can take up to 5 business days.",
+ processed:
+ "Payouts that have been processed by the program and will be sent to your connected crypto wallet (a 1% stablecoin payout fee is deducted).",
+ sent: "Payouts that are on their way to your connected crypto wallet – typically arriving within minutes.",
+ completed:
+ "Payouts that have been paid out to your connected crypto wallet.",
+ },
+
paypal: {
pending:
"Payouts that have passed the [program's holding period](https://dub.co/help/article/commissions-payouts#what-does-holding-period-mean) and are awaiting payment from the program (once it reaches the [program's minimum payout amount](https://dub.co/help/article/commissions-payouts#what-does-minimum-payout-amount-mean)).",
diff --git a/apps/web/ui/partners/bank-account-requirements-modal.tsx b/apps/web/ui/partners/payouts/bank-account-requirements-modal.tsx
similarity index 98%
rename from apps/web/ui/partners/bank-account-requirements-modal.tsx
rename to apps/web/ui/partners/payouts/bank-account-requirements-modal.tsx
index 5154557e3f..4788371132 100644
--- a/apps/web/ui/partners/bank-account-requirements-modal.tsx
+++ b/apps/web/ui/partners/payouts/bank-account-requirements-modal.tsx
@@ -5,7 +5,7 @@ import { Button, Modal } from "@dub/ui";
import { TriangleWarning } from "@dub/ui/icons";
import { COUNTRIES, COUNTRY_CURRENCY_CODES } from "@dub/utils";
import { Dispatch, SetStateAction, useMemo, useState } from "react";
-import { Markdown } from "../shared/markdown";
+import { Markdown } from "../../shared/markdown";
function BankAccountRequirementsModal({
showModal,
diff --git a/apps/web/ui/partners/payouts/connect-payout-button.tsx b/apps/web/ui/partners/payouts/connect-payout-button.tsx
new file mode 100644
index 0000000000..a041a07ebb
--- /dev/null
+++ b/apps/web/ui/partners/payouts/connect-payout-button.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { hasPermission } from "@/lib/auth/partner-users/partner-user-permissions";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
+import { useConnectPayoutModal } from "@/ui/partners/payouts/connect-payout-modal";
+import { PartnerPayoutMethod } from "@dub/prisma/client";
+import { Button, ButtonProps, TooltipContent } from "@dub/ui";
+import { COUNTRIES } from "@dub/utils";
+import { useCallback, useMemo } from "react";
+import { usePayoutConnectFlow } from "./use-payout-connect-flow";
+
+interface ConnectPayoutButtonProps extends ButtonProps {
+ payoutMethod?: PartnerPayoutMethod;
+ connected?: boolean;
+ allowWhenPayoutsEnabled?: boolean;
+}
+
+export function ConnectPayoutButton({
+ payoutMethod,
+ connected,
+ allowWhenPayoutsEnabled,
+ ...props
+}: ConnectPayoutButtonProps) {
+ const { partner, availablePayoutMethods } = usePartnerProfile();
+
+ const { setShowConnectPayoutModal, ConnectPayoutModal } =
+ useConnectPayoutModal();
+
+ const {
+ connect,
+ isPending,
+ BankAccountRequirementsModal,
+ StablecoinPayoutModal,
+ } = usePayoutConnectFlow({
+ closeParent: () => setShowConnectPayoutModal(false),
+ });
+
+ const handleClick = useCallback(() => {
+ if (payoutMethod) {
+ connect(payoutMethod);
+ return;
+ }
+ setShowConnectPayoutModal(true);
+ }, [payoutMethod, connect, setShowConnectPayoutModal]);
+
+ const errorMessage = useMemo(
+ () =>
+ !partner?.country
+ ? "You haven't set your country yet. Please update your country or contact support."
+ : availablePayoutMethods.length === 0
+ ? `Your current country (${COUNTRIES[partner.country]}) is not supported for payout. Please update your country or contact support.`
+ : undefined,
+ [partner, availablePayoutMethods],
+ );
+
+ if (partner && !hasPermission(partner.role, "payout_settings.update")) {
+ return null;
+ }
+
+ if (partner?.payoutsEnabledAt && !allowWhenPayoutsEnabled) {
+ return null;
+ }
+
+ return (
+ <>
+ {ConnectPayoutModal}
+ {BankAccountRequirementsModal}
+ {StablecoinPayoutModal}
+ <Button
+ onClick={handleClick}
+ text={
+ connected ? "Manage" : payoutMethod ? "Connect" : "Connect payout"
+ }
+ loading={isPending}
+ disabledTooltip={
+ errorMessage && (
+ <TooltipContent
+ title={errorMessage}
+ cta="Update profile settings"
+ href="/profile"
+ />
+ )
+ }
+ {...props}
+ />
+ </>
+ );
+}
diff --git a/apps/web/ui/partners/payouts/connect-payout-modal.tsx b/apps/web/ui/partners/payouts/connect-payout-modal.tsx
new file mode 100644
index 0000000000..c0c21a074e
--- /dev/null
+++ b/apps/web/ui/partners/payouts/connect-payout-modal.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import usePartnerPayoutSettings from "@/lib/swr/use-partner-payout-settings";
+import { Modal, MoneyBills2 } from "@dub/ui";
+import { X } from "lucide-react";
+import { Dispatch, SetStateAction, useMemo, useState } from "react";
+import { PayoutMethodSelector } from "./payout-method-cards";
+
+function ConnectPayoutModal({
+ showModal,
+ setShowModal,
+}: {
+ showModal: boolean;
+ setShowModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const { payoutMethods, isLoading: isPayoutMethodsLoading } =
+ usePartnerPayoutSettings();
+
+ const isOnlyPayoutMethod = payoutMethods.length === 1;
+
+ return (
+ <Modal
+ showModal={showModal}
+ setShowModal={setShowModal}
+ className="max-w-xl"
+ >
+ <div className="relative flex items-start justify-between gap-4 px-4 py-4 sm:px-6">
+ <div className="flex min-w-0 flex-1 flex-col gap-4">
+ <div className="flex size-12 shrink-0 items-center justify-center rounded-full border border-neutral-200 text-neutral-900">
+ <MoneyBills2 className="size-5 text-neutral-700" />
+ </div>
+ <div className="min-w-0">
+ <h3 className="text-lg font-semibold text-neutral-800">
+ {isPayoutMethodsLoading
+ ? "Loading…"
+ : isOnlyPayoutMethod
+ ? "Connect your payout method"
+ : "Select a payout method"}
+ </h3>
+ <p className="mt-0.5 text-sm text-neutral-500">
+ {isPayoutMethodsLoading
+ ? "Loading payout methods."
+ : isOnlyPayoutMethod
+ ? "Set up your payout method to receive payouts."
+ : "Select your preferred payout method to receive payouts."}
+ </p>
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => setShowModal(false)}
+ className="group shrink-0 rounded-full p-2 text-neutral-500 transition-all duration-75 hover:bg-neutral-100 focus:outline-none active:bg-neutral-200"
+ >
+ <X className="size-5" />
+ </button>
+ </div>
+
+ <div className="px-4 py-4 pt-0 sm:px-6">
+ {isPayoutMethodsLoading ? (
+ <PayoutMethodSelectorSkeleton />
+ ) : (
+ <PayoutMethodSelector payoutMethods={payoutMethods} />
+ )}
+ </div>
+ </Modal>
+ );
+}
+
+function PayoutMethodSelectorSkeleton() {
+ return (
+ <div className="grid gap-3 sm:grid-cols-2">
+ {[1, 2].map((i) => (
+ <div
+ key={i}
+ className="flex flex-col rounded-xl border border-neutral-200 bg-neutral-100 p-4"
+ aria-hidden
+ >
+ <div className="size-10 animate-pulse rounded-lg bg-neutral-200" />
+ <div className="mt-2 h-4 w-24 animate-pulse rounded bg-neutral-200" />
+ <ul className="mt-2.5 space-y-2.5">
+ {[1, 2, 3].map((j) => (
+ <li
+ key={j}
+ className="h-3 w-full animate-pulse rounded bg-neutral-200"
+ />
+ ))}
+ </ul>
+ <div className="mt-4 h-9 w-full animate-pulse rounded-lg bg-neutral-200" />
+ </div>
+ ))}
+ </div>
+ );
+}
+
+export function useConnectPayoutModal() {
+ const [showModal, setShowModal] = useState(false);
+
+ const ConnectPayoutModalElement = useMemo(
+ () => (
+ <ConnectPayoutModal showModal={showModal} setShowModal={setShowModal} />
+ ),
+ [showModal],
+ );
+
+ return useMemo(
+ () => ({
+ setShowConnectPayoutModal: setShowModal,
+ ConnectPayoutModal: ConnectPayoutModalElement,
+ }),
+ [ConnectPayoutModalElement, setShowModal],
+ );
+}
diff --git a/apps/web/ui/partners/payouts/payout-method-cards.tsx b/apps/web/ui/partners/payouts/payout-method-cards.tsx
new file mode 100644
index 0000000000..9339f6a623
--- /dev/null
+++ b/apps/web/ui/partners/payouts/payout-method-cards.tsx
@@ -0,0 +1,200 @@
+"use client";
+
+import type { PartnerPayoutMethodSetting } from "@/lib/types";
+import { Badge } from "@dub/ui";
+import { cn } from "@dub/utils";
+import type { ComponentType } from "react";
+import { ReactNode } from "react";
+import { ConnectPayoutButton } from "./connect-payout-button";
+import {
+ PAYOUT_METHODS,
+ type PayoutMethodFeature,
+} from "./payout-method-config";
+
+export { PAYOUT_METHODS };
+
+const CARD_VARIANTS = {
+ default: {
+ card: "p-4",
+ content: "gap-2",
+ title: "text-sm font-semibold text-neutral-900",
+ list: "space-y-2.5 text-xs",
+ featureIcon: "[&>svg]:size-4",
+ action: "mt-4",
+ },
+ compact: {
+ card: "p-3",
+ content: "gap-2",
+ title: "text-sm font-semibold text-neutral-900",
+ list: "space-y-2 text-xs",
+ featureIcon: "[&>svg]:size-4",
+ action: "mt-3",
+ },
+ spotlight: {
+ card: "p-8",
+ content: "gap-4",
+ title: "text-xl font-semibold text-neutral-900",
+ list: "space-y-3.5 text-sm",
+ featureIcon: "[&>svg]:size-5",
+ action: "mt-6",
+ },
+} as const;
+
+export function PayoutMethodSelector({
+ payoutMethods,
+ variant: variantProp,
+ actionFooter,
+ allowConnectWhenPayoutsEnabled,
+}: {
+ payoutMethods: PartnerPayoutMethodSetting[];
+ variant?: "default" | "compact";
+ actionFooter?: (setting: PartnerPayoutMethodSetting) => ReactNode;
+ allowConnectWhenPayoutsEnabled?: boolean;
+}) {
+ const filteredMethods = PAYOUT_METHODS.filter((m) =>
+ payoutMethods.some((s) => s.type === m.id),
+ );
+
+ const methodCount = filteredMethods.length;
+ const isSingleOption = methodCount === 1;
+ const isCompact = variantProp === "compact";
+
+ const gridClassName = isSingleOption
+ ? "w-full"
+ : methodCount === 2
+ ? "grid gap-3 sm:grid-cols-2"
+ : "grid gap-3 sm:grid-cols-3";
+
+ const cardVariant = isCompact
+ ? "compact"
+ : isSingleOption
+ ? "spotlight"
+ : "default";
+
+ const iconSize = isCompact ? "sm" : isSingleOption ? "lg" : "sm";
+
+ return (
+ <div className={gridClassName}>
+ {filteredMethods.map((method) => {
+ const setting = payoutMethods.find((s) => s.type === method.id)!;
+ return (
+ <PayoutMethodCard
+ key={method.id}
+ icon={
+ <PayoutMethodIcon
+ icon={method.icon}
+ wrapperClasses={method.iconWrapperClass}
+ size={iconSize}
+ />
+ }
+ title={method.title}
+ features={method.features}
+ recommended={method.recommended}
+ action={
+ <ConnectPayoutButton
+ payoutMethod={method.id}
+ connected={setting.connected}
+ className={cn(
+ "w-full rounded-lg",
+ isSingleOption ? "h-10" : "h-9",
+ )}
+ allowWhenPayoutsEnabled={allowConnectWhenPayoutsEnabled}
+ />
+ }
+ actionFooter={actionFooter?.(setting)}
+ variant={cardVariant}
+ />
+ );
+ })}
+ </div>
+ );
+}
+
+function PayoutMethodIcon({
+ icon: Icon,
+ wrapperClasses,
+ size = "sm",
+ iconClassName,
+}: {
+ icon: ComponentType<{ className?: string }>;
+ wrapperClasses: string;
+ size?: "sm" | "lg";
+ iconClassName?: string;
+}) {
+ const containerSize = size === "lg" ? "size-14" : "size-10";
+ const iconSize = size === "lg" ? "size-8" : "size-5";
+
+ return (
+ <div
+ className={cn(
+ "flex items-center justify-center rounded-lg border",
+ wrapperClasses,
+ containerSize,
+ )}
+ >
+ <Icon className={cn(iconSize, iconClassName)} />
+ </div>
+ );
+}
+
+function PayoutMethodCard({
+ icon,
+ title,
+ features,
+ recommended,
+ action,
+ actionFooter,
+ variant = "default",
+}: {
+ icon: ReactNode;
+ title: string;
+ features: readonly PayoutMethodFeature[];
+ recommended?: boolean;
+ action: ReactNode;
+ actionFooter?: ReactNode;
+ variant?: "default" | "compact" | "spotlight";
+}) {
+ const styles = CARD_VARIANTS[variant];
+
+ return (
+ <div
+ className={cn(
+ "relative flex flex-col rounded-xl border border-neutral-200 bg-neutral-100",
+ styles.card,
+ )}
+ >
+ {recommended && variant !== "spotlight" && (
+ <Badge
+ variant="green"
+ className="absolute right-3 top-3 rounded-md font-semibold text-green-700"
+ >
+ Recommended
+ </Badge>
+ )}
+
+ <div className={cn("flex flex-col text-left", styles.content)}>
+ <div>{icon}</div>
+ <h3 className={styles.title}>{title}</h3>
+
+ <ul className={cn("flex-1 font-medium text-neutral-600", styles.list)}>
+ {features.map(({ icon: FeatureIcon, text }) => (
+ <li key={text} className="flex items-center gap-2">
+ <span
+ className={cn(
+ "flex shrink-0 items-center justify-center text-neutral-500",
+ styles.featureIcon,
+ )}
+ >
+ <FeatureIcon />
+ </span>
+ {text}
+ </li>
+ ))}
+ </ul>
+
+ <div className={styles.action}>{action}</div>
+ {actionFooter}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/payouts/payout-method-config.ts b/apps/web/ui/partners/payouts/payout-method-config.ts
new file mode 100644
index 0000000000..32f21c9465
--- /dev/null
+++ b/apps/web/ui/partners/payouts/payout-method-config.ts
@@ -0,0 +1,64 @@
+import type { PartnerPayoutMethod } from "@dub/prisma/client";
+import { CircleDollar, GreekTemple, Paypal, Stablecoin } from "@dub/ui";
+import { Calendar, Globe, MapPin, Zap } from "lucide-react";
+import type { ComponentType } from "react";
+
+export const PAYOUT_METHODS = [
+ {
+ id: "stablecoin" as const,
+ title: "Stablecoin",
+ recommended: true,
+ icon: Stablecoin,
+ iconWrapperClass: "border-[#1717170D] bg-blue-100",
+ features: [
+ { icon: CircleDollar, text: "Paid in USDC" },
+ { icon: Globe, text: "No local bank required" },
+ { icon: Zap, text: "Payouts deposited instantly" },
+ ],
+ },
+ {
+ id: "connect" as const,
+ title: "Bank Account",
+ recommended: false,
+ icon: GreekTemple,
+ iconWrapperClass: "border-[#1717171A] bg-white text-content-emphasis",
+ features: [
+ { icon: MapPin, text: "Paid in local currency" },
+ { icon: GreekTemple, text: "Local bank required" },
+ { icon: Calendar, text: "Payouts deposited in days" },
+ ],
+ },
+ {
+ id: "paypal" as const,
+ title: "PayPal",
+ recommended: false,
+ icon: Paypal,
+ iconWrapperClass: "border-[#1717171A] bg-white p-2",
+ features: [
+ { icon: MapPin, text: "Paid in local currency" },
+ { icon: GreekTemple, text: "May require a linked bank" },
+ { icon: Zap, text: "Payouts deposited instantly" },
+ ],
+ },
+] as const;
+
+const PAYOUT_METHOD_ICON_CONFIG = Object.fromEntries(
+ PAYOUT_METHODS.map((m) => [
+ m.id,
+ { Icon: m.icon, wrapperClass: m.iconWrapperClass },
+ ]),
+) as Record<
+ PartnerPayoutMethod,
+ { Icon: ComponentType<{ className?: string }>; wrapperClass: string }
+>;
+
+export function getPayoutMethodIconConfig(type: PartnerPayoutMethod) {
+ return (
+ PAYOUT_METHOD_ICON_CONFIG[type] ?? { Icon: GreekTemple, wrapperClass: "" }
+ );
+}
+
+export type PayoutMethodFeature = {
+ icon: ComponentType<{ className?: string }>;
+ text: string;
+};
diff --git a/apps/web/ui/partners/payouts/payout-method-dropdown.tsx b/apps/web/ui/partners/payouts/payout-method-dropdown.tsx
new file mode 100644
index 0000000000..82d3090215
--- /dev/null
+++ b/apps/web/ui/partners/payouts/payout-method-dropdown.tsx
@@ -0,0 +1,205 @@
+"use client";
+
+import usePartnerPayoutSettings from "@/lib/swr/use-partner-payout-settings";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
+import type { PartnerPayoutMethodSetting } from "@/lib/types";
+import { partnerPayoutMethodSchema } from "@/lib/zod/schemas/partner-profile";
+import { getPayoutMethodIconConfig } from "@/ui/partners/payouts/payout-method-config";
+import { PartnerPayoutMethod } from "@dub/prisma/client";
+import { Button, Popover } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { ChevronsUpDown } from "lucide-react";
+import { useCallback, useState } from "react";
+import { usePayoutConnectFlow } from "./use-payout-connect-flow";
+
+export function PayoutMethodDropdown() {
+ const [openPopover, setOpenPopover] = useState(false);
+ const { partner, loading: isPartnerLoading } = usePartnerProfile();
+
+ const {
+ connect,
+ isPending,
+ BankAccountRequirementsModal,
+ StablecoinPayoutModal,
+ } = usePayoutConnectFlow();
+
+ const { payoutMethods: payoutMethodsData, isLoading: isSettingsLoading } =
+ usePartnerPayoutSettings();
+
+ const payoutMethods =
+ !payoutMethodsData || !Array.isArray(payoutMethodsData)
+ ? null
+ : payoutMethodsData.map((m) => partnerPayoutMethodSchema.parse(m));
+
+ const hasConnected = payoutMethods?.some((m) => m.connected) ?? false;
+
+ const handleAction = useCallback(
+ (type: PartnerPayoutMethod, isManage: boolean) => {
+ setOpenPopover(false);
+ connect(type, { isManage });
+ },
+ [connect],
+ );
+
+ const selectedMethod =
+ payoutMethods?.find((m) => m.default) ??
+ payoutMethods?.find((m) => m.connected);
+
+ const isLoading = isPartnerLoading || isSettingsLoading;
+
+ if (!partner || !hasConnected) {
+ return null;
+ }
+
+ return (
+ <>
+ {BankAccountRequirementsModal}
+ {StablecoinPayoutModal}
+ <div>
+ <Popover
+ popoverContentClassName="w-[var(--radix-popover-trigger-width)]"
+ content={
+ <div className="relative w-full">
+ <div className="w-full space-y-0.5 rounded-lg bg-white p-1 text-sm">
+ <div className="flex flex-col gap-2">
+ {payoutMethods?.map((method) => (
+ <PayoutMethodItem
+ key={method.type}
+ method={method}
+ onAction={handleAction}
+ isActionPending={isPending}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ }
+ align="start"
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ <button
+ type="button"
+ onClick={() => setOpenPopover(!openPopover)}
+ className={cn(
+ "flex w-full cursor-pointer items-center justify-between rounded-lg bg-white p-2 text-left text-sm transition-colors duration-75",
+ "border border-neutral-200 outline-none hover:bg-neutral-50 focus-visible:ring-2 focus-visible:ring-black/50",
+ )}
+ >
+ {isLoading || !selectedMethod ? (
+ <PayoutMethodSkeleton />
+ ) : (
+ <SelectedMethodDisplay method={selectedMethod} />
+ )}
+ </button>
+ </Popover>
+ </div>
+ </>
+ );
+}
+
+function PayoutMethodItem({
+ method,
+ onAction,
+ isActionPending,
+}: {
+ method: PartnerPayoutMethodSetting;
+ onAction: (type: PartnerPayoutMethod, isManage: boolean) => void;
+ isActionPending: boolean;
+}) {
+ const { Icon, wrapperClass } = getPayoutMethodIconConfig(method.type);
+
+ return (
+ <div className="flex w-full cursor-default items-center justify-between gap-4 rounded-md px-2 py-1.5 transition-colors duration-75 hover:bg-neutral-50">
+ <div className="flex min-w-0 flex-1 items-center gap-x-2">
+ <div
+ className={cn(
+ "flex size-9 shrink-0 items-center justify-center rounded-lg border",
+ wrapperClass,
+ )}
+ >
+ <Icon className="size-5" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="text-xs font-medium text-neutral-900">
+ {method.label}
+ </span>
+
+ {method.default && (
+ <span className="rounded-md bg-green-100 px-1.5 py-0.5 text-xs font-semibold text-green-700">
+ Default
+ </span>
+ )}
+ </div>
+ <span className="mt-0.5 block truncate text-xs text-neutral-500">
+ {method.identifier ?? "Not connected"}
+ </span>
+ </div>
+ </div>
+ <Button
+ variant={method.connected ? "primary" : "secondary"}
+ text={method.connected ? "Manage" : "Connect"}
+ onClick={() => onAction(method.type, method.connected)}
+ loading={isActionPending}
+ className="h-7 w-fit shrink-0 cursor-pointer text-xs"
+ />
+ </div>
+ );
+}
+
+function SelectedMethodDisplay({
+ method,
+}: {
+ method: PartnerPayoutMethodSetting;
+}) {
+ const { Icon, wrapperClass } = getPayoutMethodIconConfig(method.type);
+ return (
+ <>
+ <div className="flex min-w-0 items-center gap-x-2.5 pr-2">
+ <div
+ className={cn(
+ "flex size-8 shrink-0 items-center justify-center rounded-lg border",
+ wrapperClass,
+ )}
+ >
+ <Icon className="size-5" />
+ </div>
+ <div className="min-w-0">
+ <div className="flex items-center gap-1.5">
+ <span className="block text-xs font-medium text-neutral-900">
+ {method.label}
+ </span>
+ {method.default && (
+ <span className="rounded bg-green-100 px-1.5 py-0.5 text-xs font-medium text-green-700">
+ Default
+ </span>
+ )}
+ </div>
+ <span className="block truncate text-xs text-neutral-500">
+ {method.identifier ?? "Not connected"}
+ </span>
+ </div>
+ </div>
+ <ChevronsUpDown
+ className="size-4 shrink-0 text-neutral-400"
+ aria-hidden="true"
+ />
+ </>
+ );
+}
+
+function PayoutMethodSkeleton() {
+ return (
+ <>
+ <div className="flex min-w-0 items-center gap-x-2.5 pr-2">
+ <div className="size-8 shrink-0 animate-pulse rounded-lg bg-neutral-200" />
+ <div className="min-w-0">
+ <div className="h-3 w-24 animate-pulse rounded bg-neutral-200" />
+ <div className="mt-1 h-3 w-44 animate-pulse rounded bg-neutral-200" />
+ </div>
+ </div>
+ <div className="size-4 shrink-0 animate-pulse rounded bg-neutral-200" />
+ </>
+ );
+}
diff --git a/apps/web/ui/partners/payouts/stablecoin-payout-modal.tsx b/apps/web/ui/partners/payouts/stablecoin-payout-modal.tsx
new file mode 100644
index 0000000000..a555ddb076
--- /dev/null
+++ b/apps/web/ui/partners/payouts/stablecoin-payout-modal.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+import { MarkdownDescription } from "@/ui/shared/markdown-description";
+import { Badge, Button, CircleDollar3, Modal } from "@dub/ui";
+import { Dispatch, SetStateAction, useMemo, useState } from "react";
+
+function StablecoinPayoutModal({
+ showModal,
+ setShowModal,
+ onContinue,
+}: {
+ showModal: boolean;
+ setShowModal: Dispatch<SetStateAction<boolean>>;
+ onContinue: () => Promise<void>;
+}) {
+ const [isLoading, setIsLoading] = useState(false);
+
+ return (
+ <Modal
+ showModal={showModal}
+ setShowModal={setShowModal}
+ className="max-w-md"
+ >
+ <div className="relative flex flex-col overflow-hidden rounded-t-2xl">
+ <div className="relative flex h-40 items-center justify-center overflow-hidden bg-gradient-to-r from-blue-400 via-indigo-500 to-purple-600">
+ <div
+ className="absolute inset-0 opacity-30"
+ style={{
+ backgroundImage: `radial-gradient(circle at 1px 1px, white 1px, transparent 0)`,
+ backgroundSize: "24px 24px",
+ }}
+ />
+ <div className="relative flex size-20 shrink-0 items-center justify-center rounded-2xl bg-white shadow-lg">
+ <div className="flex size-12 items-center justify-center rounded-full bg-[#635BFF]">
+ <CircleDollar3 className="size-7 text-white" />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-2 p-8">
+ <div className="flex items-center gap-2">
+ <Badge
+ variant="green"
+ className="rounded-md font-semibold text-green-700"
+ >
+ NEW
+ </Badge>
+ </div>
+
+ <h3 className="text-lg font-semibold text-neutral-900">
+ Stablecoin payouts are here!
+ </h3>
+
+ <MarkdownDescription className="text-sm leading-5 text-neutral-600">
+ You can now connect your crypto wallet for payouts. With [stablecoin
+ payouts](https://dub.co/help/article/receiving-payouts), you can get
+ paid USDC worldwide in seconds, instead of waiting days with a bank
+ account.
+ </MarkdownDescription>
+
+ <div className="mt-4">
+ <Button
+ text="Connect Stablecoin"
+ variant="primary"
+ className="w-full rounded-lg"
+ loading={isLoading}
+ onClick={async () => {
+ setIsLoading(true);
+ try {
+ await onContinue();
+ } finally {
+ setIsLoading(false);
+ }
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </Modal>
+ );
+}
+
+export function useStablecoinPayoutModal({
+ onContinue,
+}: {
+ onContinue: () => Promise<void>;
+}) {
+ const [showModal, setShowModal] = useState(false);
+
+ const StablecoinPayoutModalElement = useMemo(
+ () => (
+ <StablecoinPayoutModal
+ showModal={showModal}
+ setShowModal={setShowModal}
+ onContinue={onContinue}
+ />
+ ),
+ [showModal, onContinue],
+ );
+
+ return useMemo(
+ () => ({
+ setShowStablecoinPayoutModal: setShowModal,
+ StablecoinPayoutModal: StablecoinPayoutModalElement,
+ }),
+ [StablecoinPayoutModalElement],
+ );
+}
diff --git a/apps/web/ui/partners/payouts/use-payout-connect-flow.tsx b/apps/web/ui/partners/payouts/use-payout-connect-flow.tsx
new file mode 100644
index 0000000000..24ac412565
--- /dev/null
+++ b/apps/web/ui/partners/payouts/use-payout-connect-flow.tsx
@@ -0,0 +1,132 @@
+"use client";
+
+import { generatePaypalOAuthUrl } from "@/lib/actions/partners/generate-paypal-oauth-url";
+import { generateStripeAccountLink } from "@/lib/actions/partners/generate-stripe-account-link";
+import { generateStripeRecipientAccountLink } from "@/lib/actions/partners/generate-stripe-recipient-account-link";
+import { useBankAccountRequirementsModal } from "@/ui/partners/payouts/bank-account-requirements-modal";
+import { useStablecoinPayoutModal } from "@/ui/partners/payouts/stablecoin-payout-modal";
+import { PartnerPayoutMethod } from "@dub/prisma/client";
+import { useAction } from "next-safe-action/hooks";
+import { useRouter } from "next/navigation";
+import { useCallback, useMemo } from "react";
+import { toast } from "sonner";
+
+export function usePayoutConnectFlow(options?: { closeParent?: () => void }) {
+ const router = useRouter();
+ const closeParent = options?.closeParent;
+
+ const {
+ executeAsync: executeStripeConnect,
+ isPending: isStripeConnectPending,
+ } = useAction(generateStripeAccountLink, {
+ onSuccess: ({ data }) => {
+ router.push(data.url);
+ },
+ onError: ({ error }) => {
+ toast.error(error.serverError);
+ },
+ });
+
+ const {
+ executeAsync: executeStablecoinConnect,
+ isPending: isStablecoinConnectPending,
+ } = useAction(generateStripeRecipientAccountLink, {
+ onSuccess: ({ data }) => {
+ router.push(data.url);
+ },
+ onError: ({ error }) => {
+ toast.error(error.serverError);
+ },
+ });
+
+ const {
+ executeAsync: executePaypalConnect,
+ isPending: isPaypalConnectPending,
+ } = useAction(generatePaypalOAuthUrl, {
+ onSuccess: ({ data }) => {
+ router.push(data.url);
+ },
+ onError: ({ error }) => {
+ toast.error(error.serverError);
+ },
+ });
+
+ const {
+ setShowBankAccountRequirementsModal,
+ BankAccountRequirementsModal: BankAccountRequirementsModalElement,
+ } = useBankAccountRequirementsModal({
+ onContinue: async () => {
+ await executeStripeConnect();
+ },
+ });
+
+ const {
+ setShowStablecoinPayoutModal,
+ StablecoinPayoutModal: StablecoinPayoutModalElement,
+ } = useStablecoinPayoutModal({
+ onContinue: async () => {
+ await executeStablecoinConnect();
+ },
+ });
+
+ const connect = useCallback(
+ async (
+ type: PartnerPayoutMethod,
+ connectOptions?: { isManage?: boolean },
+ ) => {
+ const isManage = connectOptions?.isManage ?? false;
+
+ if (type === "connect") {
+ if (isManage) {
+ await executeStripeConnect();
+ } else {
+ closeParent?.();
+ setShowBankAccountRequirementsModal(true);
+ }
+ return;
+ }
+
+ if (type === "stablecoin") {
+ if (isManage) {
+ await executeStablecoinConnect();
+ } else {
+ closeParent?.();
+ setShowStablecoinPayoutModal(true);
+ }
+ return;
+ }
+
+ if (type === "paypal") {
+ closeParent?.();
+ await executePaypalConnect();
+ }
+ },
+ [
+ closeParent,
+ setShowBankAccountRequirementsModal,
+ setShowStablecoinPayoutModal,
+ executeStripeConnect,
+ executeStablecoinConnect,
+ executePaypalConnect,
+ ],
+ );
+
+ const isPending = useMemo(
+ () =>
+ isStripeConnectPending ||
+ isStablecoinConnectPending ||
+ isPaypalConnectPending,
+ [
+ isStripeConnectPending,
+ isStablecoinConnectPending,
+ isPaypalConnectPending,
+ ],
+ );
+
+ return {
+ connect,
+ isPending,
+ BankAccountRequirementsModal: BankAccountRequirementsModalElement,
+ StablecoinPayoutModal: StablecoinPayoutModalElement,
+ };
+}
diff --git a/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx b/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
index 10b71139f8..ad5eee477a 100644
--- a/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
+++ b/apps/web/ui/partners/program-reward-modifiers-tooltip.tsx
@@ -2,12 +2,10 @@
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
import { getRewardAmount } from "@/lib/partners/get-reward-amount";
-import { RewardConditions, RewardProps } from "@/lib/types";
+import { RewardCondition, RewardConditions, RewardProps } from "@/lib/types";
import {
CONDITION_OPERATOR_LABELS,
REWARD_CONDITIONS,
- rewardConditionSchema,
- rewardConditionsSchema,
} from "@/lib/zod/schemas/rewards";
import { InfoTooltip, useScrollProgress } from "@dub/ui";
import {
@@ -19,7 +17,6 @@ import {
} from "@dub/utils";
import { formatDuration } from "date-fns";
import { useRef } from "react";
-import * as z from "zod/v4";
interface ProgramRewardModifiersTooltipProps {
reward?: Omit<RewardProps, "id" | "updatedAt"> | null;
@@ -127,8 +124,8 @@ const RewardItem = ({
operator = "AND",
}: {
reward: Omit<RewardProps, "id" | "updatedAt">;
- conditions?: z.infer<typeof rewardConditionSchema>[];
- operator?: z.infer<typeof rewardConditionsSchema>["operator"];
+ conditions?: RewardCondition[];
+ operator?: RewardConditions["operator"];
}) => {
const rewardAmount = constructRewardAmount({
...reward,
diff --git a/packages/email/src/templates/connected-payout-method.tsx b/packages/email/src/templates/connected-payout-method.tsx
index 57e9e3a2ba..f79b1674e8 100644
--- a/packages/email/src/templates/connected-payout-method.tsx
+++ b/packages/email/src/templates/connected-payout-method.tsx
@@ -19,20 +19,28 @@ import { Footer } from "../components/footer";
export default function ConnectedPayoutMethod({
email = "[email protected]",
payoutMethod = {
+ type: "stablecoin",
account_holder_name: "Brendon Urie",
bank_name: "BANK OF AMERICA, N.A.",
last4: "1234",
routing_number: "1234567890",
+ wallet_address: "0x1234567890123456789012345678901234567890",
+ wallet_network: "Ethereum",
},
}: {
email: string;
payoutMethod: {
- account_holder_name: string | null;
- bank_name: string | null;
- last4: string;
- routing_number: string | null;
+ type?: "connect" | "stablecoin";
+ account_holder_name?: string | null;
+ bank_name?: string | null;
+ last4?: string | null;
+ routing_number?: string | null;
+ wallet_address?: string | null;
+ wallet_network?: string | null;
};
}) {
+ const isStablecoin = payoutMethod.type === "stablecoin";
+
return (
<Html>
<Head />
@@ -49,8 +57,9 @@ export default function ConnectedPayoutMethod({
</Heading>
<Text className="mb-6 text-sm leading-6 text-neutral-600">
- Great news! Your bank account has been successfully connected to
- your Dub partner account. You're all set to receive payouts.
+ {isStablecoin
+ ? "Great news! Your stablecoin wallet has been successfully connected to your Dub partner account. You're all set to receive USDC payouts."
+ : "Great news! Your bank account has been successfully connected to your Dub partner account. You're all set to receive payouts."}
</Text>
{/* Payout Method Details Card */}
@@ -59,46 +68,75 @@ export default function ConnectedPayoutMethod({
Connected payout method
</Text>
- {payoutMethod.account_holder_name && (
- <Row className="mb-2">
- <Column className="text-sm text-neutral-600">
- Account Holder
- </Column>
- <Column className="text-right text-sm font-medium text-neutral-800">
- {payoutMethod.account_holder_name}
- </Column>
- </Row>
- )}
+ {isStablecoin ? (
+ <>
+ {payoutMethod.wallet_network && (
+ <Row className="mb-2">
+ <Column className="text-sm text-neutral-600">
+ Network
+ </Column>
+ <Column className="text-right text-sm font-medium text-neutral-800">
+ {payoutMethod.wallet_network}
+ </Column>
+ </Row>
+ )}
+ {payoutMethod.wallet_address && (
+ <Row>
+ <Column className="text-sm text-neutral-600">
+ Wallet Address
+ </Column>
+ <Column className="text-right text-sm font-medium text-neutral-800">
+ {payoutMethod.wallet_address}
+ </Column>
+ </Row>
+ )}
+ </>
+ ) : (
+ <>
+ {payoutMethod.account_holder_name && (
+ <Row className="mb-2">
+ <Column className="text-sm text-neutral-600">
+ Account Holder
+ </Column>
+ <Column className="text-right text-sm font-medium text-neutral-800">
+ {payoutMethod.account_holder_name}
+ </Column>
+ </Row>
+ )}
- {payoutMethod.bank_name && (
- <Row className="mb-2">
- <Column className="text-sm text-neutral-600">
- Bank Name
- </Column>
- <Column className="text-right text-sm font-medium text-neutral-800">
- {payoutMethod.bank_name}
- </Column>
- </Row>
- )}
+ {payoutMethod.bank_name && (
+ <Row className="mb-2">
+ <Column className="text-sm text-neutral-600">
+ Bank Name
+ </Column>
+ <Column className="text-right text-sm font-medium text-neutral-800">
+ {payoutMethod.bank_name}
+ </Column>
+ </Row>
+ )}
- <Row className="mb-2">
- <Column className="text-sm text-neutral-600">
- Account Number
- </Column>
- <Column className="text-right text-sm font-medium text-neutral-800">
- •••• {payoutMethod.last4}
- </Column>
- </Row>
+ {payoutMethod.last4 && (
+ <Row className="mb-2">
+ <Column className="text-sm text-neutral-600">
+ Account Number
+ </Column>
+ <Column className="text-right text-sm font-medium text-neutral-800">
+ •••• {payoutMethod.last4}
+ </Column>
+ </Row>
+ )}
- {payoutMethod.routing_number && (
- <Row>
- <Column className="text-sm text-neutral-600">
- Routing Number
- </Column>
- <Column className="text-right text-sm font-medium text-neutral-800">
- {payoutMethod.routing_number}
- </Column>
- </Row>
+ {payoutMethod.routing_number && (
+ <Row>
+ <Column className="text-sm text-neutral-600">
+ Routing Number
+ </Column>
+ <Column className="text-right text-sm font-medium text-neutral-800">
+ {payoutMethod.routing_number}
+ </Column>
+ </Row>
+ )}
+ </>
)}
</Section>
diff --git a/packages/email/src/templates/partner-payout-confirmed.tsx b/packages/email/src/templates/partner-payout-confirmed.tsx
index 7df774c323..b6702841cf 100644
--- a/packages/email/src/templates/partner-payout-confirmed.tsx
+++ b/packages/email/src/templates/partner-payout-confirmed.tsx
@@ -14,6 +14,13 @@ import {
} from "@react-email/components";
import { addBusinessDays } from "date-fns";
import { Footer } from "../components/footer";
+import { PartnerPayoutMethod } from "../types";
+
+const PAYOUT_METHOD_LABELS: Record<PartnerPayoutMethod, string> = {
+ connect: "Stripe Express",
+ stablecoin: "USDC wallet",
+ paypal: "PayPal",
+} as const;
// Send this email when the payout is confirmed when payment is send using ACH
export default function PartnerPayoutConfirmed({
@@ -31,7 +38,7 @@ export default function PartnerPayoutConfirmed({
endDate: new Date("2024-11-30"),
mode: "internal",
paymentMethod: "ach",
- payoutMethod: "stripe",
+ payoutMethod: "connect",
},
}: {
email: string;
@@ -48,7 +55,7 @@ export default function PartnerPayoutConfirmed({
endDate?: Date | null;
mode: "internal" | "external" | null;
paymentMethod: string;
- payoutMethod: "stripe" | "paypal";
+ payoutMethod: PartnerPayoutMethod | null;
};
}) {
const payoutAmountInDollars = currencyFormatter(payout.amount);
@@ -73,6 +80,11 @@ export default function PartnerPayoutConfirmed({
const etaDays = payout.paymentMethod === "ach_fast" ? 2 : 5;
+ const payoutDestination =
+ payout.payoutMethod === null
+ ? `${program.name} account`
+ : PAYOUT_METHOD_LABELS[payout.payoutMethod];
+
return (
<Html>
<Head />
@@ -118,13 +130,7 @@ export default function PartnerPayoutConfirmed({
<Text className="text-sm leading-6 text-neutral-600">
The payout is currently being processed and is expected to be
transferred to your{" "}
- <strong className="text-black">
- {payout.mode === "external"
- ? program.name
- : payout.payoutMethod === "paypal"
- ? "PayPal"
- : "Stripe Express"}
- </strong>{" "}
+ <strong className="text-black">{payoutDestination}</strong>{" "}
account in{" "}
<strong className="text-black">{etaDays} business days</strong>{" "}
(excluding weekends and public holidays).
diff --git a/packages/email/src/templates/partner-payout-processed.tsx b/packages/email/src/templates/partner-payout-processed.tsx
index 4aa9d9976a..31550d9948 100644
--- a/packages/email/src/templates/partner-payout-processed.tsx
+++ b/packages/email/src/templates/partner-payout-processed.tsx
@@ -13,6 +13,7 @@ import {
Text,
} from "@react-email/components";
import { Footer } from "../components/footer";
+import { PartnerPayoutMethod } from "../types";
export default function PartnerPayoutProcessed({
email = "[email protected]",
@@ -22,11 +23,11 @@ export default function PartnerPayoutProcessed({
},
payout = {
id: "po_8VuCr2i7WnG65d4TNgZO19fT",
- amount: 490,
+ amount: 12000,
periodStart: new Date("2024-11-01"),
periodEnd: new Date("2024-11-30"),
+ method: "connect",
},
- variant = "stripe",
}: {
email: string;
program: {
@@ -38,8 +39,8 @@ export default function PartnerPayoutProcessed({
amount: number;
periodStart?: Date | null;
periodEnd?: Date | null;
+ method: PartnerPayoutMethod | null;
};
- variant: "stripe" | "paypal";
}) {
const payoutAmountInDollars = currencyFormatter(payout.amount, {
trailingZeroDisplay: "stripIfInteger",
@@ -63,6 +64,21 @@ export default function PartnerPayoutProcessed({
})
: null;
+ let statusMessage = "";
+
+ if (payout.method === "stablecoin") {
+ statusMessage =
+ "Your USDC has been sent to your connected crypto wallet. You should receive it within seconds.";
+ } else if (payout.method === "connect") {
+ statusMessage =
+ payout.amount >= 1000
+ ? "The funds will begin transferring to your connected bank account shortly. You will receive another email when the funds are on their way."
+ : "Since this payout is below the minimum withdrawal amount of $10, it will remain in processed status.";
+ } else if (payout.method === "paypal") {
+ statusMessage =
+ "Your payout is on its way to your PayPal account. You'll receive an email from PayPal when it's complete.";
+ }
+
return (
<Html>
<Head />
@@ -114,14 +130,10 @@ export default function PartnerPayoutProcessed({
</Section>
<Text className="text-sm leading-6 text-neutral-600">
- {variant === "stripe"
- ? payout.amount >= 1000
- ? "The funds will begin transferring to your connected bank account shortly. You will receive another email when the funds are on their way."
- : "Since this payout is below the minimum withdrawal amount of $10, it will remain in processed status."
- : "Your payout is on its way to your PayPal account. You'll receive an email from PayPal when it's complete."}
+ {statusMessage}
</Text>
- {variant === "stripe" && payout.amount < 1000 && (
+ {payout.method === "connect" && payout.amount < 1000 && (
<Text className="text-sm leading-6 text-neutral-600">
If you'd like to receive your payout right away, please{" "}
<Link
diff --git a/packages/email/src/types.ts b/packages/email/src/types.ts
index 418f9bd744..8b198ad61d 100644
--- a/packages/email/src/types.ts
+++ b/packages/email/src/types.ts
@@ -7,3 +7,5 @@ export type WorkspaceProps = {
plan: string;
defaultProgramId: string | null;
};
+
+export type PartnerPayoutMethod = "connect" | "stablecoin" | "paypal";
diff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prisma
index 5aa09da024..75f0f9cf80 100644
--- a/packages/prisma/schema/partner.prisma
+++ b/packages/prisma/schema/partner.prisma
@@ -16,6 +16,12 @@ enum MonthlyTraffic {
OneHundredThousandPlus
}
+enum PartnerPayoutMethod {
+ connect
+ stablecoin
+ paypal
+}
+
model Partner {
id String @id @default(cuid())
name String
@@ -27,11 +33,14 @@ model Partner {
country String?
// payout fields
- paypalEmail String? @unique
- stripeConnectId String? @unique
+ defaultPayoutMethod PartnerPayoutMethod?
payoutsEnabledAt DateTime?
- payoutMethodHash String?
connectPayoutsLastRemindedAt DateTime?
+ paypalEmail String? @unique
+ stripeConnectId String? @unique
+ stripeRecipientId String? @unique
+ payoutMethodHash String?
+ cryptoWalletAddress String?
// timestamp fields
createdAt DateTime @default(now())
@@ -148,4 +157,4 @@ model PartnerSalesChannel {
partner Partner @relation(fields: [partnerId], references: [id], onDelete: Cascade)
@@unique([partnerId, salesChannel])
-}
\ No newline at end of file
+}
diff --git a/packages/prisma/schema/payout.prisma b/packages/prisma/schema/payout.prisma
index 6464c867b5..67bbb74bfb 100644
--- a/packages/prisma/schema/payout.prisma
+++ b/packages/prisma/schema/payout.prisma
@@ -14,25 +14,26 @@ enum PayoutMode {
}
model Payout {
- id String @id @default(cuid())
+ id String @id @default(cuid())
programId String
partnerId String
invoiceId String?
- amount Int @default(0)
- currency String @default("USD")
- status PayoutStatus @default(pending)
+ amount Int @default(0)
+ currency String @default("USD")
+ status PayoutStatus @default(pending)
mode PayoutMode?
+ method PartnerPayoutMethod?
description String?
periodStart DateTime?
periodEnd DateTime?
- paypalTransferId String? @unique
+ paypalTransferId String? @unique
stripeTransferId String?
stripePayoutId String?
- stripePayoutTraceId String? @db.Text
- failureReason String? @db.Text
- webhookEventId String? @unique // only for external payouts
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ stripePayoutTraceId String? @db.Text
+ failureReason String? @db.Text
+ webhookEventId String? @unique // only for external payouts
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
userId String? // user who made the payout
initiatedAt DateTime?
@@ -50,6 +51,7 @@ model Payout {
@@index(partnerId)
@@index(invoiceId)
@@index(status)
+ @@index(method)
@@index(userId)
@@index(stripePayoutId)
@@index(stripeTransferId)
diff --git a/packages/ui/src/icons/index.tsx b/packages/ui/src/icons/index.tsx
index 2f8357b569..9808223e0c 100644
--- a/packages/ui/src/icons/index.tsx
+++ b/packages/ui/src/icons/index.tsx
@@ -55,6 +55,7 @@ export * from "./payment-platforms/card-discover";
export * from "./payment-platforms/card-mastercard";
export * from "./payment-platforms/card-visa";
export * from "./payment-platforms/paypal";
+export * from "./payment-platforms/stablecoin";
export * from "./payment-platforms/stripe-icon";
export * from "./payment-platforms/stripe-link";
diff --git a/packages/ui/src/icons/nucleo/circle-dollar3.tsx b/packages/ui/src/icons/nucleo/circle-dollar3.tsx
new file mode 100644
index 0000000000..774041b607
--- /dev/null
+++ b/packages/ui/src/icons/nucleo/circle-dollar3.tsx
@@ -0,0 +1,29 @@
+import { SVGProps } from "react";
+
+export function CircleDollar3(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <path
+ d="M12.9999 2.52161C15.9631 3.71143 18.0554 6.61141 18.0554 10C18.0554 13.3886 15.9631 16.2886 12.9999 17.4784M6.9999 2.52161C4.03666 3.71143 1.94434 6.61141 1.94434 10C1.94434 13.3886 4.03665 16.2886 6.99988 17.4784"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M11.9445 6.94459H9.30539C8.46172 6.94459 7.77783 7.62847 7.77783 8.47214C7.77783 9.31581 8.46172 10.0001 9.30539 10.0001H10.6946C11.5383 10.0001 12.2222 10.684 12.2222 11.5277C12.2222 12.3714 11.5383 13.0554 10.6946 13.0554H8.0555M9.99994 5.83325V6.94459M9.99994 14.1666V13.0555"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ );
+}
diff --git a/packages/ui/src/icons/nucleo/index.ts b/packages/ui/src/icons/nucleo/index.ts
index bddcac4c3e..eacb7be190 100644
--- a/packages/ui/src/icons/nucleo/index.ts
+++ b/packages/ui/src/icons/nucleo/index.ts
@@ -49,6 +49,7 @@ export * from "./circle-check";
export * from "./circle-check-fill";
export * from "./circle-dollar";
export * from "./circle-dollar-out";
+export * from "./circle-dollar3";
export * from "./circle-dotted";
export * from "./circle-half-dotted-check";
export * from "./circle-half-dotted-clock";
diff --git a/packages/ui/src/icons/payment-platforms/stablecoin.tsx b/packages/ui/src/icons/payment-platforms/stablecoin.tsx
new file mode 100644
index 0000000000..14f3198463
--- /dev/null
+++ b/packages/ui/src/icons/payment-platforms/stablecoin.tsx
@@ -0,0 +1,103 @@
+import { cn } from "@dub/utils";
+
+export function Stablecoin({ className }: { className?: string }) {
+ return (
+ <svg
+ viewBox="0 0 74 74"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ className={cn("h-full w-full", className)}
+ >
+ <g filter="url(#filter0_dii_46872_4505)">
+ <circle cx={37} cy={35} r={35} fill="#155DFC" />
+ </g>
+ <path
+ d="M46.5449 11.2051C55.9734 14.9909 62.6308 24.2182 62.6308 35.0001C62.6308 45.7819 55.9734 55.0091 46.545 58.7949M27.4541 11.2051C18.0256 14.9909 11.3682 24.2182 11.3682 35.0001C11.3682 45.7819 18.0255 55.0091 27.454 58.7949"
+ stroke="white"
+ strokeWidth={4.77273}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M43.1873 25.2782H34.7901C32.1057 25.2782 29.9297 27.4543 29.9297 30.1387C29.9297 32.823 32.1057 35.0005 34.7901 35.0005H39.2103C41.8947 35.0005 44.0707 37.1765 44.0707 39.8608C44.0707 42.5452 41.8947 44.7216 39.2103 44.7216H30.8132M37 21.7422V25.2782M37 48.2573V44.722"
+ stroke="white"
+ strokeWidth={4.77273}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <defs>
+ <filter
+ id="filter0_dii_46872_4505"
+ x={0}
+ y={-3}
+ width={74}
+ height={77}
+ filterUnits="userSpaceOnUse"
+ colorInterpolationFilters="sRGB"
+ >
+ <feFlood floodOpacity={0} result="BackgroundImageFix" />
+ <feColorMatrix
+ in="SourceAlpha"
+ type="matrix"
+ values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
+ result="hardAlpha"
+ />
+ <feOffset dy={2} />
+ <feGaussianBlur stdDeviation={1} />
+ <feComposite in2="hardAlpha" operator="out" />
+ <feColorMatrix
+ type="matrix"
+ values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.08 0"
+ />
+ <feBlend
+ mode="normal"
+ in2="BackgroundImageFix"
+ result="effect1_dropShadow_46872_4505"
+ />
+ <feBlend
+ mode="normal"
+ in="SourceGraphic"
+ in2="effect1_dropShadow_46872_4505"
+ result="shape"
+ />
+ <feColorMatrix
+ in="SourceAlpha"
+ type="matrix"
+ values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
+ result="hardAlpha"
+ />
+ <feOffset dy={-3} />
+ <feGaussianBlur stdDeviation={5} />
+ <feComposite in2="hardAlpha" operator="arithmetic" k2={-1} k3={1} />
+ <feColorMatrix
+ type="matrix"
+ values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"
+ />
+ <feBlend
+ mode="normal"
+ in2="shape"
+ result="effect2_innerShadow_46872_4505"
+ />
+ <feColorMatrix
+ in="SourceAlpha"
+ type="matrix"
+ values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
+ result="hardAlpha"
+ />
+ <feOffset dy={4} />
+ <feGaussianBlur stdDeviation={3} />
+ <feComposite in2="hardAlpha" operator="arithmetic" k2={-1} k3={1} />
+ <feColorMatrix
+ type="matrix"
+ values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.25 0"
+ />
+ <feBlend
+ mode="normal"
+ in2="effect2_innerShadow_46872_4505"
+ result="effect3_innerShadow_46872_4505"
+ />
+ </filter>
+ </defs>
+ </svg>
+ );
+}
diff --git a/packages/utils/src/constants/index.ts b/packages/utils/src/constants/index.ts
index 17def2340c..3293e8497e 100644
--- a/packages/utils/src/constants/index.ts
+++ b/packages/utils/src/constants/index.ts
@@ -16,6 +16,7 @@ export * from "./paypal-supported-countries";
export * from "./regions";
export * from "./reserved-slugs";
export * from "./saml";
+export * from "./stablecoin-supported-countries";
// pricing copy & values
export * from "./pricing/pricing-plan-compare-features";
diff --git a/packages/utils/src/constants/paypal-supported-countries.ts b/packages/utils/src/constants/paypal-supported-countries.ts
index 41040cf3a2..a82ef24e5c 100644
--- a/packages/utils/src/constants/paypal-supported-countries.ts
+++ b/packages/utils/src/constants/paypal-supported-countries.ts
@@ -1,7 +1,7 @@
import { CONNECT_SUPPORTED_COUNTRIES } from "./connect-supported-countries";
// @see: https://developer.paypal.com/docs/payouts/standard/reference/country-feature
-export const PAYPAL_SUPPORTED_COUNTRIES_FULL = [
+const PAYPAL_SUPPORTED_COUNTRIES_FULL = [
"AD", // Andorra
"AR", // Argentina
"AU", // Australia
diff --git a/packages/utils/src/constants/stablecoin-supported-countries.ts b/packages/utils/src/constants/stablecoin-supported-countries.ts
new file mode 100644
index 0000000000..22ce53e8b2
--- /dev/null
+++ b/packages/utils/src/constants/stablecoin-supported-countries.ts
@@ -0,0 +1,160 @@
+export const STABLECOIN_SUPPORTED_COUNTRIES = [
+ "AD", // Andorra
+ "AE", // United Arab Emirates
+ "AG", // Antigua and Barbuda
+ "AM", // Armenia
+ "AO", // Angola
+ "AR", // Argentina
+ "AT", // Austria
+ "AU", // Australia
+ "AZ", // Azerbaijan
+ "BA", // Bosnia and Herzegovina
+ "BB", // Barbados
+ "BE", // Belgium
+ "BG", // Bulgaria
+ "BH", // Bahrain
+ "BJ", // Benin
+ "BN", // Brunei Darussalam
+ "BR", // Brazil
+ "BS", // Bahamas
+ "BT", // Bhutan
+ "BW", // Botswana
+ "BZ", // Belize
+ "CA", // Canada
+ "CH", // Switzerland
+ "CI", // Côte d'Ivoire
+ "CL", // Chile
+ "CM", // Cameroon
+ "CO", // Colombia
+ "CR", // Costa Rica
+ "CV", // Cabo Verde
+ "CY", // Cyprus
+ "CZ", // Czech Republic
+ "DE", // Germany
+ "DJ", // Djibouti
+ "DK", // Denmark
+ "DM", // Dominica
+ "DO", // Dominican Republic
+ "EC", // Ecuador
+ "EE", // Estonia
+ "EG", // Egypt
+ "ES", // Spain
+ "FI", // Finland
+ "FJ", // Fiji
+ "FM", // Micronesia
+ "FR", // France
+ "GA", // Gabon
+ "GB", // United Kingdom
+ "GG", // Guernsey
+ "GH", // Ghana
+ "GI", // Gibraltar
+ "GM", // Gambia
+ "GN", // Guinea
+ "GQ", // Equatorial Guinea
+ "GR", // Greece
+ "GT", // Guatemala
+ "GW", // Guinea-Bissau
+ "GY", // Guyana
+ "HK", // Hong Kong
+ "HN", // Honduras
+ "HR", // Croatia
+ "HT", // Haiti
+ "HU", // Hungary
+ "ID", // Indonesia
+ "IE", // Ireland
+ "IL", // Israel
+ "IM", // Isle of Man
+ "IS", // Iceland
+ "IT", // Italy
+ "JE", // Jersey
+ "JM", // Jamaica
+ "JO", // Jordan
+ "JP", // Japan
+ "KE", // Kenya
+ "KG", // Kyrgyzstan
+ "KH", // Cambodia
+ "KI", // Kiribati
+ "KM", // Comoros
+ "KN", // Saint Kitts and Nevis
+ "KR", // Korea, Republic of
+ "KW", // Kuwait
+ "KY", // Cayman Islands
+ "KZ", // Kazakhstan
+ "LA", // Lao PDR
+ "LC", // Saint Lucia
+ "LI", // Liechtenstein
+ "LK", // Sri Lanka
+ "LR", // Liberia
+ "LS", // Lesotho
+ "LT", // Lithuania
+ "LU", // Luxembourg
+ "LV", // Latvia
+ "MA", // Morocco
+ "MC", // Monaco
+ "MD", // Moldova
+ "ME", // Montenegro
+ "MG", // Madagascar
+ "MN", // Mongolia
+ "MR", // Mauritania
+ "MT", // Malta
+ "MU", // Mauritius
+ "MV", // Maldives
+ "MW", // Malawi
+ "MX", // Mexico
+ "MY", // Malaysia
+ "MZ", // Mozambique
+ "NA", // Namibia
+ "NG", // Nigeria
+ "NL", // Netherlands
+ "NO", // Norway
+ "NR", // Nauru
+ "NZ", // New Zealand
+ "OM", // Oman
+ "PA", // Panama
+ "PE", // Peru
+ "PG", // Papua New Guinea
+ "PH", // Philippines
+ "PL", // Poland
+ "PT", // Portugal
+ "PW", // Palau
+ "PY", // Paraguay
+ "QA", // Qatar
+ "RO", // Romania
+ "RS", // Serbia
+ "RW", // Rwanda
+ "SA", // Saudi Arabia
+ "SB", // Solomon Islands
+ "SC", // Seychelles
+ "SE", // Sweden
+ "SG", // Singapore
+ "SI", // Slovenia
+ "SK", // Slovakia
+ "SL", // Sierra Leone
+ "SM", // San Marino
+ "SN", // Senegal
+ "SR", // Suriname
+ "ST", // Sao Tome and Principe
+ "SV", // El Salvador
+ "SZ", // Eswatini
+ "TG", // Togo
+ "TH", // Thailand
+ "TJ", // Tajikistan
+ "TL", // Timor-Leste
+ "TM", // Turkmenistan
+ "TO", // Tonga
+ "TR", // Turkey
+ "TT", // Trinidad and Tobago
+ "TV", // Tuvalu
+ "TZ", // Tanzania
+ "UG", // Uganda
+ "US", // United States
+ "UY", // Uruguay
+ "UZ", // Uzbekistan
+ "VA", // Holy See
+ "VC", // St. Vincent & Grenadines
+ "VN", // Viet Nam
+ "VU", // Vanuatu
+ "WS", // Samoa
+ "ZA", // South Africa
+ "ZM", // Zambia
+];