Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/keychain/src/components/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import { hasApprovalPolicies } from "@/hooks/session";
import { PurchaseStarterpack } from "./purchasenew/starterpack/starterpack";
import { Quests } from "./quests";
import { QuestClaim } from "./quests/claim";
import { CoinbasePopup } from "./coinbase-popup";

function DefaultRoute() {
const account = useAccount();
Expand Down Expand Up @@ -233,6 +234,7 @@ export function App() {
return (
<Routes>
<Route path="/booster-pack/:privateKey" element={<BoosterPack />} />
<Route path="/coinbase" element={<CoinbasePopup />} />
<Route path="/" element={<Authentication />}>
<Route index element={<DefaultRoute />} />
<Route path="/settings" element={<Settings />} />
Expand Down
145 changes: 145 additions & 0 deletions packages/keychain/src/components/coinbase-popup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { useState, useEffect, useRef, useCallback } from "react";
import { useSearchParams } from "react-router-dom";
import { SpinnerIcon, TimesIcon } from "@cartridge/ui";
import {
CoinbaseOnRampOrderDocument,
CoinbaseOnRampOrderQuery,
CoinbaseOnrampStatus,
} from "@cartridge/ui/utils/api/cartridge";
import { request } from "@/utils/graphql";

/** Polling interval for checking order status (1 second for responsive UX) */
const POLL_INTERVAL_MS = 1_000;
/** Timeout for the payment (10 minutes) */
const PAYMENT_TIMEOUT_MS = 10 * 60 * 1000;

/**
* Standalone page rendered at /coinbase in the keychain app.
* Opened as a popup from the CoinbaseCheckout component.
*
* - Embeds the Coinbase payment link in an iframe (works because
* the top-level domain is x.cartridge.gg)
* - Polls the order status via GraphQL
* - Closes the popup automatically on success
* - Shows failure message if payment fails or times out
*/
export function CoinbasePopup() {
const [searchParams] = useSearchParams();
const paymentLink = searchParams.get("paymentLink");
const orderId = searchParams.get("orderId");

const [iframeLoaded, setIframeLoaded] = useState(false);
const [status, setStatus] = useState<CoinbaseOnrampStatus | undefined>();
const [error, setError] = useState<string | undefined>();

const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const pollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

const stopPolling = useCallback(() => {
if (pollIntervalRef.current) {
clearInterval(pollIntervalRef.current);
pollIntervalRef.current = null;
}
if (pollTimeoutRef.current) {
clearTimeout(pollTimeoutRef.current);
pollTimeoutRef.current = null;
}
}, []);

// Start polling when we have an orderId
useEffect(() => {
if (!orderId) return;

const poll = async () => {
try {
const result = await request<CoinbaseOnRampOrderQuery>(
CoinbaseOnRampOrderDocument,
{ orderId },
);
const orderStatus = result.coinbaseOnrampOrder.status;
setStatus(orderStatus);

if (orderStatus === CoinbaseOnrampStatus.Completed) {
stopPolling();
// Brief delay so the user sees the success state before auto-close
setTimeout(() => window.close(), 1500);
} else if (orderStatus === CoinbaseOnrampStatus.Failed) {
stopPolling();
setError("Payment failed. You can close this window and try again.");
}
} catch (err) {
console.error("Failed to poll order status:", err);
// Don't stop polling on transient errors
}
};

// Immediate first poll
poll();

// Subsequent polls
pollIntervalRef.current = setInterval(poll, POLL_INTERVAL_MS);

// Timeout
pollTimeoutRef.current = setTimeout(() => {
stopPolling();
setError("Payment timed out. Please close this window and try again.");
setStatus(CoinbaseOnrampStatus.Failed);
}, PAYMENT_TIMEOUT_MS);

return () => stopPolling();
}, [orderId, stopPolling]);

if (!paymentLink || !orderId) {
return (
<div className="flex items-center justify-center h-screen bg-[#0F1410] text-foreground-300">
<p>Missing payment information.</p>
</div>
);
}

const isCompleted = status === CoinbaseOnrampStatus.Completed;
const isFailed = status === CoinbaseOnrampStatus.Failed;

return (
<div className="flex flex-col h-screen bg-[#0F1410]">
{/* Status bar */}
{(isCompleted || isFailed) && (
<div
className={`flex items-center justify-center gap-2 px-4 py-3 text-sm font-medium ${
isCompleted
? "bg-[#1a2e1a] text-[#4ade80]"
: "bg-[#2e1a1a] text-[#f87171]"
}`}
>
{isCompleted ? (
<>
<span>✓</span>
<span>Payment successful! This window will close shortly.</span>
</>
) : (
<>
<TimesIcon size="sm" />
<span>{error}</span>
</>
)}
</div>
)}

{/* Iframe */}
<div className="flex-1 relative">
{!iframeLoaded && (
<div className="absolute inset-0 flex items-center justify-center bg-[#0F1410] z-10">
<SpinnerIcon className="animate-spin" size="lg" />
</div>
)}
<iframe
src={paymentLink}
className="h-full w-full border-none"
allow="payment"
title="Coinbase Onramp"
onLoad={() => setIframeLoaded(true)}
/>
</div>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export function BridgePending({
const waitForDeposit = waitForDepositProp ?? onchainContext.waitForDeposit;
const onOnchainPurchase = onchainContext.onOnchainPurchase;
const orderStatus = onchainContext.orderStatus;
const orderTxHash = onchainContext.orderTxHash;

const [initialBridgeHash, setInitialBridgeHash] = useState(bridgeTxHash);

Expand Down Expand Up @@ -235,8 +236,8 @@ export function BridgePending({
: "Bridging to Starknet"
}
externalLink={
initialBridgeHash
? `https://layerswap.io/explorer/${initialBridgeHash}`
orderTxHash || initialBridgeHash
? `https://layerswap.io/explorer/${orderTxHash || initialBridgeHash}`
: undefined
}
isLoading={!paymentCompleted}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ const MockOnchainPurchaseProvider = ({ children }: { children: ReactNode }) => {
stopPolling: () => {},
orderId: undefined,
orderStatus: undefined,
orderTxHash: undefined,
isPollingOrder: false,
getTransactions: async () => [],
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ const mockOnchainPurchaseValue: OnchainPurchaseContextType = {
stopPolling: () => {},
orderId: undefined,
orderStatus: undefined,
orderTxHash: undefined,
isPollingOrder: false,
getTransactions: async () => [],
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export interface OnchainPurchaseContextType {
isFetchingCoinbaseQuote: boolean;
orderId: string | undefined;
orderStatus: CoinbaseOnrampStatus | undefined;
orderTxHash: string | undefined;
isPollingOrder: boolean;

// Actions
Expand Down Expand Up @@ -216,6 +217,7 @@ export const OnchainPurchaseProvider = ({
isFetchingQuote: isFetchingCoinbaseQuote,
isPollingOrder,
orderStatus,
orderTxHash,
openPaymentPopup,
stopPolling,
} = useCoinbase({
Expand Down Expand Up @@ -539,6 +541,7 @@ export const OnchainPurchaseProvider = ({
isFetchingCoinbaseQuote,
orderId,
orderStatus,
orderTxHash,
isPollingOrder,
onOnchainPurchase,
onExternalConnect,
Expand Down
27 changes: 21 additions & 6 deletions packages/keychain/src/hooks/starterpack/coinbase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export interface UseCoinbaseReturn {
isFetchingQuote: boolean;
isPollingOrder: boolean;
orderStatus: CoinbaseOnrampStatus | undefined;
orderTxHash: string | undefined;

// Actions
createOrder: (input: CreateOrderInput) => Promise<CoinbaseOrderResult>;
Expand Down Expand Up @@ -140,6 +141,7 @@ export function useCoinbase({
const [orderStatus, setOrderStatus] = useState<
CoinbaseOnrampStatus | undefined
>();
const [orderTxHash, setOrderTxHash] = useState<string | undefined>();

// Refs for managing the polling lifecycle
const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
Expand Down Expand Up @@ -173,6 +175,10 @@ export function useCoinbase({
const result = await getCoinbaseOrderStatus(targetOrderId);
setOrderStatus(result.status);

if (result.txHash) {
setOrderTxHash(result.txHash);
}

// Terminal states – stop polling
if (
result.status === CoinbaseOnrampStatus.Completed ||
Expand Down Expand Up @@ -209,29 +215,36 @@ export function useCoinbase({
const openPaymentPopup = useCallback(() => {
if (!paymentLink || !orderId) return;

// Open a centered popup (use screen dimensions since we're inside an iframe)
// Build the keychain-hosted coinbase page URL
// The popup runs at the keychain origin (x.cartridge.gg) so the
// Coinbase iframe inside it will work correctly.
const keychainOrigin = window.location.origin;
const popupUrl = new URL("/coinbase", keychainOrigin);
popupUrl.searchParams.set("paymentLink", paymentLink);
popupUrl.searchParams.set("orderId", orderId);

// Open a centered popup (use screen dimensions since we may be in an iframe)
const width = 500;
const height = 700;
const left = (window.screen.width - width) / 2;
const top = (window.screen.height - height) / 2;

const popup = window.open(
paymentLink,
popupUrl.toString(),
"coinbase-payment",
`width=${width},height=${height},left=${left},top=${top},toolbar=no,menubar=no,scrollbars=yes,resizable=yes`,
);

popupRef.current = popup;

// Start polling for order status
// Start polling for order status in the keychain as well
startPolling(orderId);

// Also watch for the popup being closed by the user
// Watch for the popup being closed by the user
const checkClosed = setInterval(() => {
if (popup && popup.closed) {
clearInterval(checkClosed);
// If order is still not in a terminal state, keep polling briefly
// to catch last-second completions, but don't error immediately
// Keep polling briefly to catch last-second completions
}
}, 1000);
}, [paymentLink, orderId, startPolling]);
Expand All @@ -246,6 +259,7 @@ export function useCoinbase({
setIsCreatingOrder(true);
setOrderError(null);
setOrderStatus(undefined);
setOrderTxHash(undefined);

const order = await createCoinbaseOrder(input, !isMainnet);

Expand Down Expand Up @@ -303,6 +317,7 @@ export function useCoinbase({
isFetchingQuote,
isPollingOrder,
orderStatus,
orderTxHash,
createOrder,
getTransactions,
getQuote,
Expand Down
Loading