From e95cee104d4590d0fcbc7fcee42fce079034aedd Mon Sep 17 00:00:00 2001 From: "goodbounties-nanoclaw-agent[bot]" <307944451+goodbounties-nanoclaw-agent[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:23:56 +0000 Subject: [PATCH] [gdpatchagent] feat(ai-credits-widget): API key tab, key-ready sheet and aiCreditsApi client (Stage 0) Replaces the Antseed Desktop / signer-key setup flow with hosted-gateway API keys: Buy Credits / API Key / History tabs, rotate and revoke dialogs, a one-time key sheet, a typed aiCreditsApi client with a Storybook/dev-only mock, and rewritten guide and FAQ copy. The purchase path is unchanged until Stage 1. Refs #318, #319. Co-Authored-By: Claude Code On-Behalf-Of: gdpatchagent[onecli] (yaskkeryodtdijpv) --- apps/ai-credits-web/index.html | 2 +- apps/ai-credits-web/src/App.tsx | 124 +----- .../ai-credits-web/tests/landing-page.spec.ts | 44 +- .../tests/purchase-only.spec.ts | 34 -- .../ai-credits-widget/AiCreditsWidget.mdx | 58 +-- .../AiCreditsWidgetQA.stories.tsx | 129 ++---- .../helpers/aiCreditsWidgetStories.tsx | 283 ++++--------- .../ai-credits-widget/src/AiCreditsWidget.tsx | 303 +++++-------- packages/ai-credits-widget/src/adapter.ts | 179 +------- .../src/aiCreditsApi/gatewayUrlFormats.ts | 15 + .../src/aiCreditsApi/types.ts | 71 ++++ .../src/assets/antseed-signer-row.png | Bin 13080 -> 0 bytes .../ai-credits-widget/src/assets/assets.d.ts | 10 - .../ai-credits-widget/src/backendClient.ts | 83 +--- .../ai-credits-widget/src/backendTypes.ts | 2 - packages/ai-credits-widget/src/chainClient.ts | 13 - .../src/components/apiKey/ApiKeyCard.tsx | 127 ++++++ .../src/components/apiKey/ApiKeyPanel.tsx | 138 ++++++ .../components/apiKey/ApiKeyReadySheet.tsx | 189 +++++++++ .../src/components/buy/AmountPicker.tsx | 2 +- .../components/buy/GenerateSignerKeyPanel.tsx | 256 ----------- .../components/buy/OperatorConsentStep.tsx | 174 -------- .../BonusHighlight.tsx} | 6 +- .../SetupFaqView.tsx => guide/FaqView.tsx} | 106 ++--- .../GuidanceCard.tsx} | 44 +- .../src/components/guide/HowToUseView.tsx | 104 +++++ .../src/components/history/HistoryTab.tsx | 109 +---- .../ai-credits-widget/src/components/index.ts | 16 +- .../manage/CreditsManagementCard.tsx | 123 +----- .../components/manage/RevokeConsentStep.tsx | 104 ----- .../components/manage/SignerOperatorCard.tsx | 380 ----------------- .../components/setup/AntseedSetupPanel.tsx | 146 ------- .../src/components/setup/AntseedSignerRow.tsx | 62 --- .../src/components/setup/HowToUseView.tsx | 288 ------------- .../components/setup/SetupOnboardingFlow.tsx | 172 -------- .../src/components/setup/SignerKeyPanel.tsx | 230 ---------- .../src/components/shared/AddressView.tsx | 35 -- .../components/shared/CopyAnnouncement.tsx | 19 + .../components/shared/CopyableValueRow.tsx | 53 +++ .../src/components/shared/constants.ts | 8 - .../src/components/shared/tooltips.tsx | 23 +- packages/ai-credits-widget/src/element.ts | 3 + packages/ai-credits-widget/src/index.ts | 12 + .../src/mocked/AiCreditsMockWidget.tsx | 3 + .../src/mocked/aiCreditsApi.ts | 161 +++++++ .../src/mocked/backendClient.ts | 13 - .../src/mocked/chainClient.ts | 4 - .../ai-credits-widget/src/mocked/index.ts | 1 + .../ai-credits-widget/src/signerSignatures.ts | 75 ---- .../src/useAiCreditsHistory.ts | 89 +--- packages/ai-credits-widget/src/useApiKey.ts | 174 ++++++++ .../src/widgetRuntimeContract.ts | 12 +- packages/ai-credits-widget/tsup.config.ts | 4 - .../widgets/ai-credits-widget/states.spec.ts | 399 +++++++----------- .../test-results/acw-01-disconnected.png | Bin 110070 -> 91347 bytes .../test-results/acw-02-purchase-setup.png | Bin 156948 -> 138234 bytes .../test-results/acw-03-quote-ready.png | Bin 134023 -> 115250 bytes .../acw-04-quote-ready-goodid.png | Bin 134312 -> 115561 bytes .../test-results/acw-05-payment-pending.png | Bin 86299 -> 67279 bytes .../test-results/acw-06-payment-confirmed.png | Bin 85748 -> 68135 bytes .../test-results/acw-07-api-key-tab.png | Bin 0 -> 136042 bytes .../acw-07-credits-management.png | Bin 157016 -> 0 bytes .../acw-08-insufficient-g-balance.png | Bin 98515 -> 80971 bytes .../test-results/acw-09-payment-failed.png | Bin 133481 -> 114878 bytes .../acw-10-backend-unavailable.png | Bin 93926 -> 76276 bytes .../test-results/acw-11-unsupported-chain.png | Bin 90426 -> 71881 bytes .../test-results/acw-12-connecting.png | Bin 109425 -> 91076 bytes .../test-results/acw-13-history-tab.png | Bin 115487 -> 96388 bytes .../acw-14-appkit-connect-no-config.png | Bin 0 -> 25637 bytes .../test-results/acw-15-buy-tab-error.png | Bin 152708 -> 124853 bytes .../acw-15-multi-buyer-manage.png | Bin 155675 -> 0 bytes .../acw-15-multi-signer-manage.png | Bin 175990 -> 0 bytes .../test-results/acw-16-deep-link-buyer.png | Bin 122797 -> 0 bytes .../test-results/acw-16-deep-link-signer.png | Bin 133706 -> 0 bytes .../acw-17-multi-buyer-history.png | Bin 102903 -> 0 bytes .../acw-17-multi-signer-history.png | Bin 118205 -> 0 bytes .../test-results/acw-18-import-key-link.png | Bin 195955 -> 0 bytes .../acw-19-deep-link-consent-pending.png | Bin 164365 -> 0 bytes .../acw-20-guidance-card-default.png | Bin 142046 -> 123470 bytes .../test-results/acw-20-setup-tab.png | Bin 100599 -> 0 bytes .../acw-21-guidance-how-to-use.png | Bin 183851 -> 123362 bytes .../acw-22-guidance-back-to-buying.png | Bin 100599 -> 123470 bytes .../test-results/acw-23-guidance-faq.png | Bin 125509 -> 98079 bytes .../acw-24-guidance-tab-switch.png | Bin 118106 -> 95538 bytes .../acw-25-download-antseed-step.png | Bin 100599 -> 0 bytes .../acw-26-download-antseed-tabs.png | Bin 100599 -> 0 bytes .../test-results/acw-27-wallet-controls.png | Bin 126784 -> 104783 bytes .../acw-28-wallet-controls-hidden.png | Bin 125108 -> 102617 bytes .../test-results/acw-29-api-key-tab-empty.png | Bin 0 -> 127882 bytes .../acw-30-api-key-tab-coming-soon.png | Bin 0 -> 98133 bytes .../test-results/acw-31-api-key-tab-error.png | Bin 0 -> 108696 bytes .../acw-32-api-key-ready-sheet.png | Bin 0 -> 152205 bytes .../acw-33-buy-tab-unavailable.png | Bin 0 -> 75537 bytes .../version-disconnected-desktop-dark.png | Bin 110070 -> 91464 bytes .../version-disconnected-mobile-dark.png | Bin 100786 -> 81697 bytes 95 files changed, 1620 insertions(+), 3594 deletions(-) delete mode 100644 apps/ai-credits-web/tests/purchase-only.spec.ts create mode 100644 packages/ai-credits-widget/src/aiCreditsApi/gatewayUrlFormats.ts create mode 100644 packages/ai-credits-widget/src/aiCreditsApi/types.ts delete mode 100644 packages/ai-credits-widget/src/assets/antseed-signer-row.png delete mode 100644 packages/ai-credits-widget/src/assets/assets.d.ts create mode 100644 packages/ai-credits-widget/src/components/apiKey/ApiKeyCard.tsx create mode 100644 packages/ai-credits-widget/src/components/apiKey/ApiKeyPanel.tsx create mode 100644 packages/ai-credits-widget/src/components/apiKey/ApiKeyReadySheet.tsx delete mode 100644 packages/ai-credits-widget/src/components/buy/GenerateSignerKeyPanel.tsx delete mode 100644 packages/ai-credits-widget/src/components/buy/OperatorConsentStep.tsx rename packages/ai-credits-widget/src/components/{setup/SetupBonusHighlight.tsx => guide/BonusHighlight.tsx} (96%) rename packages/ai-credits-widget/src/components/{setup/SetupFaqView.tsx => guide/FaqView.tsx} (51%) rename packages/ai-credits-widget/src/components/{setup/SetupGuidanceCard.tsx => guide/GuidanceCard.tsx} (76%) create mode 100644 packages/ai-credits-widget/src/components/guide/HowToUseView.tsx delete mode 100644 packages/ai-credits-widget/src/components/manage/RevokeConsentStep.tsx delete mode 100644 packages/ai-credits-widget/src/components/manage/SignerOperatorCard.tsx delete mode 100644 packages/ai-credits-widget/src/components/setup/AntseedSetupPanel.tsx delete mode 100644 packages/ai-credits-widget/src/components/setup/AntseedSignerRow.tsx delete mode 100644 packages/ai-credits-widget/src/components/setup/HowToUseView.tsx delete mode 100644 packages/ai-credits-widget/src/components/setup/SetupOnboardingFlow.tsx delete mode 100644 packages/ai-credits-widget/src/components/setup/SignerKeyPanel.tsx delete mode 100644 packages/ai-credits-widget/src/components/shared/AddressView.tsx create mode 100644 packages/ai-credits-widget/src/components/shared/CopyAnnouncement.tsx create mode 100644 packages/ai-credits-widget/src/components/shared/CopyableValueRow.tsx delete mode 100644 packages/ai-credits-widget/src/components/shared/constants.ts create mode 100644 packages/ai-credits-widget/src/mocked/aiCreditsApi.ts create mode 100644 packages/ai-credits-widget/src/useApiKey.ts create mode 100644 tests/widgets/ai-credits-widget/test-results/acw-07-api-key-tab.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-07-credits-management.png create mode 100644 tests/widgets/ai-credits-widget/test-results/acw-14-appkit-connect-no-config.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-15-multi-buyer-manage.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-15-multi-signer-manage.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-16-deep-link-buyer.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-16-deep-link-signer.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-17-multi-buyer-history.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-17-multi-signer-history.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-18-import-key-link.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-19-deep-link-consent-pending.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-20-setup-tab.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-25-download-antseed-step.png delete mode 100644 tests/widgets/ai-credits-widget/test-results/acw-26-download-antseed-tabs.png create mode 100644 tests/widgets/ai-credits-widget/test-results/acw-29-api-key-tab-empty.png create mode 100644 tests/widgets/ai-credits-widget/test-results/acw-30-api-key-tab-coming-soon.png create mode 100644 tests/widgets/ai-credits-widget/test-results/acw-31-api-key-tab-error.png create mode 100644 tests/widgets/ai-credits-widget/test-results/acw-32-api-key-ready-sheet.png create mode 100644 tests/widgets/ai-credits-widget/test-results/acw-33-buy-tab-unavailable.png 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 7e10726902d320d3531a0a189b7d21fcf6eeb567..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13080 zcmXY11yq#J*Iq?MLK;C35TrY$S&#*!Lpr6qI~MQ<(kb1sba$81xzgP%-Q9dI|MQ)* zhh^v9d1u}`^W1x%I}@xRC-DxI2o(eZy_5U~Q38QpJ_7%nzkLb(9lom&0D;hD%tb{N zBt=C(DLB}gm|GcxKyImVYRKx}``@Q)DUrW=3lWyumc@$35te$(YvK-$RI^j_p?HGB`V!_l@aKCZ|&o7ObhH{ zaPkX}5ke^qgv?!$FFqBY-Bh82IGf1f0|Z9GBz$4-c_jS}P`bRa?lv~%-hUM!Fd#NV z+R9bI!8!i))<$N5hgJJ-up+!Ac8fm|iKNmWsV#zU;O zk<~PTbd`KvWR&LE(O8y9zH0{h8Lc=R9QfoX^qv#qpSJ#{zM$?h+~BQj@fH&A!+h&E zgSF-)DF<hsW6nhL_ zRLW4IT&nFD=I&HwCVJncHJ<*Qsl-h((1n28ekXh&$R5DIRPQ)CBkTFkIg~Q>`UOd} zm-e+V<5xxDOnR48#@}7NMQ+;i$y;PFqR@Fs$L!k!dmlx)ir?IRJaXw|{H$NVn9Oo< zLb{a0p&{RIf)h+nL}AL0E1n`eEB}EyUZSdxcNj&z?kd%}&^eZy#C>%w{D$54Ezdaz z(r27I56WXAG}Mj^tYBX+yHp>&^0ynJk9%0E{lUn*lanuUuCC}*s{Y^xIf@YW{k#eh zqUz5?MpUug3!Yl^$L?IPdJuROh?YjmbB^`Tz!6_VaMe73teBEV+=2GEPwxhSZ}f; z6F zeGBzvhVUFaW(WyFyM9+X$pj4dgj6b(;1qWgtva@a)Eer{NTddF*u6glsoA|HjYK=9 zySDN|(Tz}Bb-p&gr+)+;^|WJ~y%POT@J~#~=djO4Sa~=hZ*%<*{6+maj&*iFwS2}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Z?7B7dRaln0%UVxwzBugc9@fXsRni0giP>07p2uYjIyK33}`_0#Drq61B+ads{a7SMDfsencVCYClBNnu}R~=W+%)J990C^H%_J7 z>cS1qqO=ndNcmOrqHd06PI;)gFpSsQ1Sl!jgzhPK%UQPm}@xF1EQr=>m69@^X3l)?O9a{{8JN_wrDO=C3N z+^&m7TrMq=9uAFOmGIx&Gl{a6+-7BG)(v6xwm?xWIwM1`UAGme;SfK31o^stwX{{H zLsBqLFRbM*iv5twn2vH(96|^Ut8kycnzqrlHCwi`d-}ZD2nyNjC+s81b4hvm<+{DVJMupkTL;85 zEKeqd)+BzLxIpY(KF1WFiqQ#cQv^TwMPC>Zz-(V-UQyrLJs!~1Gx;2uMCg&9Oa9*S;*-A+eo0} zWn;)2`f( 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 */} + + {/* RESTORE: walkthrough video and written-guide link go here once they are re-recorded for the API key flow. */} + + {/* Quick summary section */} + + + QUICK SUMMARY + + + + {QUICK_SUMMARY_STEPS.map((step) => ( + + {/* Step number circle */} + + + {step.index} + + + + {/* Step content */} + + + + {step.title} + + + {step.tabLabel} + + + + {step.description} + + + + ))} + + + + ) +} diff --git a/packages/ai-credits-widget/src/components/history/HistoryTab.tsx b/packages/ai-credits-widget/src/components/history/HistoryTab.tsx index e6092261..39dd8563 100644 --- a/packages/ai-credits-widget/src/components/history/HistoryTab.tsx +++ b/packages/ai-credits-widget/src/components/history/HistoryTab.tsx @@ -19,15 +19,10 @@ import { compactButtonProps } from '../shared/styles' import type { AiCreditsHistoryActions, AiCreditsHistoryState, - SignerAddressFilter, CreditHistorySource, CreditHistoryStatusFilter, } from '../../useAiCreditsHistory' -import { - BUYER_FILTER_ALL, - HISTORY_LOOKBACK_DAYS, - getLast90DaysRange, -} from '../../useAiCreditsHistory' +import { HISTORY_LOOKBACK_DAYS, getLast90DaysRange } from '../../useAiCreditsHistory' const STATUS_OPTIONS = [ { label: 'All', value: 'all' }, @@ -45,8 +40,6 @@ const SOURCE_PILL_OPTIONS: { id: CreditHistorySource; label: string }[] = [ export interface HistoryTabProps { state: AiCreditsHistoryState actions: AiCreditsHistoryActions - /** Known signer records to populate the signer filter dropdown. */ - knownSigners?: { address: string; label?: string }[] } function sourceLabel(source: CreditHistorySource): string { @@ -448,103 +441,10 @@ function StatusFilterSelect({ ) } -/** Dropdown for filtering history entries by Signer Address. */ -function SignerFilterSelect({ - value, - signers, - onValueChange, -}: { - value: SignerAddressFilter - signers: { address: string; label?: string }[] - onValueChange: (value: SignerAddressFilter) => void -}) { - const [open, setOpen] = useState(false) - - // Only render when there are known signers to filter by - if (signers.length === 0) return null - - const options = [ - { value: BUYER_FILTER_ALL, label: 'All signers' }, - ...signers.map((b) => ({ - value: b.address, - label: b.label ?? `${b.address.slice(0, 6)}…${b.address.slice(-4)}`, - })), - ] - - const selected = options.find((o) => o.value === value) ?? options[0] - - return ( - - setOpen((current) => !current)} - > - - Signer: {selected?.label ?? 'All signers'} - - - - - {open ? ( - - {options.map((option) => ( - { - onValueChange(option.value) - setOpen(false) - }} - > - - {option.label} - - - ))} - - ) : null} - - ) -} - -export function HistoryTab({ state, actions, knownSigners = [] }: HistoryTabProps) { +export function HistoryTab({ state, actions }: HistoryTabProps) { const { selectedSources, statusFilter, - signerAddressFilter, fromDate, toDate, entries, @@ -605,11 +505,6 @@ export function HistoryTab({ state, actions, knownSigners = [] }: HistoryTabProp value={statusFilter} onValueChange={actions.setStatusFilter} /> - diff --git a/packages/ai-credits-widget/src/components/index.ts b/packages/ai-credits-widget/src/components/index.ts index f39bafcb..b80ad176 100644 --- a/packages/ai-credits-widget/src/components/index.ts +++ b/packages/ai-credits-widget/src/components/index.ts @@ -1,16 +1,12 @@ export * from './theme/cards' export { AiCreditsHero } from './buy/AiCreditsHero' -export { GenerateSignerKeyPanel } from './buy/GenerateSignerKeyPanel' -export { OperatorConsentStep } from './buy/OperatorConsentStep' export { AmountPicker } from './buy/AmountPicker' export { CreditsManagementCard } from './manage/CreditsManagementCard' -export { SignerOperatorCard } from './manage/SignerOperatorCard' export { HistoryTab } from './history/HistoryTab' -export { SetupGuidanceCard } from './setup/SetupGuidanceCard' -export { HowToUseView } from './setup/HowToUseView' -export { SetupFaqView } from './setup/SetupFaqView' -export { SetupOnboardingFlow } from './setup/SetupOnboardingFlow' -export { SignerKeyPanel } from './setup/SignerKeyPanel' -export { AntseedSetupPanel } from './setup/AntseedSetupPanel' -export { AntseedSignerRow } from './setup/AntseedSignerRow' +export { GuidanceCard } from './guide/GuidanceCard' +export { HowToUseView } from './guide/HowToUseView' +export { FaqView } from './guide/FaqView' +export { ApiKeyPanel } from './apiKey/ApiKeyPanel' +export { ApiKeyCard } from './apiKey/ApiKeyCard' +export { ApiKeyReadySheet } from './apiKey/ApiKeyReadySheet' export { AiCreditsPurchaseFlow } from './flow/AiCreditsPurchaseFlow' diff --git a/packages/ai-credits-widget/src/components/manage/CreditsManagementCard.tsx b/packages/ai-credits-widget/src/components/manage/CreditsManagementCard.tsx index a28adecc..9574301d 100644 --- a/packages/ai-credits-widget/src/components/manage/CreditsManagementCard.tsx +++ b/packages/ai-credits-widget/src/components/manage/CreditsManagementCard.tsx @@ -1,12 +1,9 @@ import React, { useMemo, useState } from 'react' import { - Button, - ButtonText, Card, Coins, Gift, Heading, - Input, Repeat, Spinner, Text, @@ -15,10 +12,7 @@ import { XStack, YStack, } from '@goodwidget/ui' -import type { - AiCreditsWidgetAdapterActions, - AiCreditsWidgetAdapterState, -} from '../../widgetRuntimeContract' +import type { AiCreditsWidgetAdapterState } from '../../widgetRuntimeContract' import { quoteTotalUsdMicro } from '../../quoteMath' import { formatExactGAmount, @@ -27,17 +21,11 @@ import { formatUsdMicroValue, isGValueCompacted, } from '../../format' -import { - BUYER_KEY_REQUIRED_CLOSE_TOOLTIP, - BUYER_KEY_REQUIRED_WITHDRAW_TOOLTIP, - WITHDRAW_TOOLTIP, -} from '../shared/constants' -import { HoverTooltip, InfoTooltip } from '../shared/tooltips' -import { compactButtonProps } from '../shared/styles' interface CreditsManagementCardProps { state: AiCreditsWidgetAdapterState - actions: Pick + /** This month's gateway spend in micro-USD, or null while unknown or when key management is unavailable. */ + usedThisMonthUsdMicro: string | null } /** Lucide glyph a stat cell shows in the chip above its label. */ @@ -254,20 +242,15 @@ function CreditBalanceCard({ ) } -export function CreditsManagementCard({ state, actions }: CreditsManagementCardProps) { - const [isClosing, setIsClosing] = useState(false) - const [isWithdrawing, setIsWithdrawing] = useState(false) - const [channelId, setChannelId] = useState('') - const [withdrawAmount, setWithdrawAmount] = useState('') +/** AI Credits card: live balance stats plus this month's gateway usage. */ +export function CreditsManagementCard({ state, usedThisMonthUsdMicro }: CreditsManagementCardProps) { const { totalCreditUsd, totalGdDepositedG, monthlyStreamG, gdUsdPerToken, isGoodIdVerified, - withdrawableUsd, totalBonusUsd, - signerPrvKey, } = state const monthlyStreamUsdDisplay = useMemo(() => { @@ -295,21 +278,14 @@ export function CreditsManagementCard({ state, actions }: CreditsManagementCardP ? formatUsdAmount('0') : null - const withdrawableDisplay = withdrawableUsd !== null ? formatUsdAmount(withdrawableUsd) : null + const usedThisMonthDisplay = + usedThisMonthUsdMicro !== null ? formatUsdAmount(usedThisMonthUsdMicro) : null const totalBonusDisplay = totalBonusUsd !== null ? formatUsdAmount(totalBonusUsd) : null - const hasWithdrawableBalance = withdrawableUsd !== null && BigInt(withdrawableUsd) > 0n - const canClose = Boolean(signerPrvKey) && Boolean(channelId.trim()) && !isClosing - const canWithdraw = - Boolean(signerPrvKey) && - hasWithdrawableBalance && - Boolean(withdrawAmount.trim()) && - !isWithdrawing return ( AI Credits - {/* The stat grid keeps its own tighter rhythm than the form sections below. */} @@ -330,92 +306,15 @@ export function CreditsManagementCard({ state, actions }: CreditsManagementCardP )} - - {withdrawableDisplay !== null ? ( - + + {usedThisMonthDisplay !== null ? ( + ) : ( - + — )} - - - - - Withdraw - - - - - - - - - - - - - - - - Close Channel - - - - - - - - - - ) } diff --git a/packages/ai-credits-widget/src/components/manage/RevokeConsentStep.tsx b/packages/ai-credits-widget/src/components/manage/RevokeConsentStep.tsx deleted file mode 100644 index c595e5cb..00000000 --- a/packages/ai-credits-widget/src/components/manage/RevokeConsentStep.tsx +++ /dev/null @@ -1,104 +0,0 @@ -import React from 'react' -import { - Button, - ButtonText, - Icon, - PermissionList, - PermissionRow, - Spinner, - Text, - XStack, - YStack, - Heading, -} from '@goodwidget/ui' -import { truncateAddress, compactButtonProps, monospaceSingleLineStyle } from '../shared/styles' - -interface RevokeConsentStepProps { - signerPubKey: string | null - operatorConsentPending?: boolean - /** Surfaced only after a confirm attempt, so a stale widget error stays out of this sheet. */ - error?: string | null - onConfirm: () => void - onCancel: () => void -} - -/** - * Drawer body for withdrawing the operator authorization — the counterpart to - * OperatorConsentStep, and deliberately shaped like it so the grant and the - * withdrawal read as two sides of the same permission. - */ -export function RevokeConsentStep({ - signerPubKey, - operatorConsentPending = false, - error = null, - onConfirm, - onCancel, -}: RevokeConsentStepProps) { - return ( - - Unauthorize Credit Management? - - This removes the operator's ability to act on your behalf. It is an on-chain change, - not a payment. - - - - - the operator from fulfilling purchases you initiate. - - - - - Your credits and your signer key stay where they are. You can authorize the wallet again at - any time. - - - {signerPubKey && ( - - Signer Address:{' '} - - {truncateAddress(signerPubKey)} - - - )} - - {error && ( - - - - {error} - - - )} - - - - - - - ) -} diff --git a/packages/ai-credits-widget/src/components/manage/SignerOperatorCard.tsx b/packages/ai-credits-widget/src/components/manage/SignerOperatorCard.tsx deleted file mode 100644 index 75ee7719..00000000 --- a/packages/ai-credits-widget/src/components/manage/SignerOperatorCard.tsx +++ /dev/null @@ -1,380 +0,0 @@ -import React, { useEffect, useState } from 'react' -import { - Button, - ButtonText, - Card, - Heading, - Icon, - Spinner, - Text, - XStack, - YStack, - Drawer, - ScrollArea, -} from '@goodwidget/ui' -import type { - AiCreditsWidgetAdapterActions, - AiCreditsWidgetAdapterState, -} from '../../widgetRuntimeContract' -import { SignerKeyPanel } from '../setup/SignerKeyPanel' -import { RevokeConsentStep } from './RevokeConsentStep' -import { monospaceSingleLineStyle, compactButtonProps, truncateAddress } from '../shared/styles' -import { useCopyFeedback } from '../shared/useCopyFeedback' - -interface SignerOperatorCardProps { - state: AiCreditsWidgetAdapterState - actions: AiCreditsWidgetAdapterActions -} - -function shortAddress(address: string): string { - return `${address.slice(0, 6)}…${address.slice(-4)}` -} - -/** Chevron + label row used for the switch-signer and private-key disclosures. */ -function DisclosureToggle({ - open, - label, - onPress, -}: { - open: boolean - label: string - onPress: () => void -}) { - return ( - - ) -} - -/** Monospace value with a copy affordance — used for the signer and its private key. */ -function CopyableValue({ value, display }: { value: string; display?: string }) { - const { copied, copy } = useCopyFeedback() - - return ( - - - {display ?? value} - - - - ) -} - -function SignerStatus({ consented, size = '$1' }: { consented: boolean; size?: '$1' | '$2' }) { - return ( - - - - {consented ? 'Authorized' : 'Not authorized'} - - - ) -} - -function SignerSelector({ - signers, - activeSignerAddress, - onSelect, -}: { - signers: string[] - activeSignerAddress: string | null - onSelect: (address: string) => void -}) { - return ( - - {signers.map((signer) => { - const isActive = signer.toLowerCase() === activeSignerAddress?.toLowerCase() - return ( - { - if (!isActive) void onSelect(signer) - }} - > - - {shortAddress(signer)} - - {isActive ? ( - - - active - - - - ) : null} - - ) - })} - - ) -} - -/** - * Signer Key card for the Manage tab. - * - * Collapsed by default: the header carries the active signer and its authorization state, - * which is all this card needs to report at rest. Everything else — switching signers, - * generating or importing a key, and the private key itself — sits behind a disclosure so - * Manage stays focused on credits. Generate/Import reuse the Set up tab's SignerKeyPanel - * so there is a single implementation of that flow. - */ -export function SignerOperatorCard({ state, actions }: SignerOperatorCardProps) { - const { - signerPubKey, - signerPrvKey, - operatorSignature, - operatorConsented, - operatorConsentPending, - signers, - } = state - - const [isExpanded, setIsExpanded] = useState(false) - const [showSwitcher, setShowSwitcher] = useState(false) - const [showReplacePanel, setShowReplacePanel] = useState(false) - const [showPrivateKey, setShowPrivateKey] = useState(false) - // Remounts SignerKeyPanel so it returns to its Generate / Import choice after a - // signer settles, instead of staying parked in the sub-flow that created it. - const [panelInstance, setPanelInstance] = useState(0) - const [showRevokeDrawer, setShowRevokeDrawer] = useState(false) - // Keeps a pre-existing widget error out of the sheet until this flow produces one. - const [revokeAttempted, setRevokeAttempted] = useState(false) - - const signerCanSign = Boolean(signerPrvKey || operatorSignature) - // Revoking is signed locally by the signer key, so a deep-link signer that only carries - // an operator signature cannot revoke even though it can consent. - const signerCanRevoke = Boolean(signerPrvKey) - - // revokeOperatorConsent reports failure through state.error rather than by rejecting, - // so the sheet closes on consent actually dropping — not on the promise settling. - useEffect(() => { - if (!operatorConsented) setShowRevokeDrawer(false) - }, [operatorConsented]) - - const handleConfirmRevoke = () => { - setRevokeAttempted(true) - void Promise.resolve(actions.revokeOperatorConsent()) - } - - return ( - - setIsExpanded((prev) => !prev)} - > - - Signer Key - {signerPubKey ? ( - - {/* Separators carry their own spacing: adjacent Text renders inline, so - the flex gap between two of them collapses. */} - - {`${truncateAddress(signerPubKey)} · `} - - - - ) : ( - - No signer key yet - - )} - - - - - {isExpanded && ( - - {signerPubKey && ( - - - Active Signer Address - - - - - {!operatorConsented && ( - - )} - {operatorConsented && signerCanRevoke && ( - - )} - - - )} - - {signers.length > 1 && ( - - setShowSwitcher((prev) => !prev)} - /> - {showSwitcher && ( - - )} - - )} - - {signerPrvKey && ( - - - - Signer Private Key - - - - - - Treat this like a password — anyone who has it can spend your credits. - - - )} - - - {signerPubKey ? ( - setShowReplacePanel((prev) => !prev)} - /> - ) : null} - {(showReplacePanel || !signerPubKey) && ( - setPanelInstance((prev) => prev + 1)} - /> - )} - - - - )} - - setShowRevokeDrawer(false)}> - - - setShowRevokeDrawer(false)} - /> - - - - - ) -} diff --git a/packages/ai-credits-widget/src/components/setup/AntseedSetupPanel.tsx b/packages/ai-credits-widget/src/components/setup/AntseedSetupPanel.tsx deleted file mode 100644 index 709fe262..00000000 --- a/packages/ai-credits-widget/src/components/setup/AntseedSetupPanel.tsx +++ /dev/null @@ -1,146 +0,0 @@ -import React, { useState } from 'react' -import { - Anchor, - Button, - ButtonText, - Heading, - Icon, - Text, - XStack, - YStack, - copyTextToClipboard, -} from '@goodwidget/ui' -import { compactButtonProps } from '../shared/styles' - -const ANTSEED_DOWNLOAD_URL = 'https://ubi.gd/3UzJBr9' -const ANTSEED_API_DOCS_URL = 'https://antseed.com/docs/guides/using-the-api' - -const snippetLineStyle: React.CSSProperties = { - fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace', - fontSize: 13, - lineHeight: '20px', - wordBreak: 'break-word', - overflowWrap: 'anywhere', -} - -/** Placeholder, not the real key: the signer key may not exist at this step. */ -const SETUP_SNIPPET = [ - 'npm install -g @antseed/cli', - '', - 'export ANTSEED_IDENTITY_HEX=', - '', - 'antseed signer start', - 'antseed network browse', - 'antseed signer connection set --peer ', -].join('\n') - -interface AntseedSetupPanelProps { - /** - * Advances to the signer key step and marks this one done. - * - * Driven by an explicit press, never by opening the download or copying the - * snippet: neither proves anything — we cannot see an install, and a copy is - * not a setup — and completing a step behind the user's back is how the - * stepper ends up claiming work nobody did. - */ - onProceed: () => void - /** Opens with the API section already expanded, for arrivals from the signer key guide. */ - expandApiSetup?: boolean -} - -/** - * First setup step: getting Antseed. - * - * One screen. The desktop download is the primary path and the API route is a - * secondary disclosure on the same screen rather than a separate view — this - * step covers getting Antseed and nothing else, so signer key guidance lives in - * the signer key step where it belongs. - */ -export function AntseedSetupPanel({ onProceed, expandApiSetup = false }: AntseedSetupPanelProps) { - const [apiExpanded, setApiExpanded] = useState(expandApiSetup) - const [copied, setCopied] = useState(false) - - const handleDownload = () => { - if (typeof window !== 'undefined') { - window.open(ANTSEED_DOWNLOAD_URL, '_blank', 'noopener,noreferrer') - } - } - - const handleCopy = async () => { - const didCopy = await copyTextToClipboard(SETUP_SNIPPET.replace(/\n\n+/g, '\n').trim()) - if (!didCopy) return - setCopied(true) - setTimeout(() => setCopied(false), 2000) - } - - return ( - - Get Antseed - - Download the free Antseed Desktop app to use your AI credits. - - - - - {/* Secondary route, collapsed by default: the desktop app is the primary - experience and this only concerns advanced users. */} - - setApiExpanded((open) => !open)} - > - - Advanced user? Use API Setup to use your AI credits through your terminal. - - - API Setup - - - - - {apiExpanded && ( - - - - - - {SETUP_SNIPPET.split('\n').map((line, index) => ( - - {line.length > 0 ? line : ' '} - - ))} - - - Your signer key goes in{' '} - - ANTSEED_IDENTITY_HEX - {' '} - — generate or import it in the next step, then copy it from there. See the{' '} - - AntSeed API guide - - . - - - )} - - - - - ) -} diff --git a/packages/ai-credits-widget/src/components/setup/AntseedSignerRow.tsx b/packages/ai-credits-widget/src/components/setup/AntseedSignerRow.tsx deleted file mode 100644 index e00f290c..00000000 --- a/packages/ai-credits-widget/src/components/setup/AntseedSignerRow.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import React from 'react' -import { Text, YStack } from '@goodwidget/ui' -import antseedSignerRow from '../../assets/antseed-signer-row.png' - -type SignerRowMode = 'generate' | 'import' - -interface AntseedSignerRowProps { - /** - * Which arrow the caption points at. Both glyphs sit on the same Antseed row - * and do opposite things, so naming the wrong one is how someone overwrites a - * key they never backed up. - */ - mode: SignerRowMode - /** Hidden when surrounding copy already gives the instructions. */ - showCaption?: boolean -} - -/** - * Screenshot of Antseed's Profile → Signer row, captioned per flow. - * - * The image shows both arrow buttons because that is what the user will - * actually see; the caption below names the one to press. Deliberately one - * action per flow — an earlier version also told the user to back up first, - * which duplicated the warning rendered just above this in SignerKeyPanel and - * left two different keys to keep straight in a single sentence. Backing up - * belongs to that warning; this line only answers "which arrow". - */ -export function AntseedSignerRow({ mode, showCaption = true }: AntseedSignerRowProps) { - const isGenerate = mode === 'generate' - - return ( - - The Signer row in Antseed's Profile, showing a download arrow to export the current key and an upload arrow to import a new one - - {showCaption ? ( - - {isGenerate ? ( - <> - Copy the key above, then tap ↑ in Antseed's{' '} - - Profile → Signer - {' '} - and paste it there. - - ) : ( - <> - In Antseed's{' '} - - Profile → Signer - - , tap ↓ to export your key, then paste it below. - - )} - - ) : null} - - ) -} diff --git a/packages/ai-credits-widget/src/components/setup/HowToUseView.tsx b/packages/ai-credits-widget/src/components/setup/HowToUseView.tsx deleted file mode 100644 index 61bcf702..00000000 --- a/packages/ai-credits-widget/src/components/setup/HowToUseView.tsx +++ /dev/null @@ -1,288 +0,0 @@ -import React, { useState } from 'react' -import { - Anchor, - Badge, - BadgeText, - Button, - ButtonText, - Card, - Icon, - Text, - XStack, - YStack, -} from '@goodwidget/ui' - -/** YouTube id for the getting-started walkthrough. */ -const VIDEO_ID = 'Anb2GkLqs24' - -/** Fallback for anyone whose browser or host page will not frame the player. */ -const VIDEO_URL = `https://youtu.be/${VIDEO_ID}` - -/** Poster frame. YouTube serves this for every video, so it needs no asset of ours. */ -const VIDEO_POSTER_URL = `https://i.ytimg.com/vi/${VIDEO_ID}/hqdefault.jpg` - -// Nothing loads from YouTube until the play button is pressed: no third-party -// frame, cookies, or requests for the majority of visitors who never watch. -const VIDEO_EMBED_URL = `https://www.youtube-nocookie.com/embed/${VIDEO_ID}?autoplay=1&rel=0` - -/** Notion written guide URL. */ -const WRITTEN_GUIDE_URL = - 'https://app.notion.com/p/gooddollar/Full-Setup-Walkthrough-Widget-AntSeed-VPR-3c0f258232f08184bee9cd440cc93059' - -/** Summary step with an associated widget tab label. */ -interface SummaryStep { - index: number - title: string - tabLabel: string - description: string -} - -const QUICK_SUMMARY_STEPS: SummaryStep[] = [ - { - index: 1, - title: 'Get G$ and connect your wallet', - tabLabel: 'Set Up', - description: - 'Any wallet holding G$ works. If your wallet is GoodDollar-verified, the bonus is applied automatically.', - }, - { - index: 2, - title: 'Complete one-time setup', - tabLabel: 'Set Up', - description: - 'Set up your Signer Key and complete the required authorization. Set up how you’ll use your credits with Antseed Desktop or API Setup for advanced users.', - }, - { - index: 3, - title: 'Buy or stream credits', - tabLabel: 'Buy Credits', - description: - 'Deposit once (+10% if verified) or subscribe continuously (+20% if verified), then confirm.', - }, - { - index: 4, - title: 'Manage and track', - tabLabel: 'Manage History', - description: - 'Check your Signer Key and balance under Manage, and view or export your credit history under History.', - }, -] - -interface HowToUseViewProps { - /** Callback to return to the normal buy view. */ - onBack: () => void -} - -/** - * In-widget "How to use" guide rendered inside the Setup tab content area. - * Provides a video card, a link to the full written guide, and a quick summary - * of the four-step end-to-end flow. - */ -export function HowToUseView({ onBack }: HowToUseViewProps) { - return ( - - {/* Back navigation */} - - - - New here? Start with the 3-minute video — it covers the whole journey, start to finish. - - - {/* Video card */} - - - {/* Written guide card */} - - - - - - - - - Full written guide{' '} - - - - See the complete step-by-step walkthrough with screenshots. - - - - - - - - - - {/* Quick summary section */} - - - QUICK SUMMARY - - - - {QUICK_SUMMARY_STEPS.map((step) => ( - - {/* Step number circle */} - - - {step.index} - - - - {/* Step content */} - - - - {step.title} - - - {step.tabLabel} - - - - {step.description} - - - - ))} - - - {/* Security note */} - - Your G$ wallet is never exposed — only the scoped signer key. - - - - ) -} - -/** - * Click-to-play walkthrough card. - * - * The card used to be an Anchor around a play button that only ever opened a new - * tab, which sends someone mid-setup away from the widget. It now plays in place, - * and only reaches for YouTube once the play button is pressed — before that it - * is a poster image, so the common case of never watching costs no third-party - * frame, cookies, or requests. - */ -function VideoCard() { - const [playing, setPlaying] = useState(false) - - if (playing) { - return ( - - {/* 16:9 via padding-top, so the frame keeps its ratio at any card width. */} - -