Skip to content

Add Stripe Connect Express payouts (bank + instant debit card) - #66

Merged
Gajesh2007 merged 2 commits into
masterfrom
feature/stripe-payouts
Apr 22, 2026
Merged

Gajesh2007 merged 2 commits into
masterfrom
feature/stripe-payouts

Conversation

@Gajesh2007

Copy link
Copy Markdown
Member

Summary

  • New withdrawal rail: users can link a bank account or debit card via Stripe-hosted onboarding and withdraw their internal credit balance — Standard ACH (1-2 business days, free) or Instant to debit card (~30 min, 1.5% fee, $0.50 min). Fees are deducted from the gross.
  • Coordinator gains a Stripe Connect Express client, persist-first state machine for withdrawals (pending → transferred → paid), idempotent webhook handling, and Postgres schema for the new stripe_withdrawals table + Stripe fields on users.
  • Console UI gains a StripePayoutsCard + StripeWithdrawModal on the Billing page, four proxy routes, and an integer-cent fee helper that mirrors the server formula exactly.

Why this design

  • Persist before any Stripe call. Eliminates the failure mode where a DB write could fail after Stripe already moved money. State transitions only update an existing row.
  • Refund idempotency keyed on Refunded flag, not Status. A partial-refund failure can be retried on webhook redelivery without manually clearing state.
  • Webhook secret required in non-mock mode. Refusing to verify (rather than parse-without-verify) closes a vector where a stolen po_… ID could trigger an unsigned payout.failed and inject a ledger refund.
  • return_url allowlist anchored on operator-configured default. Blocks open-redirect via crafted onboard requests.
  • Express requests both transfers and card_payments capabilities. Caught in live test-mode validation: Stripe rejects transfers-only without pre-approval. Adding card_payments is cosmetic — we never call charges.

Validation

  • 33 new Go tests (handler lifecycle, fee math, signature verification rejecting empty secrets in prod, redirect allowlist, persist-first ordering, idempotent webhooks, Postgres CRUD).
  • 16 new vitest cases (fee helper parity with the server formula, proxy URL shape, error surfacing).
  • Full coordinator suite (~600 cases) and console-ui build still pass.
  • Live test-mode validation via stripe listen + stripe trigger: real signed account.updated webhook delivered through to the handler, signature verified, event parsed, 200 returned. Direct accounts.create and account_links.create calls against live test-mode Stripe both succeed.
  • Independent code review (general-purpose subagent) caught 6 issues pre-merge; all fixed before commit.

New env vars (all optional — feature activates when EIGENINFERENCE_STRIPE_SECRET_KEY is set)

  • EIGENINFERENCE_STRIPE_CONNECT_WEBHOOK_SECRET — required in non-mock prod
  • EIGENINFERENCE_STRIPE_CONNECT_COUNTRY (default: US)
  • EIGENINFERENCE_STRIPE_CONNECT_RETURN_URL
  • EIGENINFERENCE_STRIPE_CONNECT_REFRESH_URL

Test plan

  • Confirm Stripe Connect is enabled on the production account before merging
  • Set the four new env vars in EigenCloud (test secret key first, then live)
  • Create the production webhook endpoint pointing at /v1/billing/stripe/connect/webhook with events: account.updated, payout.paid, payout.failed, payout.canceled
  • Run a real round-trip in test mode: onboard a fake user, withdraw $1 to a test bank account, verify webhook flips status to paid
  • Verify the withdraw row gets refunded when a real payout.failed is triggered
  • Confirm the Stripe USD float strategy (Stripe Checkout deposits as float) is in place before high-volume launch

Stands up a parallel dev environment on GCP (project sepolia-ai) that mirrors
prod's trust/MDM semantics so the full attestation chain is exercised before
changes hit EigenCloud.

Shape: GCE Ubuntu VM + Docker + systemd running the coordinator + step-ca +
MicroMDM container, with a 30 GB persistent disk at /mnt/disks/userdata (same
path prod uses on EigenCloud). Cloud SQL Postgres via cloud-sql-proxy sidecar.
Console UI on Vercel. Cloud Build auto-deploys on master push (~2-4 min per
coordinator deploy).

Parameterization so dev and prod share source but never artifacts:
- provider/build.rs emits DARKBLOOM_COORDINATOR_URL and DARKBLOOM_R2_CDN_URL
  as compile-time constants; 17 hardcoded URL sites in provider/src/main.rs
  now use option_env! fallbacks.
- Coordinator templates install.sh at serve time (__DARKBLOOM_COORD_URL__,
  __DARKBLOOM_R2_CDN_URL__, __DARKBLOOM_R2_SITE_PACKAGES_CDN_URL__) via
  new SetBaseURL/SetR2CDNURL/SetR2SitePackagesCDNURL setters. 5-subtest
  regression in install_sh_test.go.
- release.yml adds workflow_dispatch + environment input + resolve-env job
  (routes dev/prod by tag shape vX.Y.Z-dev.N OR explicit input); R2_BUCKET
  and R2_CDN come from per-env GitHub Variables; DARKBLOOM_COORDINATOR_URL
  and DARKBLOOM_R2_CDN_URL are baked into the Rust build per environment.

Ops tooling:
- deploy/gcp/bootstrap.sh: one-shot provisioning (APIs, Artifact Registry,
  Secret Manager with placeholder secrets, service account + IAM, Cloud SQL,
  30 GB persistent disk, firewall, static IP, Ubuntu VM with startup script,
  Cloud Build SA IAP/compute permissions).
- deploy/gcp/vm-startup.sh: idempotent VM boot script. Installs gcloud + Docker
  + cloud-sql-proxy in the right order (gcloud first — Ubuntu 24.04 ships
  without it). Mounts data disk. Fetches secrets from Secret Manager.
  Writes systemd units for cloud-sql-proxy and the coordinator (with an image-
  tag-from-metadata wrapper so Cloud Build can pin a SHA per deploy).
- deploy/gcp/cloudbuild.yaml: docker build + push to Artifact Registry + SSH
  via IAP + systemctl restart + /health poll.
- deploy/provider-fleet/{dev,prod}-inventory.txt + update-fleet.sh: fleet SSH
  update helper (dev default; prod guarded by --force-prod).
- scripts/smoke-dev.sh: post-deploy smoke (health, stats, catalog, install.sh
  templating sanity, optional authenticated chat).

Docs:
- docs/dev-environment.md: full runbook (bootstrap, secrets, DNS on Vercel
  Domains, Vercel console setup, Cloud Build wiring, rollback, cost).
- CLAUDE.md Infrastructure table updated with real GCP values.
- AGENTS.md and docs/ARCHITECTURE.md no longer claim AWS.

Dev uses a new Privy app, new BIP39 mnemonic on mainnet Solana, and its own
R2 bucket (d-inf-app-dev). MIN_TRUST=hardware matches prod so MDM and
attestation paths are exercised end-to-end.
Users can now link a bank account or debit card via Stripe-hosted
onboarding and withdraw their Darkbloom credit balance. Standard ACH
arrives in 1-2 business days at no cost; Instant Payouts to debit cards
arrive in ~30 minutes for a 1.5% fee ($0.50 minimum) deducted from the
gross.

Coordinator:
  * billing/stripe_connect.go: Express accounts, account links,
    transfers, payouts, Connect-webhook signature verification, mock
    mode for dev.
  * api/stripe_payouts.go: handlers for onboard, status, withdraw,
    list, and Connect webhook. Persist-first state machine (pending ->
    transferred -> paid) eliminates the double-spend window where a DB
    write could fail after Stripe moved money. Refunded flag (not
    Status) keys idempotency so a partial-refund failure can retry on
    webhook redelivery. Connect webhook secret is required in non-mock
    mode; we refuse to verify rather than fall back to parse-without-
    verify, closing a ledger-refund-injection vector. return_url and
    refresh_url are validated against the operator-configured default
    host (localhost always allowed) to block open-redirect.
  * store: User gains StripeAccount{ID,Status,DestinationType,Last4,
    InstantEligible}; new stripe_withdrawals table with full CRUD on
    both memory and Postgres backends. Postgres migrations are
    idempotent (IF NOT EXISTS / DO ... EXCEPTION blocks).
  * Express accounts request both `transfers` and `card_payments`
    capabilities -- Stripe rejects transfers-only requests without
    pre-approval, even though we only ever use transfers + payouts.

Console UI:
  * Billing page: StripePayoutsCard surfaces onboarding, ready-state,
    destination chip, and recent withdrawals. StripeWithdrawModal
    previews fee + net using integer-cent math that mirrors the server.
  * Four new proxy routes under /api/payments/stripe/{onboard,status,
    withdrawals} and /api/payments/withdraw/stripe; all forward the
    Privy session token via the cookie fallback so the UI works without
    an API key configured.

Tests: 33 new Go cases (handler lifecycle, fee math, signature
verification rejecting empty secrets in prod, redirect allowlist,
persist-first ordering, idempotent webhooks, Postgres CRUD) and 16
vitest cases (fee helper parity with the server formula, proxy URL
shape, error surfacing).

Validated end-to-end against live test-mode Stripe via the CLI:
accounts.create, account_links.create, real signed webhook delivery
all round-trip cleanly through the handlers.

Env vars added (all optional; activate by setting the secret key):
  EIGENINFERENCE_STRIPE_CONNECT_WEBHOOK_SECRET
  EIGENINFERENCE_STRIPE_CONNECT_COUNTRY (default: US)
  EIGENINFERENCE_STRIPE_CONNECT_RETURN_URL
  EIGENINFERENCE_STRIPE_CONNECT_REFRESH_URL
@vercel

vercel Bot commented Apr 19, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Apr 19, 2026 0:01am
d-inference-landing Ready Ready Preview Apr 19, 2026 0:01am

Request Review

@Gajesh2007
Gajesh2007 merged commit 81ff77b into master Apr 22, 2026
10 checks passed
Gajesh2007 added a commit that referenced this pull request Jul 5, 2026
…66 + CBv2 vision prefill #63)

provider-swift full suite against the new pin: 1,340 tests / 115 suites, all
pass (clean rebuild; the transient SIGSEGV during iteration was a stale
incremental-build artifact from cross-pin object files, gone after a clean
build with mlx.metallib restored).

Co-authored-by: Cursor <cursoragent@cursor.com>
Gajesh2007 added a commit that referenced this pull request Jul 5, 2026
… test follow-ups)

Co-authored-by: Cursor <cursoragent@cursor.com>
Gajesh2007 added a commit that referenced this pull request Jul 5, 2026
… fused-cache removal (#516)

* provider: drop fused-MoE-cache accounting; pin mlx-swift-lm to the fused-cache removal

mlx-swift-lm (Layr-Labs/mlx-swift-lm#66) deletes SwitchGLU's runtime
fused gate+up cache — the full second copy of the MoE gate/up expert
weights (7.98 GiB qat-4bit / 15.07 GiB 8bit always-resident) whose only
active shape was B=1 solo decode at ~0% measured win, and the root cause
of the v0.7.3 black-hole incident. With the cache gone the provider's
fused-byte accounting has nothing to measure, so the special-casing is
deleted rather than left reading a structural zero:

- EngineV2VLMTextExtraction: no more cross-tree cache sharing
  (shareMoEFusedCaches) or fusedMoECacheBytes measurement; Extraction
  carries only the model + parity diff.
- EngineV2KVSizing.netOfEngineResidentOverhead deleted — the v2 KV
  ceiling is the weights-derived grant, nothing netted out (PR#508
  finding 2 no longer has a subject). The 8–15 GiB return to KV /
  admission headroom automatically.
- ModelSlot.engineResidentOverheadBytes deleted; the co-resident
  residency sums (later engine ceilings, heartbeat fleet clamp) are
  plain weight sums again. The post-engine-build serveable-KV headroom
  re-check (unload + 503, never black-hole) stays — it guards any
  load-time growth, not just the removed cache.
- Tests: EngineV2FusedCacheCapacityTests deleted (its subject is gone);
  the two Gemma VLM live tests now pin the STRONGER invariant that the
  extraction + parity probe retain (almost) nothing beyond the shared
  weights, and that the weights-derived v2 ceiling equals the shared
  gate's headroom with nothing netted.

Parity re-run on this pin (M4 Max, qat-4bit, BenchCBv2 v2-compiled, 256
steps): B=1 104.6-107.1 TPS/req, B=2 69.9-70.3 TPS/req, gpuActive
13.48 GiB (fused-ON baseline 21.45 GiB).

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: pin mlx-swift-lm to merged main (bc6eb9b — fused-cache removal #66 + CBv2 vision prefill #63)

provider-swift full suite against the new pin: 1,340 tests / 115 suites, all
pass (clean rebuild; the transient SIGSEGV during iteration was a stale
incremental-build artifact from cross-pin object files, gone after a clean
build with mlx.metallib restored).

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: size the capacity regression from scheduler weights (Codex P2)

The step-4 consistency check passed live MLX usage as newModelWeightBytes,
making ceiling == headroom tautological. It now uses
scheduler.modelWeightBytes — the exact input production
makeEngineV2BridgeForSlot passes — so any non-weight state retained by
extraction/probe shows up as ceiling-over-headroom divergence, bounded by
the same 2 GiB retained-state bar as step 1 (plus a 64 MiB rounding guard
in the impossible direction). Verified live on the 8bit checkpoint:
ceiling 28.57 GiB vs headroom 28.56 GiB, retained overhead 0.00 GiB.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: pin mlx-swift-lm to current main HEAD bc1c0ee (#66 removal + #67 test follow-ups)

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Gajesh2007 added a commit that referenced this pull request Jul 5, 2026
…GiB reclaimed per MoE box)

The SwitchGLU runtime fused gate+up cache held a full second copy of the
MoE expert weights (~15 GiB on gemma-4-26b-8bit, ~8 GiB on qat-4bit) for a
decode benefit measured at ~0%, confined to B=1 solo decode — batched
decode and prefill never used it. Deleting it (mlx-swift-lm #66/#67,
d-inference #516) returns those bytes to KV/admission headroom
automatically via the weights-derived v2 ceiling.

Also rides in this pin: dormant CBv2 vision-prefill engine support
(mlx-swift-lm #63) — activates with the upcoming multimodal provider
release; text serving is byte-identical.

LatestProviderVersion fallback bumped in lockstep.

Co-authored-by: Cursor <cursoragent@cursor.com>
cursor Bot pushed a commit that referenced this pull request Jul 10, 2026
MemoryLedger.adopt_fencing_epoch + POST /v1/admin/adopt-job so orphaned
jobs can be recovered/force-settled after ownership steal. Stream wait
ownership-steal oneshot; shared watch_ownership_lost helper.

This branch was successfully deployed

2 active deployments
Preview – d-inference — 6b1489b8 Deployed Apr 19, 2026 by vercel[bot]
Preview – d-inference-landing — 6b1489b8 Deployed Apr 19, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant