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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 9 additions & 75 deletions apps/ai-credits-web/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'
import React, { useEffect, useState } from 'react'
import {
AiCreditsWidget,
createBackendClient,
DEFAULT_DISCOUNT_CONFIG,
type DiscountConfig,
} from '@goodwidget/ai-credits-widget'
import type { EIP1193Provider } from '@goodwidget/core'
import {
DefaultAppKitProvider,
DEFAULT_APPKIT_NETWORKS,
useAppKit,
useAppKitAccount,
useAppKitNetwork,
useAppKitProvider,
useAppKitSession,
useDisconnect,
} from '@goodwidget/embed/appkit-provider'
import {
Expand All @@ -36,9 +31,6 @@ import {
} from '@goodwidget/ui'
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/'

Expand Down Expand Up @@ -70,79 +62,21 @@ function useDiscountConfig(backendUrl: string | undefined): DiscountConfig {
}

function ReownAiCreditsWidget() {
const { open } = useAppKit()
const session = useAppKitSession()
const { disconnect } = useDisconnect()
const { address: appKitAddress, status: accountStatus } = useAppKitAccount()
const { walletProvider } = useAppKitProvider<EIP1193Provider | undefined>('eip155')
const { chainId, switchNetwork, approvedCaipNetworkIds } = useAppKitNetwork()
const appKitAddressRef = useRef(appKitAddress)
appKitAddressRef.current = appKitAddress

// AppKit reports no address both while restoring a prior session and once it
// has settled on "no wallet". Only the second is a real override, so during
// the unresolved window these stay undefined and the core provider's own
// EIP-1193 tracking covers the gap.
//
// A restored 'connected' also needs its provider before it counts. AppKit
// rehydrates the last account from storage without checking the wallet behind
// it, so that address alone can describe a locked wallet — and the widget can
// only catch that by asking the provider for its accounts. Handing down an
// address with no provider to verify it against is the one combination that
// renders as a healthy session nothing can disprove.
const isAccountResolved =
(accountStatus === 'connected' && Boolean(walletProvider)) || accountStatus === 'disconnected'

// switchNetwork takes a network descriptor, not a chain id.
const appKitNetworksByChainId = useMemo(
() => new Map(DEFAULT_APPKIT_NETWORKS.map((network) => [Number(network.id), network])),
[],
)

// CAIP ids look like "eip155:42220"; undefined means AppKit has not reported
// yet, which is "no restriction known" rather than "nothing available".
const availableChainIds = useMemo(
() =>
approvedCaipNetworkIds
? approvedCaipNetworkIds
.map((caipId) => Number(caipId.split(':')[1]))
.filter((id) => Number.isFinite(id))
: null,
[approvedCaipNetworkIds],
)

return (
<AiCreditsWidget
provider={walletProvider}
connectOverride={async () => {
await open({ view: 'Connect' })

if (!appKitAddressRef.current) {
throw new Error('wallet_connect_cancelled')
}
}}
provider={session.provider}
connectOverride={session.connectOverride}
showWalletControls
disconnectOverride={async () => {
await disconnect()
}}
addressOverride={isAccountResolved ? (appKitAddress ?? null) : undefined}
chainIdOverride={isAccountResolved ? (chainId == null ? null : Number(chainId)) : undefined}
availableChainIdsOverride={availableChainIds}
switchChainOverride={async (targetChainId) => {
const targetNetwork = appKitNetworksByChainId.get(targetChainId)
// The modal only lets the user attempt the switch — it never confirms
// one happened — so this throws rather than resolves. Resolving would
// report success for a network the wallet may still not be on.
if (!targetNetwork) {
await open({ view: 'Networks' })
throw new Error(SWITCH_CHAIN_MANUAL_SELECTION_ERROR)
}
try {
await switchNetwork(targetNetwork)
} catch {
await open({ view: 'Networks' })
throw new Error(SWITCH_CHAIN_MANUAL_SELECTION_ERROR)
}
}}
addressOverride={session.addressOverride}
chainIdOverride={session.chainIdOverride}
availableChainIdsOverride={session.availableChainIdsOverride}
switchChainOverride={session.switchChainOverride}
backendUrl={import.meta.env.VITE_AI_CREDITS_BACKEND_URL}
baseRpcUrl={import.meta.env.VITE_AI_CREDITS_BASE_RPC_URL}
celoRpcUrl={import.meta.env.VITE_AI_CREDITS_CELO_RPC_URL}
Expand Down
82 changes: 4 additions & 78 deletions apps/superfluid-campaign-web/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import React, { useMemo, useRef } from 'react'
import React from 'react'
import { SuperfluidCampaignWidget } from '@goodwidget/superfluid-campaign-widget'
import type { EIP1193Provider } from '@goodwidget/core'
import type { CampaignActionLinkOverrides } from '@goodwidget/superfluid-campaign-widget'
import {
DEFAULT_APPKIT_NETWORKS,
DefaultAppKitProvider,
useAppKit,
useAppKitAccount,
useAppKitNetwork,
useAppKitProvider,
useAppKitSession,
} from '@goodwidget/embed/appkit-provider'
import { TamaguiProvider } from '@tamagui/core'
import { YStack, defaultConfig } from '@goodwidget/ui'
Expand Down Expand Up @@ -38,85 +33,16 @@ const STANDALONE_CLAIM_REWARDS_URL = 'https://ubi.gd/4iN7RhK'
*/
const APPKIT_DISCONNECT_LABEL = 'Network settings'

const SWITCH_CHAIN_MANUAL_SELECTION_ERROR = 'Select the network in the wallet dialog, then try again.'

function AppKitSuperfluidCampaignWidget() {
const { open } = useAppKit()
const { address, status: accountStatus } = useAppKitAccount()
const { walletProvider } = useAppKitProvider<EIP1193Provider | undefined>('eip155')
const { chainId, switchNetwork, approvedCaipNetworkIds } = useAppKitNetwork()
const addressRef = useRef(address)
addressRef.current = address

// AppKit reports `address: undefined` both while it's still restoring a prior
// session ('connecting'/'reconnecting'/not yet reported) and once it has
// definitively resolved to "no wallet". Only the latter is a real override —
// during the unresolved window this stays `undefined` so the core provider's
// own EIP-1193 fallback tracking (rather than a premature "disconnected"
// override) covers the gap until AppKit reports a final status. `chainId`
// below is gated on the same flag so it doesn't fall back to a stale
// previously-tracked chain once the account is known to be disconnected.
const isAccountResolved = accountStatus === 'connected' || accountStatus === 'disconnected'

// AppKit's switchNetwork takes the network descriptor object, not a chain id,
// so this looks up the descriptor for whichever chain the widget wants to
// switch to. AppKit's own active-network state (chainId here) is always the
// source of truth for what's "current" — the widget never tracks it separately.
const appKitNetworksByChainId = useMemo(
() => new Map(DEFAULT_APPKIT_NETWORKS.map((network) => [Number(network.id), network])),
[],
)

// CAIP network ids are formatted like "eip155:122" — the widget's execute
// gating needs plain numeric chain ids. `undefined` (AppKit hasn't reported
// approved networks yet) is kept as `null`, meaning "no restriction known"
// rather than "nothing is available".
const availableChainIds = useMemo(
() =>
approvedCaipNetworkIds
? approvedCaipNetworkIds
.map((caipId) => Number(caipId.split(':')[1]))
.filter((id) => Number.isFinite(id))
: null,
[approvedCaipNetworkIds],
)
const { open, ...walletSession } = useAppKitSession({ requireProviderForConnected: false })

return (
<SuperfluidCampaignWidget
provider={walletProvider}
{...walletSession}
defaultTheme="dark"
contentMaxWidth={DESKTOP_WIDGET_MAX_WIDTH}
addressOverride={isAccountResolved ? (address ?? null) : undefined}
chainIdOverride={isAccountResolved ? (chainId == null ? null : Number(chainId)) : undefined}
availableChainIdsOverride={availableChainIds}
switchChainOverride={async (targetChainId) => {
const targetNetwork = appKitNetworksByChainId.get(targetChainId)
// Falling through to AppKit's own network-selection modal is the
// documented recovery path when a target chain has no direct
// programmatic descriptor here, or when switchNetwork itself fails
// (e.g. the connected wallet rejects the automatic switch request).
// The modal only lets the user attempt the switch themselves — it
// never confirms synchronously that one actually happened — so this
// throws rather than resolves, otherwise the caller (core's
// switchChain, and the claim widget's error handling built on top of
// it) would treat an opened modal as an already-finished switch.
if (!targetNetwork) {
await open({ view: 'Networks' })
throw new Error(SWITCH_CHAIN_MANUAL_SELECTION_ERROR)
}
try {
await switchNetwork(targetNetwork)
} catch {
await open({ view: 'Networks' })
throw new Error(SWITCH_CHAIN_MANUAL_SELECTION_ERROR)
}
}}
disconnectLabel={APPKIT_DISCONNECT_LABEL}
disconnectIcon="settings"
connectOverride={async () => {
await open({ view: 'Connect' })
if (!addressRef.current) throw new Error('wallet_connect_cancelled')
}}
disconnectOverride={async () => {
await open({ view: 'Account' })
}}
Expand Down
1 change: 1 addition & 0 deletions examples/storybook/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"@goodwidget/claim-widget-theme-demo": "workspace:*",
"@goodwidget/citizen-claim-widget": "workspace:*",
"@goodwidget/connect-a-wallet-widget": "workspace:*",
"@goodwidget/ecosystem-widget": "workspace:^",
"@goodwidget/goodreserve-widget": "workspace:*",
"@goodwidget/governance-widget": "workspace:*",
"@goodwidget/streaming-widget": "workspace:*",
Expand Down
15 changes: 15 additions & 0 deletions examples/storybook/src/stories/design-system/EcosystemIcons.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React from 'react'
import { Coins, HandCoins, MoreHorizontal, Sparkles, Waves } from '@goodwidget/ui'

const icons = {
Claim: HandCoins,
Reserve: Coins,
Streaming: Waves,
'AI Credits': Sparkles,
More: MoreHorizontal,
}

export function EcosystemIcon({ name, muted = false }: { name: keyof typeof icons; muted?: boolean }) {
const Glyph = icons[name]
return <Glyph size={24} color={muted ? '$placeholderColor' : '$color'} />
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import React, { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react'
import { expect, within } from '@storybook/test'
import { GoodWidgetProvider } from '@goodwidget/core'
import {
BottomAppBar, BottomBarItem, EcosystemHeader, Text,
WidgetDrawer, WidgetListRow, WidgetUnavailable, YStack,
} from '@goodwidget/ui'
import { EcosystemIcon } from './EcosystemIcons'

type PreviewArgs = { theme: 'light' | 'dark' }

const meta: Meta<PreviewArgs> = {
title: 'Design System/Primitives/Ecosystem Shell Preview',
tags: ['autodocs', 'showcase', 'ecosystem-shell'],
parameters: { layout: 'fullscreen' },
args: { theme: 'light' },
argTypes: { theme: { control: 'radio', options: ['light', 'dark'] } },
}
export default meta
type Story = StoryObj<PreviewArgs>

const widgets = [
{ label: 'Claim', description: 'Claim your daily G$ UBI' },
{ label: 'Reserve', description: 'Swap through the GoodReserve' },
{ label: 'Streaming', description: 'Streams, pools and balances' },
{ label: 'AI Credits', description: 'Buy AI coding credits with G$' },
] as const

function Preview({ theme }: PreviewArgs) {
const [connected, setConnected] = useState(false)
const [selected, setSelected] = useState('Claim')
const [drawerOpen, setDrawerOpen] = useState(false)
const [supported, setSupported] = useState(false)
const [switching, setSwitching] = useState(false)
const [presses, setPresses] = useState(0)

return (
<GoodWidgetProvider key={theme} defaultTheme={theme}>
<YStack width="100%" minHeight={700} backgroundColor="$background" data-testid="shell-preview">
<EcosystemHeader
address={connected ? '0x1234567890123456789012345678901234567890' : null}
chainId={supported ? 42220 : 1}
onConnect={() => setConnected(true)}
onWalletAction={() => setConnected(false)}
walletActionLabel="Disconnect preview wallet"
/>
<YStack flex={1} width="100%" padding="$4" gap="$4">
<Text>Component preview only — no wallet or widget is connected.</Text>
{connected && selected === 'Reserve' && !supported ? (
<WidgetUnavailable
widgetName="GoodReserve"
networkName="Ethereum"
onSwitchNetwork={() => setSupported(true)}
/>
) : connected ? (
<Text>{selected} widget placeholder</Text>
) : (
<Text>Connect the preview wallet to continue.</Text>
)}
</YStack>
<BottomAppBar>
{widgets.slice(0, 3).map(({ label }) => (
<BottomBarItem
key={label}
label={label}
icon={<EcosystemIcon name={label} muted={selected !== label} />}
active={selected === label}
onPress={() => setSelected(label)}
/>
))}
<BottomBarItem label="More" icon={<EcosystemIcon name="More" muted />} onPress={() => setDrawerOpen(true)} />
</BottomAppBar>
<WidgetDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)}>
{widgets.map(({ label, description }) => (
<WidgetListRow
key={label}
label={label}
description={description}
icon={<EcosystemIcon name={label} />}
active={selected === label}
onPress={() => { setSelected(label); setDrawerOpen(false) }}
/>
))}
</WidgetDrawer>
</YStack>
<YStack width="100%" padding="$4" gap="$4" backgroundColor="$background">
<Text>Building blocks and states</Text>
<Text>EcosystemHeader provides the wallet and network controls. BottomAppBar contains BottomBarItem navigation; More opens a WidgetDrawer of WidgetListRow items. WidgetUnavailable explains unsupported networks.</Text>

<YStack gap="$2" data-testid="header-states">
<Text>EcosystemHeader: connecting and native wallet</Text>
<EcosystemHeader onConnect={() => {}} connecting />
<EcosystemHeader address="0x1234567890123456789012345678901234567890" chainId={42220} />
</YStack>

<YStack gap="$2" data-testid="navigation-states">
<Text>BottomAppBar and BottomBarItem: active, loading and disabled</Text>
<BottomAppBar>
<BottomBarItem label="Claim" icon={<EcosystemIcon name="Claim" />} active onPress={() => setPresses((count) => count + 1)} />
<BottomBarItem label="Loading" icon={<EcosystemIcon name="Streaming" />} loading onPress={() => setPresses((count) => count + 1)} />
<BottomBarItem label="More" icon={<EcosystemIcon name="More" muted />} disabled onPress={() => setPresses((count) => count + 1)} />
</BottomAppBar>
<Text>Pressed {presses}</Text>
</YStack>

<YStack gap="$2" data-testid="row-states">
<Text>WidgetListRow: disabled</Text>
<WidgetListRow label="Disabled" description="Unavailable" icon={<EcosystemIcon name="Streaming" />} disabled />
</YStack>

<YStack gap="$2" data-testid="unavailable-state">
<Text>WidgetUnavailable: switching</Text>
<WidgetUnavailable widgetName="Citizen Claim" networkName="Ethereum" switching={switching} onSwitchNetwork={() => setSwitching(true)} />
{switching && <Text>Switch requested</Text>}
</YStack>
</YStack>
</GoodWidgetProvider>
)
}

export const BuildingBlocks: Story = {
render: (args) => <Preview {...args} />,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
const header = within(canvas.getByTestId('header-states'))
await expect(header.getByRole('button', { name: 'Connect Wallet' })).toBeDisabled()
await expect(header.getByRole('button', { name: 'Connect Wallet' })).toHaveAttribute('aria-busy', 'true')
await expect(header.queryByRole('button', { name: 'Wallet options' })).not.toBeInTheDocument()
const navigation = within(canvas.getByTestId('navigation-states'))
await expect(navigation.getByRole('button', { name: 'Loading' })).toHaveAttribute('aria-busy', 'true')
await expect(navigation.getByRole('button', { name: 'More' })).toBeDisabled()
await expect(within(canvas.getByTestId('row-states')).getByRole('button', { name: 'Disabled' })).toBeDisabled()
},
}
Loading
Loading