diff --git a/apps/ai-credits-web/index.html b/apps/ai-credits-web/index.html
index c63a383e..48d7c713 100644
--- a/apps/ai-credits-web/index.html
+++ b/apps/ai-credits-web/index.html
@@ -6,7 +6,7 @@
AI Credits with G$ | GoodDollar × Antseed
diff --git a/apps/ai-credits-web/src/App.tsx b/apps/ai-credits-web/src/App.tsx
index bf582736..7d9dc356 100644
--- a/apps/ai-credits-web/src/App.tsx
+++ b/apps/ai-credits-web/src/App.tsx
@@ -15,17 +15,9 @@ import {
useAppKitProvider,
useDisconnect,
} from '@goodwidget/embed/appkit-provider'
-import {
- ExternalLink,
- KeyRound,
- LockKeyhole,
- Network,
- ShieldCheck,
- ShoppingCart,
-} from '@tamagui/lucide-icons'
+import { KeyRound, ShieldCheck, ShoppingCart } from '@tamagui/lucide-icons'
import {
Accordion,
- Anchor,
Card,
GlowCard,
Heading,
@@ -39,9 +31,6 @@ import { TamaguiProvider } from '@tamagui/core'
const SWITCH_CHAIN_MANUAL_SELECTION_ERROR =
'Select the network in the wallet dialog, then try again.'
-const ANTSEED_API_DOCS = 'https://antseed.com/docs/guides/using-the-api/'
-const ANTSEED_SECURITY_DOCS = 'https://antseed.com/docs/security/'
-
function envAddress(value: string | undefined): `0x${string}` | undefined {
return value ? (value as `0x${string}`) : undefined
}
@@ -236,7 +225,7 @@ function PurchaseFrame() {
enableInjected
metadata={{
name: 'GoodDollar AI Credits',
- description: 'Buy AI credits with G$ and use them through Antseed.',
+ description: 'Buy AI credits with G$ and get an API key for Claude Code, Codex and other AI tools.',
}}
>
@@ -268,57 +257,21 @@ function PurchaseFrame() {
)
}
+// Gateway-model disclosures: what the key is, and what bounds the risk if it leaks.
function SecurityDetails() {
return (
-
-
- } title="Local, explicit routing">
- The signer proxy runs locally. It will not auto-select a peer: browse the network, inspect
- the services and pricing, then pin the peer you choose.
-
- }
- title="Protected transport, visible to providers"
- >
- WebRTC transport protects requests in transit to the selected peer. The provider serving a
- request still receives its contents, so do not send secrets in prompts.
-
-
-
+
- } title="Separated identity">
- The signer signing identity is separate from the funding wallet. A compromised signer
- identity cannot access that wallet, and its exposure is bounded by deposited credits.
+ } title="Your API key is a secret">
+ Treat your API key like a password. It is shown once, right after you buy credits, and
+ anyone who has it can spend your credits. If it leaks or gets lost, rotate it from the API
+ Key tab.
- } title="Keys are secrets">
- Treat ANTSEED_IDENTITY_HEX as a private key. The CLI may store a plaintext identity.key in
- its Antseed data directory unless you supply the identity securely, such as through a
- secrets manager.
+ } title="Spend is capped">
+ Your key has a monthly spend limit, so a leaked key can only use the credits you bought.
+ It cannot move funds out of your wallet.
-
-
-
-
-
-
-
-
- GoodDollar operator role on Base
-
-
- Your one-time wallet authorization lets the GoodDollar operator fund your credits and
- handle Base-side credit actions, including moving credit funds, without requiring you
- to pay Base gas. It cannot access your payer wallet or your G$ on Celo. This is a
- trusted role for the Base credit account.
-
-
- Read the Antseed security documentation
-
-
-
-
-
)
}
@@ -351,32 +304,15 @@ function LandingPage() {
backgroundSize: 'auto, auto, auto, auto, 24px 24px, 24px 24px, 24px 24px',
}}
>
-
-
- Read the Antseed API docs
-
-
-
-
@@ -394,15 +330,15 @@ function LandingPage() {
,
},
]}
@@ -431,36 +367,10 @@ function LandingPage() {
)
}
-// Widget-only view for partner integrations (e.g. AntSeed) that embed the purchase flow
-// directly without the hero and security sections around it.
-function PurchaseOnlyView() {
- return (
-
-
-
- )
-}
-
-function readSourceParam(): string | null {
- if (typeof window === 'undefined') return null
- return new URLSearchParams(window.location.search).get('source')
-}
-
export function App() {
- const isWidgetOnlySource = readSourceParam() === 'antseed'
-
return (
- {isWidgetOnlySource ? : }
+
)
}
diff --git a/apps/ai-credits-web/tests/landing-page.spec.ts b/apps/ai-credits-web/tests/landing-page.spec.ts
index 7848e0e5..993bad82 100644
--- a/apps/ai-credits-web/tests/landing-page.spec.ts
+++ b/apps/ai-credits-web/tests/landing-page.spec.ts
@@ -1,29 +1,20 @@
import { expect, test } from '@playwright/test'
-const heroHeading = 'Get up to 20% more AI credits with GoodID'
-
test.beforeEach(async ({ page }) => {
await page.goto('/')
})
-test('renders the hero, purchase widget, and security section without an injected wallet', async ({
+test('renders the purchase widget and security section without an injected wallet', async ({
page,
}) => {
- await expect(page.getByRole('heading', { level: 1, name: heroHeading })).toBeVisible()
await expect(page.getByTestId('wallet-fallback')).toBeVisible()
- await expect(page.getByText('Know what runs, who can see it, and what is at risk')).toBeVisible()
+ await expect(page.getByText('Know what your API key can do and what is at risk')).toBeVisible()
+})
- const apiDocsLink = page.getByRole('link', {
- name: 'Read the Antseed API docs',
- exact: true,
- })
- await expect(apiDocsLink).toHaveAttribute(
- 'href',
- 'https://antseed.com/docs/guides/using-the-api/',
- )
- await expect(apiDocsLink).toHaveAttribute('target', '_blank')
- await expect(apiDocsLink).toHaveAttribute('rel', /noopener/)
- await expect(apiDocsLink).toHaveAttribute('rel', /noreferrer/)
+test('drops the Antseed desktop copy and docs links', async ({ page }) => {
+ await expect(page.getByRole('link', { name: 'Read the Antseed API docs' })).toHaveCount(0)
+ await expect(page.getByText('signer', { exact: false })).toHaveCount(0)
+ await expect(page.getByText('Antseed Desktop', { exact: false })).toHaveCount(0)
})
test('drops the marketing sections that the widget now covers itself', async ({ page }) => {
@@ -39,24 +30,13 @@ test('drops the marketing sections that the widget now covers itself', async ({
).toHaveCount(0)
})
-test('keeps the security disclosures that have no widget equivalent', async ({ page }) => {
- // The section heading stays on the page; the detail sits behind a collapsed
- // disclosure, so it has to be expanded before any of it is visible.
- await expect(page.getByText('Know what runs, who can see it, and what is at risk')).toBeVisible()
- await expect(page.getByText('Separated identity')).toHaveCount(0)
-
- await page.getByText('How routing, identity, and the operator role work').click()
+test('keeps the API key security disclosures behind a collapsed disclosure', async ({ page }) => {
+ await expect(page.getByText('Your API key is a secret')).toHaveCount(0)
- await expect(page.getByText('GoodDollar operator role on Base')).toBeVisible()
- await expect(page.getByText('Local, explicit routing')).toBeVisible()
- await expect(page.getByText('Separated identity')).toBeVisible()
+ await page.getByText('How your API key and spend limit work').click()
- const securityDocsLink = page.getByRole('link', {
- name: 'Read the Antseed security documentation',
- exact: true,
- })
- await expect(securityDocsLink).toHaveAttribute('href', 'https://antseed.com/docs/security/')
- await expect(securityDocsLink).toHaveAttribute('target', '_blank')
+ await expect(page.getByText('Your API key is a secret')).toBeVisible()
+ await expect(page.getByText('Spend is capped')).toBeVisible()
})
test('keeps the portrait purchase frame inside the viewport without horizontal overflow', async ({
diff --git a/apps/ai-credits-web/tests/purchase-only.spec.ts b/apps/ai-credits-web/tests/purchase-only.spec.ts
deleted file mode 100644
index b683812a..00000000
--- a/apps/ai-credits-web/tests/purchase-only.spec.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { expect, test } from '@playwright/test'
-
-const deepLinkQuery =
- '&signerAddress=0x1111111111111111111111111111111111111111' +
- `&operatorSignature=0x${'ab'.repeat(64)}`
-
-test('source=antseed renders only the purchase widget, without landing-page sections', async ({
- page,
-}) => {
- await page.goto('/?source=antseed')
-
- await expect(page.getByTestId('ai-credits-purchase-only')).toBeVisible()
- await expect(page.getByTestId('purchase-frame')).toBeVisible()
- await expect(page.getByTestId('ai-credits-landing-page')).toHaveCount(0)
- await expect(page.getByRole('heading', { level: 1 })).toHaveCount(0)
- await expect(page.getByText('Know what runs, who can see it, and what is at risk')).toHaveCount(0)
-})
-
-test('omitting source keeps the landing page wrapper', async ({ page }) => {
- await page.goto('/')
-
- await expect(page.getByTestId('ai-credits-landing-page')).toBeVisible()
- await expect(page.getByTestId('ai-credits-purchase-only')).toHaveCount(0)
-})
-
-test('source=antseed composes with signerAddress and operatorSignature deep-link params', async ({
- page,
-}) => {
- await page.goto(`/?source=antseed${deepLinkQuery}`)
-
- await expect(page.getByTestId('ai-credits-purchase-only')).toBeVisible()
- await expect(page.getByTestId('purchase-frame')).toBeVisible()
- await expect(page.getByTestId('ai-credits-landing-page')).toHaveCount(0)
-})
diff --git a/examples/storybook/src/stories/ai-credits-widget/AiCreditsWidget.mdx b/examples/storybook/src/stories/ai-credits-widget/AiCreditsWidget.mdx
index edcc07da..65e64406 100644
--- a/examples/storybook/src/stories/ai-credits-widget/AiCreditsWidget.mdx
+++ b/examples/storybook/src/stories/ai-credits-widget/AiCreditsWidget.mdx
@@ -7,11 +7,11 @@ import { DocsCallout, DocsCard, DocsGrid, DocsPage, DocsSection } from '../docs/
@@ -37,58 +37,51 @@ import { DocsCallout, DocsCard, DocsGrid, DocsPage, DocsSection } from '../docs/
- Setup tab with connect CTA; Buy Credits, Manage, and History tabs visible but disabled until a wallet connects.
- Connected wallet — onboarding for Download AntSeed, Signer Key, and Authorize Credits Management. The authorization step opens the same consent flow used by Buy Credits.
- Buy tab — stepper with a CTA to open the active step in a bottom drawer.
- Buy tab — pay step available via drawer CTA; ready to confirm Celo transaction.
+ Buy tab with a connect CTA; API Key and History tabs visible but disabled until a wallet connects.
+ Buy tab — amount picker and quote.
+ Buy tab — ready to confirm the Celo transaction.
Buy tab — Celo tx submitted.
- Buy tab — settling on Base.
- Manage tab — balance, stream, close/withdraw, API setup.
+ Buy tab — adding GoodDollar AI credits; the API key sheet opens after the first purchase.
+ API Key tab — credits balance, masked key, base URL, spend limit, Rotate and Revoke.
History tab — filtered, paginated AI credit funding history.
G$ below minimum purchase threshold.
Transaction or settlement error.
Backend unreachable.
Wrong network (Celo required).
+ Host passed no `aiCreditsApi`: Buy is disabled and the API Key tab shows a coming-soon notice.
- Onboarding entry point — connect wallet when disconnected; onboarding step shell when connected.
- Stepper for signer key, wallet authorization, and payment — tap a step or CTA to open it in a drawer.
- Credits balance, stream info, close/withdraw, and API setup.
+ Connect, choose a deposit or monthly stream, and pay in G$.
+ Credits balance, masked key, base URL, monthly spend limit, Rotate and Revoke.
Paginated credit history with source, status, and date filters.
- Credits profile for the payer wallet.
-
- Newest-first funding history (`items[].signerAddress` is used to recover the signer).
+
+ Typed client the host supplies: `getAccount`, `createOrTopUpKey`, `rotateKey`, `revokeKey`, `getHistory`.
+ Must be a stable reference. Storybook and dev use `MockAiCreditsApi` from `/mocked`.
- Pending or failed Base funding entries.
+ Credits profile for the payer wallet.
+ Newest-first funding history.
+ Pending or failed funding entries.
Notify `{ txHash }` after a successful Celo payment.
-
- Signer-signed SetOperator relay — backend submits `acceptSignerOperator` on Base (no signer gas).
-
- Signer-signed channel close from credits management.
- Signer-signed principal withdraw to the payer wallet.
- Vault minimum reads, quotes, withdrawable principal, and Celo deposit/stream transactions are
- handled on-chain via RPC. Signer EIP-712 signing for wallet authorization, close, and withdraw
- happens in the widget; only the Base submission is relayed by the worker. There is no
- channel-list API — paste the channel ID manually.
+ Vault minimum reads, quotes, and Celo deposit/stream transactions are handled on-chain via RPC.
@@ -96,19 +89,14 @@ import { DocsCallout, DocsCard, DocsGrid, DocsPage, DocsSection } from '../docs/
title="Known limitations"
description="Features that still need operator care in production."
>
-
- Close channel and withdraw require the signer private key in the current browser session. Use
- Sign & Generate in Signer & Operator on the credits management screen if the key was
- lost after refresh.
+
+ The full key is held in memory only while the "Your API key is ready" sheet is open. It is never
+ persisted, logged, or sent to analytics. A lost key can only be replaced by rotating it.
First-deposit USD minimum applies only when `totalDepositedGd(payer)` is zero. Monthly stream
USD minimum applies on every stream create/update.
-
- Operator consent, close, withdraw, and credit funding require the worker's Base operator
- bridge to be configured (`bridge.enabled: true` in API responses).
-
= {
@@ -77,8 +72,44 @@ export const PaymentConfirmed: Story = {
render: () => ,
}
-export const CreditsManagement: Story = {
- render: () => ,
+/** API Key tab for an account that already holds a key. */
+export const ApiKeyTabActive: Story = {
+ render: () => ,
+}
+
+/** API Key tab before the first purchase. */
+export const ApiKeyTabEmpty: Story = {
+ render: () => ,
+}
+
+/** API Key tab when the host configured no `aiCreditsApi`. */
+export const ApiKeyTabComingSoon: Story = {
+ render: () => ,
+}
+
+/** API Key tab when the account fails to load. */
+export const ApiKeyTabError: Story = {
+ render: () => ,
+}
+
+/** Rotating the key shows the new key once in the "Your API key is ready" sheet. */
+export const ApiKeyReadySheet: Story = {
+ render: () => ,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await userEvent.click(await canvas.findByRole('button', { name: 'Rotate' }))
+ await userEvent.click(await within(document.body).findByRole('button', { name: 'Rotate key' }))
+ // The sheet slides in, so visibility is polled rather than asserted once.
+ await waitFor(() =>
+ expect(within(document.body).getByText('Your API key is ready')).toBeVisible(),
+ )
+ await expect(within(document.body).getByRole('button', { name: 'Copy API key' })).toBeVisible()
+ },
+}
+
+/** Buy tab when the host configured no `aiCreditsApi`: purchases are disabled. */
+export const BuyTabUnavailable: Story = {
+ render: () => ,
}
export const HistoryTab: Story = {
@@ -105,11 +136,6 @@ export const UnsupportedChain: Story = {
render: () => ,
}
-/** Multi-signer manage tab: signer selector and private-key reveal. */
-export const MultiSignerManage: Story = {
- render: () => ,
-}
-
/** Header wallet chip opted in, with a host-supplied disconnect. */
export const WalletControls: Story = {
render: () => ,
@@ -120,25 +146,6 @@ export const WalletControlsHidden: Story = {
render: () => ,
}
-/** Deep-link partner signer: consent via pre-signed operatorSignature. */
-export const DeepLinkSigner: Story = {
- render: () => ,
-}
-
-/** Deep-link signer reaching the buy-flow consent gate: signature prefilled, not yet consented. */
-export const DeepLinkConsentPending: Story = {
- render: () => ,
-}
-
-/** History tab with signer filter dropdown. */
-export const MultiSignerHistory: Story = {
- render: () => ,
-}
-
-export const SetupTab: Story = {
- render: () => ,
-}
-
export const AppKitConnectWallet: Story = {
render: () => ,
play: async ({ canvasElement }) => {
@@ -176,7 +183,7 @@ export const GuidanceCardHowToUse: Story = {
const root = canvas.getByTestId('AiCreditsWidget-guidance-how-to-use')
const howToUseButton = within(root).getByRole('button', { name: /how to use/i })
await userEvent.click(howToUseButton)
- await expect(within(root).getByText(/Back to setup/i)).toBeVisible()
+ await expect(within(root).getByText(/^back$/i)).toBeVisible()
},
}
@@ -188,52 +195,6 @@ export const GuidanceCardFaq: Story = {
const root = canvas.getByTestId('AiCreditsWidget-guidance-faq')
const faqButton = within(root).getByRole('button', { name: /faqs/i })
await userEvent.click(faqButton)
- await expect(within(root).getByText(/Back to setup/i)).toBeVisible()
- },
-}
-
-/** Setup tab — Download AntSeed step with active "Start ›" link and locked subsequent steps. */
-export const DownloadAntSeedStep: Story = {
- render: () => ,
-}
-
-export const SignerKeyGenerated: Story = {
- render: () => ,
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement)
- await userEvent.click(canvas.getByText('Signer key', { exact: true }))
- await userEvent.click(canvas.getByRole('button', { name: /generate signer key/i }))
- await expect(canvas.getByText('Private Key — save this securely')).toBeVisible()
- },
-}
-
-export const SetupAuthorizeWallet: Story = {
- render: () => ,
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement)
- await userEvent.click(canvas.getByText('Authorize Credits Management', { exact: true }))
- await expect(
- within(document.body).getByText(
- /GoodDollar needs this one-time authorization to fund and manage your AI credits/i,
- ),
- ).toBeVisible()
- await expect(
- within(document.body).getByRole('button', { name: 'Authorize Credits Management' }),
- ).toBeEnabled()
- },
-}
-
-export const SignerKeyIncompatibleOperator: Story = {
- render: () => ,
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement)
- await userEvent.click(canvas.getByText('Signer key', { exact: true }))
- await userEvent.click(canvas.getByRole('button', { name: /import signer key/i }))
- // The operator warning is a status of the import itself, so it only appears
- // once a key has actually been imported.
- await expect(canvas.queryByText('Signer key cannot be used')).toBeNull()
- await userEvent.type(canvas.getByPlaceholderText('0x…'), `0x${'1'.repeat(64)}`)
- await userEvent.click(canvas.getByRole('button', { name: /import signer key/i }))
- await expect(canvas.getByText('Signer key cannot be used')).toBeVisible()
+ await expect(within(root).getByText(/^back$/i)).toBeVisible()
},
}
diff --git a/examples/storybook/src/stories/helpers/aiCreditsWidgetStories.tsx b/examples/storybook/src/stories/helpers/aiCreditsWidgetStories.tsx
index afaf9996..19abf699 100644
--- a/examples/storybook/src/stories/helpers/aiCreditsWidgetStories.tsx
+++ b/examples/storybook/src/stories/helpers/aiCreditsWidgetStories.tsx
@@ -3,12 +3,13 @@ import type { EIP1193Provider } from '@goodwidget/core'
import { YStack } from '@goodwidget/ui'
import {
AiCreditsWidget,
+ type AiCreditsApi,
type AiCreditsWidgetAdapterFactory,
type AiCreditsWidgetTab,
type AiCreditsWidgetAdapterState,
type AiCreditsWidgetStatus,
} from '@goodwidget/ai-credits-widget'
-import { MockAiCreditsWidget } from '@goodwidget/ai-credits-widget/mocked'
+import { MockAiCreditsApi, MockAiCreditsWidget } from '@goodwidget/ai-credits-widget/mocked'
import {
DefaultAppKitProvider,
DEFAULT_APPKIT_NETWORKS,
@@ -48,7 +49,6 @@ function createMockState(
minStreamUsd: '1.00',
totalGdDepositedG: null,
monthlyStreamG: null,
- withdrawableUsd: null,
depositBonusPercent: 10,
streamBonusPercent: 20,
error: null,
@@ -85,8 +85,6 @@ function createAdapterFactory(
verifyGoodId: async () => false,
startPurchase: () => {},
setActiveTab: () => {},
- closeChannel: async () => {},
- withdrawCredits: async () => {},
retry: async () => {},
},
})
@@ -108,20 +106,25 @@ function MockStoryShell({
provider,
showWalletControls,
disconnectOverride,
+ aiCreditsApi,
}: {
adapterFactory: AiCreditsWidgetAdapterFactory
dataTestId: string
provider?: EIP1193Provider
showWalletControls?: boolean
disconnectOverride?: () => Promise
+ /** Omit for an empty mock account; pass `null` to render a host that configured no `aiCreditsApi`. */
+ aiCreditsApi?: AiCreditsApi | null
}) {
+ // A stable instance keeps the widget's key state from resetting on every story re-render.
+ const defaultAiCreditsApi = useMemo(() => new MockAiCreditsApi(), [])
+ const resolvedAiCreditsApi =
+ aiCreditsApi === null ? undefined : (aiCreditsApi ?? defaultAiCreditsApi)
const resolvedProviderRef = useRef(provider ?? null)
const configErrorRef = useRef(null)
- // The fixtures return a frozen state object, so `setActiveTab` was a no-op and
- // any flow that switches tabs silently did nothing. Opening How to use is one
- // of those — the widget routes to Set Up to render it, so with a dead
- // setActiveTab the guide never appeared and the Buy panel stayed on screen.
+ // The fixtures return a frozen state object, so `setActiveTab` would be a no-op and
+ // tab switches (including "Buy credits" from the API Key tab) would silently do nothing.
const [tabOverride, setTabOverride] = useState(null)
const statefulAdapterFactory: AiCreditsWidgetAdapterFactory = (input) => {
const adapter = adapterFactory(input)
@@ -158,6 +161,7 @@ function MockStoryShell({
@@ -169,7 +173,7 @@ const DISCONNECTED_ADAPTER_FACTORY = createAdapterFactory('disconnected', {
address: null,
chainId: null,
gBalance: null,
- activeTab: 'setup',
+ activeTab: 'buy',
})
export function DisconnectedStory() {
@@ -190,7 +194,7 @@ export function ConnectingStory() {
address: '0x329377cbeeF39f01b0Ea04B80465c9eB47D3ED1',
chainId: 42220,
gBalance: null,
- activeTab: 'setup',
+ activeTab: 'buy',
})}
/>
)
@@ -258,105 +262,104 @@ export function PaymentConfirmedStory() {
)
}
-export function ManageTabStory() {
+const CONNECTED_WALLET_ADDRESS = '0x329377cbeeF39f01b0Ea04B80465c9eB47D3ED1'
+const SEEDED_SPEND_LIMIT_USD_MICRO = '110000000'
+
+const API_KEY_TAB_STATE_OVERRIDES: Partial = {
+ totalCreditUsd: '110000000',
+ totalBonusUsd: '10000000',
+ totalGdDepositedG: '50.00',
+ monthlyStreamG: '5.00',
+ gBalance: '42.50',
+ activeTab: 'apiKey',
+}
+
+/** API Key tab for an account that already holds a key, with a spend limit and monthly usage. */
+export function ApiKeyTabActiveStory() {
+ const aiCreditsApi = useMemo(
+ () =>
+ new MockAiCreditsApi({
+ seededAccounts: { [CONNECTED_WALLET_ADDRESS]: { limitUsdMicro: SEEDED_SPEND_LIMIT_USD_MICRO } },
+ delayMs: 50,
+ }),
+ [],
+ )
+
return (
)
}
-export function HistoryTabStory() {
+/** API Key tab before the first purchase: no key exists yet. */
+export function ApiKeyTabEmptyStory() {
+ const aiCreditsApi = useMemo(() => new MockAiCreditsApi({ delayMs: 50 }), [])
+
return (
)
}
-export function SetupTabStory() {
+/** API Key tab when the host configured no `aiCreditsApi` (production until the backend exists). */
+export function ApiKeyTabComingSoonStory() {
return (
)
}
-export function SignerKeyGeneratedStory() {
+/** API Key tab when loading the account fails. */
+export function ApiKeyTabErrorStory() {
+ const aiCreditsApi = useMemo(
+ () => new MockAiCreditsApi({ failingMethods: ['getAccount'], delayMs: 50 }),
+ [],
+ )
+
return (
)
}
-/** Setup tab with a generated signer key and the Authorize Credits Management step ready. */
-export function SetupAuthorizeWalletStory() {
+/** Buy tab when the host configured no `aiCreditsApi`: purchases stay disabled. */
+export function BuyTabUnavailableStory() {
return (
)
}
-export function SignerKeyIncompatibleOperatorStory() {
+export function HistoryTabStory() {
return (
)
}
-export function CreditsManagementStory() {
- return
-}
-
export function InsufficientGBalanceStory() {
return (
@@ -606,48 +609,9 @@ export function InjectedWalletStory() {
}
// ---------------------------------------------------------------------------
-// Multi-signer fixture stories
+// Wallet chip stories
// ---------------------------------------------------------------------------
-const BUYER_WALLET = {
- address: '0xfc128652c9b397a1f89A9EC84E798B869B0E4c7a' as const,
- privateKey: '0x0000000000000000000000000000000000000000000000000000000000000001' as const,
-}
-
-const BUYER_IMPORTED = {
- address: '0xAbcDef1234567890AbcDef1234567890AbcDef12' as const,
- privateKey: '0x0000000000000000000000000000000000000000000000000000000000000002' as const,
-}
-
-const BUYER_PARTNER = {
- address: '0x1111111111111111111111111111111111111111' as const,
- operatorSignature:
- '0x1111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222200' as const,
-}
-
-/** Multi-signer manage: backend address list with one selected signer that has a local key. */
-export function MultiSignerManageStory() {
- return (
-
- )
-}
-
/**
* Standalone/Storybook host: the wallet chip is opted in and the host supplies a
* disconnect, so the header carries the address and its Disconnect action.
@@ -658,16 +622,7 @@ export function WalletControlsStory() {
dataTestId="AiCreditsWidget-wallet-controls"
showWalletControls
disconnectOverride={async () => {}}
- adapterFactory={createAdapterFactory('quote_ready', {
- totalCreditUsd: '110000000',
- totalBonusUsd: '10000000',
- signerPubKey: BUYER_WALLET.address,
- signerPrvKey: BUYER_WALLET.privateKey,
- operatorConsented: true,
- gBalance: '42.50',
- activeTab: 'manage',
- signers: [BUYER_WALLET.address],
- })}
+ adapterFactory={createAdapterFactory('quote_ready', API_KEY_TAB_STATE_OVERRIDES)}
/>
)
}
@@ -680,75 +635,7 @@ export function WalletControlsHiddenStory() {
return (
- )
-}
-
-/** Deep-link partner signer: consent uses pre-signed operatorSignature (no private key). */
-export function DeepLinkSignerStory() {
- return (
-
- )
-}
-
-/**
- * Deep-link partner signer reaching the buy-flow consent step: a pre-signed
- * operatorSignature is prefilled but operatorConsented is still false, so the
- * explicit "Sign Operator Consent" gate must render instead of auto-advancing.
- */
-export function DeepLinkConsentPendingStory() {
- return (
-
- )
-}
-
-/** History tab with multi-signer filter options available. */
-export function MultiSignerHistoryStory() {
- return (
-
)
}
@@ -791,19 +678,3 @@ export function GuidanceCardFaqStory() {
/>
)
}
-
-/**
- * Setup tab with wallet connected — shows Download AntSeed as the first
- * actionable step with locked subsequent steps until download is started.
- */
-export function DownloadAntSeedStepStory() {
- return (
-
- )
-}
diff --git a/packages/ai-credits-widget/src/AiCreditsWidget.tsx b/packages/ai-credits-widget/src/AiCreditsWidget.tsx
index 4fdf9a20..964da41f 100644
--- a/packages/ai-credits-widget/src/AiCreditsWidget.tsx
+++ b/packages/ai-credits-widget/src/AiCreditsWidget.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useMemo, useState } from 'react'
+import React, { useCallback, useMemo, useRef, useState } from 'react'
import { GoodWidgetProvider, WalletControls } from '@goodwidget/core'
import type { EIP1193Provider } from '@goodwidget/core'
import {
@@ -9,8 +9,8 @@ import {
Card,
CircularActionButton,
getChainDisplayName,
+ GoodWidgetDialog,
Heading,
- Icon,
Text,
ToastContainer,
WidgetTabs,
@@ -24,18 +24,20 @@ import { version } from '../package.json'
import { WidgetVersion } from '@goodwidget/ui'
import { needsWalletConnection, useAiCreditsAdapter } from './adapter'
import { useAiCreditsHistory } from './useAiCreditsHistory'
+import { useApiKey } from './useApiKey'
import {
AiCreditsHero,
AiCreditsPurchaseFlow,
AiCreditsStatusNotice,
- CreditsManagementCard,
- SignerOperatorCard,
+ ApiKeyPanel,
+ ApiKeyReadySheet,
+ FaqView,
+ GuidanceCard,
HistoryTab,
- SetupGuidanceCard,
HowToUseView,
- SetupFaqView,
- SetupOnboardingFlow,
} from './components'
+import type { AiCreditsApi } from './aiCreditsApi/types'
+import type { ApiKeyActions } from './useApiKey'
import type {
AiCreditsWidgetProps,
AiCreditsWidgetEnvironment,
@@ -48,7 +50,6 @@ import type {
AiCreditsWidgetTab,
AiCreditsQuote,
} from './widgetRuntimeContract'
-import { compactButtonProps } from './components/shared/styles'
const CELO_CHAIN_ID = 42220
@@ -65,9 +66,11 @@ interface AiCreditsInnerProps {
onPaySuccess?: (detail: AiCreditsPaySuccessDetail) => void
onPayError?: (detail: AiCreditsPayErrorDetail) => void
showWalletControls?: boolean
+ aiCreditsApi?: AiCreditsApi
}
-function SetupConnectPrompt({
+/** Prompt shown on the Buy tab until a wallet is connected. */
+function ConnectPrompt({
onConnect,
connecting,
}: {
@@ -91,29 +94,6 @@ function SetupConnectPrompt({
)
}
-function SetupTabPanel({
- state,
- actions,
- onConnect,
-}: {
- state: AiCreditsWidgetAdapterState
- actions: AiCreditsWidgetAdapterActions
- onConnect: () => Promise
-}) {
- if (needsWalletConnection(state)) {
- return
- }
-
- return (
-
-
- One-time setup required before buying AI Credits.
-
-
-
- )
-}
-
/**
* Wrong-network prompt.
*
@@ -191,57 +171,31 @@ function SwitchChainNotice({
)
}
-/**
- * Standing disclaimer that buying and using credits are different jobs: the
- * purchase works anywhere, but Antseed runs on a desktop, so a phone-only user
- * cannot finish setup or spend what they bought.
- *
- * Collapsed by default to keep it off the top of every panel, but the warning
- * itself stays on the summary line — folding away the sentence that says "you
- * need a computer" would defeat the point of showing it at all. Only the
- * reassuring half, that buying on a phone is fine, is behind the toggle.
- */
-function DesktopRequiredNotice() {
- const [expanded, setExpanded] = useState(false)
-
- return (
-
- setExpanded((prev) => !prev)}
- >
-
-
-
- Please note:
- {' '}
- Using your AI credits requires a desktop computer.
-
-
-
- {expanded && (
-
- You can buy credits and set up your Signer Key from your phone. To use your AI credits, you’ll need a desktop computer.
-
- )}
-
- )
-}
-
interface BuyPanelProps {
state: AiCreditsWidgetAdapterState
actions: AiCreditsWidgetAdapterActions
isPending: boolean
+ /** False when no `aiCreditsApi` is configured, so a purchase could not be turned into a key. */
+ isPurchaseAvailable: boolean
onPay: (quote: AiCreditsQuote) => void
}
-function BuyCreditsPanel({ state, actions, isPending, onPay }: BuyPanelProps) {
+function BuyCreditsPanel({ state, actions, isPending, isPurchaseAvailable, onPay }: BuyPanelProps) {
let content: React.ReactNode
- if (state.status === 'unsupported_chain') {
+ if (!isPurchaseAvailable) {
+ // Paying without a key backend would take real G$ and hand back no key.
+ content = (
+
+
+ Buying credits is not available yet
+
+
+ GoodDollar AI credits are not open for purchase yet. Your wallet has not been charged.
+
+
+ )
+ } else if (state.status === 'unsupported_chain') {
content =
} else if (state.status === 'payment_failed') {
content = (
@@ -296,7 +250,7 @@ function BuyCreditsPanel({ state, actions, isPending, onPay }: BuyPanelProps) {
const message =
state.status === 'payment_pending'
? 'Transaction submitted — waiting for confirmation…'
- : 'Payment confirmed — settling credits on Base…'
+ : 'Payment confirmed — adding your GoodDollar AI credits…'
content = (
@@ -311,15 +265,6 @@ function BuyCreditsPanel({ state, actions, isPending, onPay }: BuyPanelProps) {
} else {
content = (
<>
- {state.error && (
-
-
- Deep link unavailable
-
- {state.error}
-
- )}
-
{state.address && (
)}
@@ -352,63 +297,6 @@ function BuyCreditsPanel({ state, actions, isPending, onPay }: BuyPanelProps) {
return {content}
}
-function ManagePanel({
- state,
- actions,
-}: {
- state: AiCreditsWidgetAdapterState
- actions: AiCreditsWidgetAdapterActions
-}) {
- const [refreshing, setRefreshing] = React.useState(false)
-
- const handleRefresh = async () => {
- setRefreshing(true)
- try {
- await actions.refresh()
- } finally {
- setRefreshing(false)
- }
- }
-
- return (
-
- {state.error && (
-
-
- {state.error}
-
-
- )}
-
-
-
-
-
-
- {state.error && (
-
- {state.error}
-
- )}
-
-
-
- )
-}
-
function AiCreditsInner({
environment,
backendUrl,
@@ -422,7 +310,22 @@ function AiCreditsInner({
onPaySuccess,
onPayError,
showWalletControls = false,
+ aiCreditsApi,
}: AiCreditsInnerProps) {
+ // The adapter needs the success callback before `useApiKey` exists, so it reaches the hook through a ref.
+ const fulfillPurchaseRef = useRef(null)
+ const handlePaySuccess = useCallback(
+ (detail: AiCreditsPaySuccessDetail) => {
+ void fulfillPurchaseRef.current?.({
+ accountId: detail.address,
+ creditUsdMicro: detail.creditUsdMicro,
+ transactionHash: detail.transactionHash,
+ })
+ onPaySuccess?.(detail)
+ },
+ [onPaySuccess],
+ )
+
const defaultAdapter = useAiCreditsAdapter({
environment,
backendUrl,
@@ -431,7 +334,7 @@ function AiCreditsInner({
fundingVaultAddress: fundingVaultAddress as `0x${string}` | undefined,
vaultAddress: vaultAddress as `0x${string}` | undefined,
goodIdAddress: goodIdAddress as `0x${string}` | undefined,
- onPaySuccess,
+ onPaySuccess: handlePaySuccess,
onPayError,
backendClient: adapterOptions?.backendClient,
chainClient: adapterOptions?.chainClient,
@@ -446,19 +349,15 @@ function AiCreditsInner({
const activeAdapter = factoryAdapter ?? defaultAdapter
const { state, actions } = activeAdapter
- const onSignersDiscoveredRef = React.useRef(actions.discoverSigners)
- onSignersDiscoveredRef.current = actions.discoverSigners
- const onSignersDiscovered = useCallback((addresses: string[]) => {
- onSignersDiscoveredRef.current(addresses)
- }, [])
+
+ const apiKey = useApiKey({ aiCreditsApi, accountId: state.address })
+ fulfillPurchaseRef.current = apiKey.actions.fulfillPurchase
const history = useAiCreditsHistory({
address: state.address,
backendUrl,
- defaultSignerFilter: state.signerPubKey ?? 'all',
environment,
backendClient: adapterOptions?.backendClient,
- onSignersDiscovered,
})
const handlePay = useCallback(
@@ -490,47 +389,73 @@ function AiCreditsInner({
const [helpView, setHelpView] = useState<'how-to-use' | 'faq' | null>(null)
+ const isKeyManagementAvailable = !!aiCreditsApi
+
const isPending = state.status === 'payment_pending' || state.status === 'payment_confirmed'
const handleTabChange = useCallback(
(tabId: string) => {
- if (tabId !== 'setup') {
- setHelpView(null)
- }
+ setHelpView(null)
actions.setActiveTab(tabId as AiCreditsWidgetTab)
},
[actions],
)
// Ending the session leaves every other tab showing empty rows, so the widget
- // returns to Setup — the only tab that has something to say while disconnected.
+ // returns to Buy Credits — the only tab that has something to say while disconnected.
const handleDisconnected = useCallback(() => {
setHelpView(null)
- actions.setActiveTab('setup')
+ actions.setActiveTab('buy')
}, [actions])
const walletRequired = needsWalletConnection(state)
- const handleHelpViewOpen = useCallback(
- (view: 'how-to-use' | 'faq') => {
- actions.setActiveTab('setup')
- setHelpView(view)
- },
- [actions],
- )
+ const handleHelpViewOpen = useCallback((view: 'how-to-use' | 'faq') => {
+ setHelpView(view)
+ }, [])
+
+ const handleBuyCredits = useCallback(() => {
+ setHelpView(null)
+ actions.setActiveTab('buy')
+ }, [actions])
const handleHelpViewClose = useCallback(() => {
setHelpView(null)
}, [])
- const setupPanel =
- helpView === 'how-to-use' ? (
-
- ) : helpView === 'faq' ? (
-
- ) : (
-
+ let tabContent: React.ReactNode
+ if (helpView === 'how-to-use') {
+ tabContent =
+ } else if (helpView === 'faq') {
+ tabContent =
+ } else if (walletRequired) {
+ tabContent =
+ } else if (state.activeTab === 'apiKey') {
+ tabContent = (
+
)
+ } else if (state.activeTab === 'history') {
+ tabContent =
+ } else {
+ tabContent = (
+ {
+ void handlePay(quote)
+ }}
+ />
+ )
+ }
return (
@@ -543,7 +468,7 @@ function AiCreditsInner({
{showWalletControls && }
- {
handleHelpViewOpen('how-to-use')
@@ -557,38 +482,23 @@ function AiCreditsInner({
/>
walletRequired && tabId !== 'setup'}
+ isTabDisabled={(tabId) => walletRequired && tabId !== 'buy'}
withConnectionStatus={false}
/>
-
-
- {walletRequired || state.activeTab === 'setup' ? (
- setupPanel
- ) : state.activeTab === 'manage' ? (
-
- ) : state.activeTab === 'history' ? (
- ({ address }))}
- />
- ) : (
- {
- void handlePay(quote)
- }}
- />
- )}
+
+ {tabContent}
+
+
)
}
@@ -618,6 +528,7 @@ export function AiCreditsWidget({
onPayError,
adapterFactory,
adapterOptions,
+ aiCreditsApi,
testId,
}: AiCreditsWidgetProps) {
return (
@@ -649,8 +560,10 @@ export function AiCreditsWidget({
onPaySuccess={onPaySuccess}
onPayError={onPayError}
showWalletControls={showWalletControls}
+ aiCreditsApi={aiCreditsApi}
/>
+
diff --git a/packages/ai-credits-widget/src/adapter.ts b/packages/ai-credits-widget/src/adapter.ts
index c5723837..219e16d9 100644
--- a/packages/ai-credits-widget/src/adapter.ts
+++ b/packages/ai-credits-widget/src/adapter.ts
@@ -12,12 +12,7 @@ import {
} from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { buildSignerKeyMessage, deriveSignerPrivateKeyFromSignature } from './signerKeyDerivation'
-import {
- normalizeChannelId,
- signRequestClose,
- signRevokeOperator,
- signWithdrawPrincipal,
-} from './signerSignatures'
+import { signRevokeOperator } from './signerSignatures'
import {
totalCreditUsdFromProfile,
buildAccountView,
@@ -63,7 +58,7 @@ import { executeCeloPayment, G_TOKEN_CELO_ADDRESS, isStreamAmountChanged } from
import { startGoodIdVerification, isUserRejectedWalletRequest } from './goodIdVerification'
import { mapPaymentError } from './paymentErrors'
import { fetchVaultPaymentMinimums, validateVaultPaymentAmounts } from './vaultMinimums'
-import { quoteTotalUsdMicro, usdDisplayToMicro } from './quoteMath'
+import { quoteTotalUsdMicro } from './quoteMath'
import type {
AiCreditsWidgetAdapterActions,
AiCreditsWidgetAdapterResult,
@@ -123,11 +118,10 @@ const INITIAL_STATE: AiCreditsWidgetAdapterState = {
minStreamUsd: null,
totalGdDepositedG: null,
monthlyStreamG: null,
- withdrawableUsd: null,
depositBonusPercent: DEFAULT_DISCOUNT_CONFIG.depositBonusPercent,
streamBonusPercent: DEFAULT_DISCOUNT_CONFIG.streamBonusPercent,
error: null,
- activeTab: 'setup',
+ activeTab: 'buy',
signers: [],
derivedSignerAddress: null,
}
@@ -140,7 +134,6 @@ const WALLET_LOADING_STATE: Partial = {
minStreamUsd: null,
totalGdDepositedG: null,
monthlyStreamG: null,
- withdrawableUsd: null,
operatorAddress: null,
currentOperator: null,
}
@@ -189,7 +182,7 @@ function selectPreferredSigner(signers: string[], preferredSigner?: string | nul
}
function isNonBuyTab(tab: AiCreditsWidgetTab): boolean {
- return tab === 'setup' || tab === 'manage' || tab === 'history'
+ return tab === 'apiKey' || tab === 'history'
}
export function needsWalletConnection(state: AiCreditsWidgetAdapterState): boolean {
@@ -200,34 +193,16 @@ export function needsWalletConnection(state: AiCreditsWidgetAdapterState): boole
)
}
-function resolveDefaultActiveTab(
- payerAddress: string | null,
- totalCreditUsd: string | null,
-): AiCreditsWidgetTab {
- if (hasCreditBalance(totalCreditUsd)) return 'manage'
- if (payerAddress && listKnownSignerAddresses(payerAddress).length > 0) return 'buy'
- return 'setup'
-}
-
function resolveActiveTab(
prev: AiCreditsWidgetAdapterState,
overrides: Partial,
): AiCreditsWidgetTab {
if (overrides.activeTab !== undefined) return overrides.activeTab
- const payerAddress = overrides.address !== undefined ? overrides.address : prev.address
- const totalCreditUsd =
- overrides.totalCreditUsd !== undefined ? overrides.totalCreditUsd : prev.totalCreditUsd
+ // Buy Credits is the landing tab for every wallet, whether or not it already holds credits.
+ if (overrides.address !== undefined && overrides.address !== prev.address) return 'buy'
- if (overrides.totalCreditUsd !== undefined && overrides.totalCreditUsd !== null) {
- return resolveDefaultActiveTab(payerAddress, overrides.totalCreditUsd)
- }
-
- if (overrides.address !== undefined && overrides.address !== prev.address) {
- return resolveDefaultActiveTab(payerAddress, totalCreditUsd)
- }
-
- return prev.activeTab ?? resolveDefaultActiveTab(payerAddress, totalCreditUsd)
+ return prev.activeTab ?? 'buy'
}
function hasCreditBalance(totalCreditUsd: string | null): boolean {
@@ -236,7 +211,7 @@ function hasCreditBalance(totalCreditUsd: string | null): boolean {
/**
* Reads the wallet's G$ balance from Celo. Both the connect load and the
- * refresh action go through here so the Manage tab's "Refresh Balance" button
+ * refresh action go through here so the API Key tab's "Refresh Balance" button
* actually re-reads the balance it names.
*/
async function readGBalance(client: PublicClient, account: string): Promise {
@@ -394,7 +369,6 @@ function viewToStatePatch(
currentOperator: view.operator.currentOperator ?? null,
}
: {}),
- ...(view.withdrawableUsd !== null ? { withdrawableUsd: view.withdrawableUsd } : {}),
totalGdDepositedG: enriched.totalGdDepositedG,
monthlyStreamG: enriched.monthlyStreamG,
}
@@ -887,8 +861,7 @@ export function useAiCreditsAdapter({
operatorAddress: null,
currentOperator: null,
totalCreditUsd: null,
- withdrawableUsd: null,
- totalGdDepositedG: null,
+ totalGdDepositedG: null,
monthlyStreamG: null,
operatorConsentPending: false,
error: null,
@@ -981,8 +954,7 @@ export function useAiCreditsAdapter({
operatorAddress: null,
currentOperator: null,
totalCreditUsd: null,
- withdrawableUsd: null,
- totalGdDepositedG: null,
+ totalGdDepositedG: null,
monthlyStreamG: null,
error: null,
...(!isNonBuyTab(prev.activeTab) ? { status: 'purchase_setup' } : {}),
@@ -1101,8 +1073,7 @@ export function useAiCreditsAdapter({
operatorAddress: null,
currentOperator: null,
totalCreditUsd: null,
- withdrawableUsd: null,
- totalGdDepositedG: null,
+ totalGdDepositedG: null,
monthlyStreamG: null,
activeTab: 'buy',
operatorConsentPending: false,
@@ -1529,7 +1500,7 @@ export function useAiCreditsAdapter({
...signerFields,
totalCreditUsd,
error: null,
- activeTab: 'manage',
+ activeTab: 'apiKey',
}),
)
@@ -1722,125 +1693,6 @@ export function useAiCreditsAdapter({
return () => window.removeEventListener('focus', onFocus)
}, [handleRefresh])
- const handleCloseChannel = useCallback(
- async (channelIdInput: string) => {
- const currentState = state
- const channelId = normalizeChannelId(channelIdInput)
- if (!channelId) {
- setState((prev) => ({
- ...prev,
- error: 'Enter a valid channel ID (0x followed by 64 hex characters)',
- }))
- return
- }
- if (!currentState.signerPrvKey) {
- setState((prev) => ({
- ...prev,
- error:
- 'Sign with your payer wallet in Signer Key below to generate the signer private key before closing a channel',
- }))
- return
- }
- if (!fundingVaultAddress) {
- setState((prev) => ({
- ...prev,
- error: 'Funding vault address is not configured',
- }))
- return
- }
-
- try {
- const signer = currentState.signerPubKey
- if (!signer) {
- setState((prev) => ({ ...prev, error: 'Select a signer before closing a channel' }))
- return
- }
- const nonce = await chainClient.getSignerAuthNonce(signer)
- const signature = await signRequestClose({
- signerPrivateKey: currentState.signerPrvKey as `0x${string}`,
- fundingVaultAddress,
- channelId,
- nonce,
- })
-
- await backendClient.closeChannel(channelId, { nonce: nonce.toString(), signature })
- setState((prev) => ({ ...prev, error: null }))
- } catch (err: unknown) {
- setState((prev) => ({
- ...prev,
- error: err instanceof Error ? err.message : 'Close channel failed',
- }))
- }
- },
- [state, backendClient, chainClient, fundingVaultAddress],
- )
-
- const handleWithdrawCredits = useCallback(
- async (withdrawAmount: string) => {
- const currentState = state
- if (!currentState.address || !currentState.signerPubKey) return
- if (!currentState.signerPrvKey) {
- setState((prev) => ({
- ...prev,
- error:
- 'Sign with your payer wallet in Signer Key below to generate the signer private key before withdrawing funds',
- }))
- return
- }
- if (!fundingVaultAddress) {
- setState((prev) => ({
- ...prev,
- error: 'Funding vault address is not configured',
- }))
- return
- }
- if (!withdrawAmount.trim()) {
- setState((prev) => ({ ...prev, error: 'Enter an amount to withdraw' }))
- return
- }
-
- try {
- const amount = usdDisplayToMicro(withdrawAmount.trim())
- const withdrawable = BigInt(currentState.withdrawableUsd ?? '0')
- if (BigInt(amount) <= 0n) {
- setState((prev) => ({ ...prev, error: 'Enter a valid USD amount' }))
- return
- }
- if (BigInt(amount) > withdrawable) {
- setState((prev) => ({ ...prev, error: 'Amount exceeds withdrawable principal' }))
- return
- }
-
- const signer = currentState.signerPubKey as Address
- const payer = currentState.address as Address
- const nonce = await chainClient.getSignerAuthNonce(signer)
- const signature = await signWithdrawPrincipal({
- signerPrivateKey: currentState.signerPrvKey as `0x${string}`,
- fundingVaultAddress,
- signer,
- amountMicro: BigInt(amount),
- recipient: payer,
- nonce,
- })
-
- await backendClient.withdrawCredits(signer, {
- amount,
- recipient: payer,
- nonce: nonce.toString(),
- signature,
- })
- setState((prev) => ({ ...prev, error: null }))
- await handleRefresh()
- } catch (err: unknown) {
- setState((prev) => ({
- ...prev,
- error: err instanceof Error ? err.message : 'Withdraw failed',
- }))
- }
- },
- [state, backendClient, chainClient, fundingVaultAddress, handleRefresh],
- )
-
const handleRetry = useCallback(async () => {
if (configurationError) {
setState((prev) => ({
@@ -1856,9 +1708,6 @@ export function useAiCreditsAdapter({
const handleSetActiveTab = useCallback((tab: AiCreditsWidgetTab) => {
setState((prev) => {
if (needsWalletConnection(prev)) {
- if (tab === 'setup') {
- return mergeStatePreservingNonBuyTab(prev, { activeTab: 'setup', error: null })
- }
return prev
}
if (tab === 'buy') {
@@ -1942,8 +1791,6 @@ export function useAiCreditsAdapter({
verifyGoodId: handleVerifyGoodId,
startPurchase: handleStartPurchase,
setActiveTab: handleSetActiveTab,
- closeChannel: handleCloseChannel,
- withdrawCredits: handleWithdrawCredits,
retry: handleRetry,
}),
[
@@ -1963,8 +1810,6 @@ export function useAiCreditsAdapter({
handleVerifyGoodId,
handleStartPurchase,
handleSetActiveTab,
- handleCloseChannel,
- handleWithdrawCredits,
handleRetry,
],
)
diff --git a/packages/ai-credits-widget/src/aiCreditsApi/gatewayUrlFormats.ts b/packages/ai-credits-widget/src/aiCreditsApi/gatewayUrlFormats.ts
new file mode 100644
index 00000000..a18567e7
--- /dev/null
+++ b/packages/ai-credits-widget/src/aiCreditsApi/gatewayUrlFormats.ts
@@ -0,0 +1,15 @@
+/** Removes trailing slashes so a format can append a path without doubling them. */
+function withoutTrailingSlash(baseUrl: string): string {
+ return baseUrl.replace(/\/+$/, '')
+}
+
+/**
+ * How the gateway base URL is written for each family of tools.
+ * TODO: confirm with AntSeed — these two formats are assumptions until the gateway docs are checked.
+ */
+export const GATEWAY_BASE_URL_FORMATS = {
+ claudeCode: (baseUrl: string) => withoutTrailingSlash(baseUrl),
+ openAiCompatible: (baseUrl: string) => `${withoutTrailingSlash(baseUrl)}/v1`,
+} as const
+
+export type GatewayToolFamily = keyof typeof GATEWAY_BASE_URL_FORMATS
diff --git a/packages/ai-credits-widget/src/aiCreditsApi/types.ts b/packages/ai-credits-widget/src/aiCreditsApi/types.ts
new file mode 100644
index 00000000..3edd5c32
--- /dev/null
+++ b/packages/ai-credits-widget/src/aiCreditsApi/types.ts
@@ -0,0 +1,71 @@
+import type { CreditHistoryQuery, CreditHistoryResponse } from '../backendTypes'
+
+/**
+ * Identifier of a user's AI credits account on the GoodDollar backend.
+ * PROVISIONAL: the payer wallet address, pending confirmation from the backend/vault side (#318 item 12).
+ */
+export type AiCreditsAccountId = string
+
+/** The user's API key as the widget may show it after creation: masked, never the full secret. */
+export interface AiCreditsApiKeySummary {
+ /** Display-safe form of the key, e.g. `sk-…a1b2`. */
+ maskedKey: string
+ /** ISO-8601 timestamp of when the key was created or last rotated. */
+ createdAt: string
+}
+
+/** Monthly spend cap enforced by the gateway for the user's key. */
+export interface AiCreditsSpendLimit {
+ /** Cap in micro-USD. */
+ limitUsdMicro: string
+ /** ISO-8601 timestamp at which the monthly spend counter resets. */
+ resetsAt: string
+}
+
+/** Everything the API Key tab shows about the user's gateway access. */
+export interface AiCreditsApiAccount {
+ accountId: AiCreditsAccountId
+ /** Gateway base URL the user pastes into their tools. Always supplied by the backend, never hardcoded in the widget. */
+ baseUrl: string
+ /** Null when the user has no active key (never bought credits, or revoked it). */
+ apiKey: AiCreditsApiKeySummary | null
+ spendLimit: AiCreditsSpendLimit | null
+ /** Spend in the current calendar month, in micro-USD. */
+ usedThisMonthUsdMicro: string
+}
+
+/** Result of an operation that can mint a new secret. */
+export interface AiCreditsApiKeyIssue {
+ account: AiCreditsApiAccount
+ /**
+ * The full key, returned only when a new secret was minted. Null when a top-up raised
+ * the limit of an existing key. The widget keeps it in memory only and never persists it.
+ */
+ fullKey: string | null
+}
+
+/** Settled purchase the backend turns into a key or a spend-limit top-up. */
+export interface AiCreditsKeyPurchase {
+ accountId: AiCreditsAccountId
+ /** Credit bought by this payment, in micro-USD. */
+ creditUsdMicro: string
+ /** Celo transaction of the payment; lets the backend treat a retry as idempotent. */
+ transactionHash: string
+}
+
+/**
+ * The only surface the widget uses to reach gateway-backed key management.
+ * Implemented by a GoodDollar backend; the widget never calls the gateway directly.
+ */
+export interface AiCreditsApi {
+ getAccount: (accountId: AiCreditsAccountId) => Promise
+ /** Creates the user's key after their first purchase, or raises its spend limit afterwards. */
+ createOrTopUpKey: (purchase: AiCreditsKeyPurchase) => Promise
+ /** Invalidates the current key and returns a fresh one. */
+ rotateKey: (accountId: AiCreditsAccountId) => Promise
+ revokeKey: (accountId: AiCreditsAccountId) => Promise
+ getHistory: (
+ accountId: AiCreditsAccountId,
+ query?: CreditHistoryQuery,
+ ) => Promise
+}
diff --git a/packages/ai-credits-widget/src/assets/antseed-signer-row.png b/packages/ai-credits-widget/src/assets/antseed-signer-row.png
deleted file mode 100644
index 7e107269..00000000
Binary files a/packages/ai-credits-widget/src/assets/antseed-signer-row.png and /dev/null differ
diff --git a/packages/ai-credits-widget/src/assets/assets.d.ts b/packages/ai-credits-widget/src/assets/assets.d.ts
deleted file mode 100644
index c9feb17d..00000000
--- a/packages/ai-credits-widget/src/assets/assets.d.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/**
- * PNG imports resolve to a data URI, inlined by the `dataurl` loader in
- * tsup.config.ts. Consumers always resolve this package through `dist`, so the
- * asset is already embedded by the time it reaches them — no loader required
- * downstream, and no separate file to host or to survive a host page's CSP.
- */
-declare module '*.png' {
- const source: string
- export default source
-}
diff --git a/packages/ai-credits-widget/src/backendClient.ts b/packages/ai-credits-widget/src/backendClient.ts
index 46aa612b..c9b84631 100644
--- a/packages/ai-credits-widget/src/backendClient.ts
+++ b/packages/ai-credits-widget/src/backendClient.ts
@@ -49,35 +49,11 @@ function normalizeAddress(address: string): string {
return address.toLowerCase()
}
-export type WithdrawPrincipalRequest = {
- amount: string
- recipient: string
- nonce: string
- signature: string
-}
-
-export type ChannelOperationRequest = {
- nonce?: string
- signature?: string
-}
-
export type BridgeResponse = {
enabled: boolean
txHash?: string
}
-export type ChannelOperationResponse = {
- channelId: string
- action: 'close' | 'withdraw'
- bridge: BridgeResponse
-}
-
-export type WithdrawPrincipalResponse = {
- account: string
- amountUsd: string
- bridge: BridgeResponse
-}
-
export type OperatorConsentRequest = {
nonce: string
signature: string
@@ -117,14 +93,6 @@ async function readBridgeResponseBody(
return { ...body, bridge }
}
-async function parseBridgeResponse(
- response: Response,
- actionLabel: string,
-): Promise {
- const body = await readBridgeResponseBody(response, actionLabel)
- return body.bridge
-}
-
const DEFAULT_HISTORY_LIMIT = 20
const MAX_HISTORY_LIMIT = 100
@@ -223,14 +191,6 @@ export interface AiCreditsBackendClient {
ref: AccountRef,
options?: { txHashes?: string[]; previousBalance?: string },
): Promise
- closeChannel(
- channelId: string,
- body?: ChannelOperationRequest,
- ): Promise
- withdrawCredits(
- signer: string,
- body: WithdrawPrincipalRequest,
- ): Promise
submitOperatorConsent(
signer: string,
body: OperatorConsentRequest,
@@ -402,35 +362,6 @@ export class ProductionAiCreditsBackendClient implements AiCreditsBackendClient
throw new Error('Settlement polling timeout — credits may still be arriving')
}
- async closeChannel(
- channelId: string,
- body: ChannelOperationRequest = {},
- ): Promise {
- const response = await fetch(
- `${this.backendUrl}/v1/channels/${encodeURIComponent(channelId)}/close`,
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- },
- )
- const bridge = await parseBridgeResponse(response, 'Close channel')
- return { channelId, action: 'close', bridge }
- }
-
- async withdrawCredits(
- signer: string,
- body: WithdrawPrincipalRequest,
- ): Promise {
- const response = await fetch(`${this.accountBase(signer)}/withdraw`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- })
- const bridge = await parseBridgeResponse(response, 'Withdraw')
- return { account: normalizeAddress(signer), amountUsd: body.amount, bridge }
- }
-
async submitOperatorConsent(
signer: string,
body: OperatorConsentRequest,
@@ -503,14 +434,6 @@ export class UnavailableAiCreditsBackendClient implements AiCreditsBackendClient
return this.unavailable()
}
- async closeChannel() {
- return this.unavailable()
- }
-
- async withdrawCredits() {
- return this.unavailable()
- }
-
async submitOperatorConsent() {
return this.unavailable()
}
@@ -554,17 +477,16 @@ export async function buildAccountView(
? normalizeAddress(options.signerAddress)
: null
- // These four reads are independent of one another and span two networks (the
+ // These three reads are independent of one another and span two networks (the
// credit backend and Base). Only the credit profile is load-bearing, so the
// rest degrade on their own rather than taking the whole view down with them:
// a Base RPC hiccup used to discard a perfectly good credit profile.
- const [credit, outstanding, operator, withdrawableUsd] = await Promise.all([
+ const [credit, outstanding, operator] = await Promise.all([
backend.getAccountCredit(payer),
backend.getOutstanding(payer).catch(() => null),
signer
? chain.getSignerOperatorStatus({ payer: normalizedPayer, signer }).catch(() => null)
: Promise.resolve(defaultOperatorStatus(normalizedPayer)),
- signer ? chain.getWithdrawableUsd(signer).catch(() => null) : Promise.resolve('0'),
])
return {
@@ -572,7 +494,6 @@ export async function buildAccountView(
signer,
profile: credit.profile,
operator,
- withdrawableUsd,
// Not rendered anywhere today; '0' keeps the shape without inventing a
// balance the caller would display.
outstandingFundingUsd: outstanding?.outstandingFundingUsd ?? '0',
diff --git a/packages/ai-credits-widget/src/backendTypes.ts b/packages/ai-credits-widget/src/backendTypes.ts
index 12b5fa10..4eac1541 100644
--- a/packages/ai-credits-widget/src/backendTypes.ts
+++ b/packages/ai-credits-widget/src/backendTypes.ts
@@ -77,8 +77,6 @@ export type AccountView = {
* "not authorized", or an already-authorized account looks unconfigured.
*/
operator: SignerOperatorStatus | null
- /** Null when the withdrawable read did not answer. */
- withdrawableUsd: string | null
outstandingFundingUsd: string
outstandingFundingCount: number
}
diff --git a/packages/ai-credits-widget/src/chainClient.ts b/packages/ai-credits-widget/src/chainClient.ts
index c51c45ae..198bf8ce 100644
--- a/packages/ai-credits-widget/src/chainClient.ts
+++ b/packages/ai-credits-widget/src/chainClient.ts
@@ -49,7 +49,6 @@ const DEPOSITS_ABI = parseAbi([
])
const FUNDING_VAULT_ABI = parseAbi([
- 'function withdrawablePrincipal(address signer) view returns (uint256)',
'function usedNonces(address signer) view returns (uint256)',
])
@@ -110,7 +109,6 @@ export interface AiCreditsChainClient {
ref: AccountRef,
operatorStatus?: SignerOperatorStatus,
): Promise
- getWithdrawableUsd(signer: string): Promise
getSignerAuthNonce(signer: string): Promise
}
@@ -246,17 +244,6 @@ export class ProductionAiCreditsChainClient implements AiCreditsChainClient {
}
}
- async getWithdrawableUsd(signer: string): Promise {
- if (!this.fundingVaultAddress) return '0'
- const amount = await (await this.baseClient).readContract({
- address: this.fundingVaultAddress,
- abi: FUNDING_VAULT_ABI,
- functionName: 'withdrawablePrincipal',
- args: [normalizeAddress(signer) as Address],
- })
- return amount.toString()
- }
-
async getSignerAuthNonce(signer: string): Promise {
// Never fall back to a default: the nonce is signed over, so a wrong one produces a
// valid signature the vault will reject — or worse, replay-protect the wrong slot.
diff --git a/packages/ai-credits-widget/src/components/apiKey/ApiKeyCard.tsx b/packages/ai-credits-widget/src/components/apiKey/ApiKeyCard.tsx
new file mode 100644
index 00000000..5d6d65df
--- /dev/null
+++ b/packages/ai-credits-widget/src/components/apiKey/ApiKeyCard.tsx
@@ -0,0 +1,127 @@
+import { Button, ButtonText, Card, Heading, ProgressBar, Spinner, Text, XStack, YStack } from '@goodwidget/ui'
+import type { AiCreditsApiAccount } from '../../aiCreditsApi/types'
+import { formatUsdMicroAmount } from '../../format'
+import { CopyableValueRow } from '../shared/CopyableValueRow'
+import { compactButtonProps, monospaceSingleLineStyle } from '../shared/styles'
+
+interface ApiKeyCardProps {
+ account: AiCreditsApiAccount | null
+ /** True while the first account fetch is in flight, so the empty state is not shown prematurely. */
+ isLoading: boolean
+ /** Key operation in flight; disables the buttons so a rotate cannot be revoked mid-request. */
+ isBusy: boolean
+ onRotate: () => void
+ onRevoke: () => void
+ onBuyCredits: () => void
+}
+
+/** Formats the reset moment as a short calendar date, in UTC so every viewer sees the same day. */
+function formatResetDate(resetsAtIso: string): string {
+ return new Date(resetsAtIso).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ timeZone: 'UTC',
+ })
+}
+
+/** Card showing the user's API key, gateway base URL and monthly spend limit, or an empty state. */
+export function ApiKeyCard({ account, isLoading, isBusy, onRotate, onRevoke, onBuyCredits }: ApiKeyCardProps) {
+ if (isLoading) {
+ return (
+
+ API key
+
+
+ )
+ }
+
+ if (!account?.apiKey) {
+ return (
+
+ API key
+
+ No API key yet
+
+ Buy credits to get an API key for Claude Code, Codex and other AI tools.
+
+
+
+
+ )
+ }
+
+ const { apiKey, spendLimit, baseUrl, usedThisMonthUsdMicro } = account
+
+ return (
+
+ API key
+
+
+
+
+
+ Key
+
+
+
+
+ Active
+
+
+
+
+
+ {apiKey.maskedKey}
+
+
+
+
+
+
+ {spendLimit ? (
+
+
+
+ {formatUsdMicroAmount(usedThisMonthUsdMicro)} of{' '}
+ {formatUsdMicroAmount(spendLimit.limitUsdMicro)} used · Resets{' '}
+ {formatResetDate(spendLimit.resetsAt)}
+
+
+ ) : null}
+
+
+
+
+
+
+
+ )
+}
diff --git a/packages/ai-credits-widget/src/components/apiKey/ApiKeyPanel.tsx b/packages/ai-credits-widget/src/components/apiKey/ApiKeyPanel.tsx
new file mode 100644
index 00000000..3349c9f9
--- /dev/null
+++ b/packages/ai-credits-widget/src/components/apiKey/ApiKeyPanel.tsx
@@ -0,0 +1,138 @@
+import { useState } from 'react'
+import {
+ Button,
+ ButtonText,
+ Icon,
+ Spinner,
+ Text,
+ YStack,
+ createDialog,
+} from '@goodwidget/ui'
+import type { ApiKeyActions, ApiKeyState } from '../../useApiKey'
+import type {
+ AiCreditsWidgetAdapterActions,
+ AiCreditsWidgetAdapterState,
+} from '../../widgetRuntimeContract'
+import { CreditsManagementCard } from '../manage/CreditsManagementCard'
+import { compactButtonProps } from '../shared/styles'
+import { AiCreditsStatusNotice } from '../theme/cards'
+import { ApiKeyCard } from './ApiKeyCard'
+
+interface ApiKeyPanelProps {
+ state: AiCreditsWidgetAdapterState
+ actions: Pick
+ apiKeyState: ApiKeyState
+ apiKeyActions: ApiKeyActions
+ /** False when the host configured no `aiCreditsApi`, so key management cannot work. */
+ isKeyManagementAvailable: boolean
+ onBuyCredits: () => void
+}
+
+/** Content of the API Key tab: credit balance, the user's key, and a refresh control. */
+export function ApiKeyPanel({
+ state,
+ actions,
+ apiKeyState,
+ apiKeyActions,
+ isKeyManagementAvailable,
+ onBuyCredits,
+}: ApiKeyPanelProps) {
+ const [refreshing, setRefreshing] = useState(false)
+
+ const handleRefresh = async () => {
+ setRefreshing(true)
+ try {
+ await Promise.all([actions.refresh(), apiKeyActions.refresh()])
+ } finally {
+ setRefreshing(false)
+ }
+ }
+
+ // The dialog accepts synchronously so it closes at once; the card shows the busy state.
+ const confirmRotate = () => {
+ createDialog({
+ title: 'Rotate API key?',
+ body: 'Your current key stops working immediately. You will get a new key to paste into your tools.',
+ acceptLabel: 'Rotate key',
+ rejectLabel: 'Cancel',
+ onAccept: () => {
+ void apiKeyActions.rotateKey()
+ },
+ onReject: () => undefined,
+ })
+ }
+
+ const confirmRevoke = () => {
+ createDialog({
+ title: 'Revoke API key?',
+ body: 'Any tool using this key stops working immediately. This cannot be undone.',
+ acceptLabel: 'Revoke key',
+ rejectLabel: 'Cancel',
+ onAccept: () => {
+ void apiKeyActions.revokeKey()
+ },
+ onReject: () => undefined,
+ })
+ }
+
+ const visibleError = apiKeyState.error ?? state.error
+
+ return (
+
+ {visibleError && (
+
+
+ {visibleError}
+
+ {apiKeyState.unfulfilledPurchase && (
+
+ )}
+
+ )}
+
+
+
+ {isKeyManagementAvailable ? (
+
+ ) : (
+
+ API keys are coming soon
+
+ Key management is not available yet. Check back shortly.
+
+
+ )}
+
+
+
+ )
+}
diff --git a/packages/ai-credits-widget/src/components/apiKey/ApiKeyReadySheet.tsx b/packages/ai-credits-widget/src/components/apiKey/ApiKeyReadySheet.tsx
new file mode 100644
index 00000000..e9874b64
--- /dev/null
+++ b/packages/ai-credits-widget/src/components/apiKey/ApiKeyReadySheet.tsx
@@ -0,0 +1,189 @@
+import { useEffect, useRef, useState } from 'react'
+import { Button, ButtonText, Drawer, Heading, Icon, Text, XStack, YStack } from '@goodwidget/ui'
+import { GATEWAY_BASE_URL_FORMATS } from '../../aiCreditsApi/gatewayUrlFormats'
+import type { GatewayToolFamily } from '../../aiCreditsApi/gatewayUrlFormats'
+import { AiCreditsStatusNotice } from '../theme/cards'
+import { CopyAnnouncement } from '../shared/CopyAnnouncement'
+import { compactButtonProps } from '../shared/styles'
+import { useCopyFeedback } from '../shared/useCopyFeedback'
+
+interface ApiKeyReadySheetProps {
+ /** Full key to reveal; the sheet is open exactly while this is set. Held in memory by the caller only. */
+ fullKey: string | null
+ /** Gateway base URL from the backend, filled into the snippet. */
+ baseUrl: string
+ /** Called once the user has confirmed they saved the key; the caller must then drop the key. */
+ onDismiss: () => void
+}
+
+const TOOL_FAMILY_LABELS: Record = {
+ claudeCode: 'Claude Code',
+ openAiCompatible: 'Codex & others',
+}
+
+const TOOL_FAMILIES = Object.keys(TOOL_FAMILY_LABELS) as GatewayToolFamily[]
+
+/** Builds the shell snippet the user pastes into their tool's environment. */
+function buildEnvironmentSnippet(
+ toolFamily: GatewayToolFamily,
+ baseUrl: string,
+ fullKey: string,
+): string {
+ const formattedBaseUrl = GATEWAY_BASE_URL_FORMATS[toolFamily](baseUrl)
+ if (toolFamily === 'claudeCode') {
+ return `export ANTHROPIC_BASE_URL="${formattedBaseUrl}"\nexport ANTHROPIC_API_KEY="${fullKey}"`
+ }
+ return `export OPENAI_BASE_URL="${formattedBaseUrl}"\nexport OPENAI_API_KEY="${fullKey}"`
+}
+
+/** Style for secret text that must wrap rather than overflow a 390px sheet. */
+const wrappingMonospaceStyle = {
+ fontFamily: 'monospace',
+ overflowWrap: 'anywhere',
+ whiteSpace: 'pre-wrap',
+} as const
+
+/**
+ * Bottom sheet that shows the full API key once, with a ready-to-paste snippet.
+ * Dismissing without "I've saved my key" asks for confirmation first, because the key cannot be shown again.
+ */
+export function ApiKeyReadySheet({ fullKey, baseUrl, onDismiss }: ApiKeyReadySheetProps) {
+ const [toolFamily, setToolFamily] = useState('claudeCode')
+ const [isConfirmingDismiss, setIsConfirmingDismiss] = useState(false)
+ const { copied: keyCopied, copy: copyKey } = useCopyFeedback()
+ const { copied: snippetCopied, copy: copySnippet } = useCopyFeedback()
+ const headingRef = useRef(null)
+
+ // Each new reveal starts from the default view, not the previous one.
+ useEffect(() => {
+ if (fullKey === null) {
+ setToolFamily('claudeCode')
+ setIsConfirmingDismiss(false)
+ }
+ }, [fullKey])
+
+ // Moves keyboard and screen-reader focus into the sheet whenever its view changes.
+ useEffect(() => {
+ if (fullKey !== null) headingRef.current?.focus()
+ }, [fullKey, isConfirmingDismiss])
+
+ const snippet = fullKey === null ? '' : buildEnvironmentSnippet(toolFamily, baseUrl, fullKey)
+
+ return (
+ setIsConfirmingDismiss(true)}
+ >
+ {fullKey === null ? null : isConfirmingDismiss ? (
+
+
+ Close without saving?
+
+
+ This is the only time your full key is shown. If you lose it, you will need to rotate it
+ to get a new one.
+
+
+
+
+
+
+ ) : (
+
+
+ Your API key is ready
+
+
+
+
+ API key
+
+
+
+ {fullKey}
+
+
+
+
+
+
+
+
+
+
+ Copy your key now — you won't be able to see it again. Anyone who has it can
+ spend your credits, so keep it private.
+
+
+
+
+
+
+ {TOOL_FAMILIES.map((family) => (
+
+ ))}
+
+
+
+ {snippet}
+
+
+
+
+
+
+
+
+ )}
+
+ )
+}
diff --git a/packages/ai-credits-widget/src/components/buy/AmountPicker.tsx b/packages/ai-credits-widget/src/components/buy/AmountPicker.tsx
index 60cd0b69..f329c717 100644
--- a/packages/ai-credits-widget/src/components/buy/AmountPicker.tsx
+++ b/packages/ai-credits-widget/src/components/buy/AmountPicker.tsx
@@ -341,7 +341,7 @@ export function AmountPicker({
<>
- Est. credits
+ Est. GoodDollar AI credits
{formatMinUsdDisplay(quoteDepositPrincipalUsd(quote, gdUsdPerToken)) +
diff --git a/packages/ai-credits-widget/src/components/buy/GenerateSignerKeyPanel.tsx b/packages/ai-credits-widget/src/components/buy/GenerateSignerKeyPanel.tsx
deleted file mode 100644
index 5e20e2f8..00000000
--- a/packages/ai-credits-widget/src/components/buy/GenerateSignerKeyPanel.tsx
+++ /dev/null
@@ -1,256 +0,0 @@
-import React, { useState } from 'react'
-import { Button, ButtonText, Card, Heading, Icon, Text, XStack, YStack } from '@goodwidget/ui'
-import { AiCreditsStatusNotice } from '../theme/cards'
-import { AntseedSignerRow } from '../setup/AntseedSignerRow'
-import { monospaceSingleLineStyle, compactButtonProps } from '../shared/styles'
-import { useCopyFeedback } from '../shared/useCopyFeedback'
-
-interface GenerateSignerKeyPanelProps {
- signerPubKey: string | null
- signerPrvKey: string | null
- /** Doubles as the screen selector: false shows generate/save, true shows the Antseed guide. */
- signerPubKeySaved: boolean
- onGenerate: () => void | Promise
- onConfirm: () => void
- /** Advances past the signer key step. */
- onProceed?: () => void
- proceedLabel?: string
- /** Opens the API setup route in the first stepper step. */
- onOpenApiSetup?: () => void
- embedded?: boolean
-}
-
-/** Numbered heading, so each screen reads as a short ordered list. */
-function NumberedStep({
- index,
- title,
- note,
-}: {
- index: number
- title: string
- /** Caveat shown under the title, aligned with it rather than the number. */
- note?: string
-}) {
- return (
-
-
-
-
- {index}
-
-
-
- {title}
-
-
- {note && (
-
- {note}
-
- )}
-
- )
-}
-
-/**
- * Generating a signer key, split across two screens.
- *
- * One screen previously created the key and explained where to paste it into
- * Antseed — two unrelated jobs, and too much at once. Screen one now ends when
- * the key is saved; screen two covers where it goes. The import route is
- * deliberately untouched.
- */
-export function GenerateSignerKeyPanel({
- signerPubKey,
- signerPrvKey,
- signerPubKeySaved,
- onGenerate,
- onConfirm,
- onProceed,
- proceedLabel = 'Continue to Authorize Credits Management',
- onOpenApiSetup,
- embedded = false,
-}: GenerateSignerKeyPanelProps) {
- const { copied: copiedAddress, copy: copyAddress } = useCopyFeedback()
- const { copied: copiedPrivate, copy: copyPrivate } = useCopyFeedback()
- const [isPrivateKeyVisible, setIsPrivateKeyVisible] = useState(false)
- const [isGenerating, setIsGenerating] = useState(false)
-
- async function handleGenerate() {
- setIsGenerating(true)
- try {
- await onGenerate()
- } finally {
- setIsGenerating(false)
- }
- }
-
- const Shell = embedded ? YStack : Card
-
- // ---- Screen 2: where the key goes -------------------------------------
- if (signerPubKeySaved) {
- return (
-
- Add your Signer Key to Antseed
-
- You'll need to do this to use your AI credits. If you haven't downloaded Antseed
- Desktop yet, you can do this later.
-
-
-
-
-
-
-
-
-
-
-
-
-
- The address you see when you paste your private key is the public address used for your
- AI credits.
-
-
-
- {onOpenApiSetup && (
-
-
-
- Advanced user? Use{' '}
-
- API Setup
- {' '}
- instead to use your AI credits through your terminal.
-
-
- )}
-
- {onProceed && (
-
- )}
-
- )
- }
-
- // ---- Screen 1: make the key, save the key ------------------------------
- return (
-
- Signer Key
-
- Sign a message with your wallet to generate your Antseed Signer Key. Save the private key —
- you'll need it to use your AI credits.
-
-
-
-
-
- {signerPubKey && (
-
-
-
- Signer Address
-
-
-
- {signerPubKey}
-
-
-
-
- {signerPrvKey && (
- <>
-
-
- Signer Private Key — save this securely
-
-
-
-
-
- {isPrivateKeyVisible
- ? signerPrvKey
- : '•'.repeat(Math.min(48, signerPrvKey.length))}
-
-
-
-
-
- Revealing your private key can expose your account. Never share it — store it in a
- secure place.
-
-
-
-
- >
- )}
-
- )}
-
- )
-}
diff --git a/packages/ai-credits-widget/src/components/buy/OperatorConsentStep.tsx b/packages/ai-credits-widget/src/components/buy/OperatorConsentStep.tsx
deleted file mode 100644
index 0149550c..00000000
--- a/packages/ai-credits-widget/src/components/buy/OperatorConsentStep.tsx
+++ /dev/null
@@ -1,174 +0,0 @@
-import React, { useState } from 'react'
-import {
- Button,
- ButtonText,
- Card,
- Heading,
- Icon,
- PermissionList,
- PermissionRow,
- Spinner,
- Text,
- XStack,
- YStack,
-} from '@goodwidget/ui'
-import { truncateAddress, compactButtonProps, monospaceSingleLineStyle } from '../shared/styles'
-
-interface OperatorConsentStepProps {
- signerPubKey: string | null
- signerPrvKey: string | null
- operatorSignature?: string | null
- operatorConsented: boolean
- operatorConsentPending?: boolean
- onSign: () => Promise
- /** Signer key this wallet derives, when the browser already knows it. */
- derivedSignerAddress?: string | null
- /** Re-derives this wallet's signer key, for a browser that no longer holds it. */
- onRestoreKey?: () => Promise
- embedded?: boolean
-}
-
-function ConsentBullet({ children }: { children: React.ReactNode }) {
- return (
-
-
- •
-
-
- {children}
-
-
- )
-}
-
-export function OperatorConsentStep({
- signerPubKey,
- signerPrvKey,
- operatorSignature = null,
- operatorConsented,
- operatorConsentPending = false,
- onSign,
- derivedSignerAddress = null,
- onRestoreKey,
- embedded = false,
-}: OperatorConsentStepProps) {
- const [restorePending, setRestorePending] = useState(false)
- const canSign = Boolean(signerPubKey && (signerPrvKey || operatorSignature))
- const isBusy = operatorConsentPending
-
- // Nothing here can be signed without the signer key. Rather than show a button
- // that cannot fire, offer the action that actually unblocks it — unless this
- // wallet derives a different signer key, in which case re-deriving would switch
- // signers behind the user's back and importing is the only honest route.
- const needsKey = Boolean(signerPubKey) && !canSign && !operatorConsented
- const derivesDifferentKey =
- needsKey &&
- Boolean(derivedSignerAddress) &&
- derivedSignerAddress?.toLowerCase() !== signerPubKey?.toLowerCase()
- const canRestoreKey = needsKey && !derivesDifferentKey && Boolean(onRestoreKey)
-
- const Shell = embedded ? YStack : Card
-
- const handleRestore = async () => {
- if (!onRestoreKey) return
- setRestorePending(true)
- try {
- await onRestoreKey()
- } finally {
- setRestorePending(false)
- }
- }
-
- return (
-
- Authorize Credits Management
-
- A one-time, on-chain approval — not a payment. Here's exactly what it does and
- doesn't allow:
-
-
- {/* Scope confirmed with the AntseedDeposits contract owner: the operator can
- only fulfil purchases the signer initiates, withdrawals return to the payer,
- and the role carries no ERC-20 allowance and nothing on Celo. Do not widen
- these claims without re-checking. */}
-
-
- move funds inside your credit balance, to fulfil purchases you initiate.
-
-
- touch your G$ wallet, your savings, or anything outside this purchase flow.
-
-
-
-
- It costs no gas and moves no funds.
-
- One time only — later purchases reuse it, and you can revoke it at any time.
-
-
-
- {signerPubKey && (
-
- Signer Address:{' '}
-
- {truncateAddress(signerPubKey)}
-
-
- )}
-
- {operatorConsented ? (
-
-
- Credits management authorized
-
- ) : derivesDifferentKey ? (
-
- This signer key was not generated by the connected wallet, so it cannot be restored here.
- Import its private key from the Signer key step to authorize it.
-
- ) : canRestoreKey ? (
- <>
-
- This browser does not hold your signer key. Restore it from your wallet to continue —
- the same wallet always produces the same key.
-
-
- >
- ) : (
-
- )}
-
- )
-}
diff --git a/packages/ai-credits-widget/src/components/setup/SetupBonusHighlight.tsx b/packages/ai-credits-widget/src/components/guide/BonusHighlight.tsx
similarity index 96%
rename from packages/ai-credits-widget/src/components/setup/SetupBonusHighlight.tsx
rename to packages/ai-credits-widget/src/components/guide/BonusHighlight.tsx
index 88518b1f..106175d5 100644
--- a/packages/ai-credits-widget/src/components/setup/SetupBonusHighlight.tsx
+++ b/packages/ai-credits-widget/src/components/guide/BonusHighlight.tsx
@@ -1,7 +1,7 @@
import React, { useState } from 'react'
import { Card, Icon, Text, XStack, YStack } from '@goodwidget/ui'
-interface SetupBonusHighlightProps {
+interface BonusHighlightProps {
/** Bonus applied to one-time deposits, in percent. */
depositBonusPercent: number
/** Bonus applied to monthly streams, in percent. */
@@ -15,11 +15,11 @@ interface SetupBonusHighlightProps {
* Collapsed it states the headline bonus; expanded it explains the
* verification requirement.
*/
-export function SetupBonusHighlight({
+export function BonusHighlight({
depositBonusPercent,
streamBonusPercent,
isGoodIdVerified,
-}: SetupBonusHighlightProps) {
+}: BonusHighlightProps) {
const [isExpanded, setIsExpanded] = useState(false)
const maxBonusPercent = Math.max(depositBonusPercent, streamBonusPercent)
diff --git a/packages/ai-credits-widget/src/components/setup/SetupFaqView.tsx b/packages/ai-credits-widget/src/components/guide/FaqView.tsx
similarity index 51%
rename from packages/ai-credits-widget/src/components/setup/SetupFaqView.tsx
rename to packages/ai-credits-widget/src/components/guide/FaqView.tsx
index 8d786bcd..861124c5 100644
--- a/packages/ai-credits-widget/src/components/setup/SetupFaqView.tsx
+++ b/packages/ai-credits-widget/src/components/guide/FaqView.tsx
@@ -1,6 +1,5 @@
import React, { useState } from 'react'
import {
- Anchor,
Button,
ButtonText,
Card,
@@ -11,17 +10,14 @@ import {
YStack,
} from '@goodwidget/ui'
-/** AntSeed website — same short link used on the setup guidance card. */
-const ANTSEED_SITE_URL = 'https://ubi.gd/46pjeqF'
-
/**
- * Matches the two inline markups an answer paragraph may carry: `**bold**` for
- * emphasised terms and `[label](href)` for inline links.
+ * Matches the inline markup an answer paragraph may carry: `**bold**` for
+ * emphasised terms.
*/
-const INLINE_MARKUP = /\*\*([^*]+)\*\*|\[([^\]]+)\]\(([^)]+)\)/g
+const INLINE_MARKUP = /\*\*([^*]+)\*\*/g
/**
- * Splits a paragraph into plain text, bold, and link runs. Answers are authored
+ * Splits a paragraph into plain text and bold runs. Answers are authored
* copy — not user input — so a tiny markup subset beats threading arrays of
* styled fragments through every FAQ entry.
*/
@@ -33,22 +29,11 @@ function renderInlineRuns(paragraph: string): React.ReactNode[] {
const start = match.index ?? 0
if (start > cursor) runs.push(paragraph.slice(cursor, start))
- const [, boldText, linkLabel, linkHref] = match
- if (boldText) {
- runs.push(
-
- {boldText}
- ,
- )
- } else {
- runs.push(
-
-
- {linkLabel}
-
- ,
- )
- }
+ runs.push(
+
+ {match[1]}
+ ,
+ )
cursor = start + match[0].length
}
@@ -57,13 +42,12 @@ function renderInlineRuns(paragraph: string): React.ReactNode[] {
}
/**
- * FAQ items focused on the AntSeed setup and onboarding experience.
- * These are distinct from the purchase-flow FAQ in BuyCreditsFaq.tsx.
+ * FAQ items for the API key credits flow.
*
* `answer` is a list of paragraphs so longer entries can breathe. Paragraphs
- * may use `**bold**` and `[label](href)` — see renderInlineRuns.
+ * may use `**bold**` — see renderInlineRuns.
*/
-const SETUP_FAQ_ITEMS = [
+const FAQ_ITEMS = [
{
id: 'goodwallet-only',
question: 'I only claim G$ UBI — can I still use this?',
@@ -73,25 +57,13 @@ const SETUP_FAQ_ITEMS = [
],
},
{
- id: 'what-is-antseed',
- question: 'What is Antseed?',
- answer: [
- 'Antseed is a free, open-source desktop application that lets you use your AI credits with ' +
- 'supported AI tools.',
- 'Your connected wallet private key is never shared with Antseed. Antseed uses your separate ' +
- '**Signer Private Key** to access your AI credits. You can ' +
- `[learn more about Antseed here](${ANTSEED_SITE_URL}).`,
- ],
- },
- {
- id: 'why-credit-management',
- question: 'Why do I need to enable Credit Management?',
+ id: 'what-is-api-key',
+ question: 'What is the API key for?',
answer: [
- 'Enabling Credit Management allows you to use G$ for AI credits on Antseed.',
- 'It authorizes the GoodDollar operator to manage the AI credits associated with your Signer, ' +
- 'so you can deposit or subscribe with G$ and use those credits through Antseed.',
- 'This only applies to your AI credits and does not give access to your connected wallet or ' +
- 'its private key.',
+ 'Your API key lets AI tools such as Claude Code and Codex use your GoodDollar AI credits. ' +
+ 'Paste the base URL and key into your tool and it works like any other API key.',
+ 'Your connected wallet private key is never shared. The API key only lets a tool spend your ' +
+ 'AI credits, up to your monthly spend limit.',
],
},
{
@@ -108,38 +80,33 @@ const SETUP_FAQ_ITEMS = [
id: 'no-code',
question: 'Do I need to know how to code?',
answer: [
- 'No. You can set up your Signer Key and buy credits directly in this widget. Then use your ' +
- '**Signer Private Key** in the Antseed Desktop App to access your credits.',
- 'Advanced users can also use the API.',
+ 'No. Buy credits in this widget, then copy the base URL and API key into your AI tool. ' +
+ 'There is nothing to install.',
],
},
{
id: 'compatible-tools',
question: 'Which tools can I use my credits with?',
answer: [
- 'You can use your credits with AI tools supported through Antseed, including Claude Code, ' +
- 'Codex, and other supported AI tools.',
+ 'Claude Code, Codex, and other AI tools that let you set a custom base URL and API key.',
],
},
{
- id: 'lost-signer-key',
- question: 'What if I lose my Signer Private Key?',
+ id: 'lost-api-key',
+ question: 'What if I lose my API key?',
answer: [
- "If you're using the same device, you can view your Signer Private Key again from the " +
- '**Manage** section.',
- 'If you no longer have access to it, reconnect your connected wallet and select ' +
- '**Generate Signer Key** again. Your Signer Key is generated deterministically, so you’ll get the same ' +
- 'key again.',
- 'You can also import a backed-up Signer Private Key.',
+ 'For your security the full key is only shown once, right after it is created, so it cannot be ' +
+ 'shown again.',
+ 'Open the **API Key** tab and choose **Rotate** to get a new key. The old key stops working ' +
+ 'immediately, so update it in any tool that uses it. Your credits are not affected.',
],
},
{
id: 'unused-credits',
question: 'Can I get unused credits back?',
answer: [
- 'Yes. The **Withdrawable** amount shown in the Manage section can be withdrawn back to your ' +
- 'connected wallet.',
- 'Bonus credits received through GoodID are not withdrawable and can only be used for AI usage.',
+ 'Pending policy confirmation: how unused credits are handled has not been finalised yet. ' +
+ 'This answer will be updated once it is.',
],
},
{
@@ -184,17 +151,16 @@ function FaqItem({ question, answer, expanded, onToggle }: FaqItemProps) {
)
}
-interface SetupFaqViewProps {
- /** Callback to return to the normal buy view. */
+interface FaqViewProps {
+ /** Callback to return to the normal tab view. */
onBack: () => void
}
/**
- * In-widget FAQ view rendered inside the Setup tab content area when the user
- * clicks the FAQs button on the guidance card. Contains setup and onboarding
- * focused questions, distinct from the purchase-flow FAQ.
+ * In-widget FAQ view rendered in place of the tab content when the user
+ * clicks the FAQs button on the guidance card.
*/
-export function SetupFaqView({ onBack }: SetupFaqViewProps) {
+export function FaqView({ onBack }: FaqViewProps) {
const [expandedId, setExpandedId] = useState(null)
return (
@@ -203,14 +169,14 @@ export function SetupFaqView({ onBack }: SetupFaqViewProps) {
{/* FAQ list */}
- {SETUP_FAQ_ITEMS.map((item, index) => (
+ {FAQ_ITEMS.map((item, index) => (
{index > 0 && }
void
/** Callback to display the FAQ inside the widget. */
@@ -25,29 +22,28 @@ interface SetupGuidanceCardProps {
/**
* Guidance card rendered above the widget tab navigation.
- * Presents a concise "WHAT'S INVOLVED" summary and three entry points:
+ * Presents a concise "WHAT'S INVOLVED" summary and two entry points:
* - How to use (in-widget guide)
- * - AntSeed site (external link)
* - FAQs (in-widget FAQ)
*/
-export function SetupGuidanceCard({
+export function GuidanceCard({
onHowToUse,
onFaq,
activeHelpView,
depositBonusPercent,
streamBonusPercent,
isGoodIdVerified,
-}: SetupGuidanceCardProps) {
+}: GuidanceCardProps) {
return (
// Rendered flush on the widget background — no card surface, so it reads as
// part of the header rather than a separate panel.
{/* Tagline */}
- GoodDollar supports buying Antseed AI credits with G$. Use them in Antseed to access supported AI tools such as Claude Code and Codex.
+ Buy AI credits with G$ and get an API key for Claude Code, Codex and other AI tools. No install needed.
-
- Get Antseed{' '}
+ Get your API key{' '}
- — Use Antseed to use your AI credits.
+ — buy credits to receive a key you can paste into your AI tool.
@@ -143,26 +139,6 @@ export function SetupGuidanceCard({
How to use
- {/* AntSeed site — external link */}
-
-
-
-
{/* FAQs */}