diff --git a/.gitignore b/.gitignore index 4c61f6d..4daceba 100644 --- a/.gitignore +++ b/.gitignore @@ -4,5 +4,3 @@ dist/ *.log .env ./demo/.env -# local pnpm link override (do not commit) -pnpm-workspace.yaml diff --git a/README.md b/README.md index 681b8d9..ee0032a 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ const config = createConfig({ [base.id]: http("https://mainnet.base.org"), [optimism.id]: http("https://mainnet.optimism.io"), [arbitrum.id]: http("https://arb1.arbitrum.io/rpc"), - [polygon.id]: http("https://polygon.lava.build"), + [polygon.id]: http("https://polygon-bor-rpc.publicnode.com"), }, }); @@ -340,7 +340,7 @@ Useful Earn props: `earnDefaultTab` (`'deposit'`|`'withdraw'`), `earnHideTabs`, | `toAmount` (flat pay) | `string` | Human / decimal | `"0.15"` | | `intent.requiredAmount` | `bigint` | Atomic (smallest unit) | `5_000_000n` (5 USDC) | -**Built-in registry.** The widget bundles common stablecoins + WETH across Ethereum, Base, Optimism, Polygon, Arbitrum (and Sepolia testnets). For flat-pay with a registry token you can omit `toTokenSymbol`/`toTokenDecimals`. For anything else, pass them. +**Built-in registry.** The widget bundles common stablecoins, WETH, and native ETH across Ethereum, Base, Optimism, Arbitrum, and supported ETH testnets. Polygon keeps its native asset separate. WETH remains an ERC-20 and can be selected alongside ETH. Native ETH uses the zero-address token sentinel and 18 decimals; balances use the wallet's native balance, and deposits send ETH as transaction value without ERC-20 approval. Keep ETH available for network fees. Pay, Swap, Earn deposits, and Smart Withdraw support ETH when the selected route is available. For flat-pay with a registry token you can omit `toTokenSymbol`/`toTokenDecimals`. For anything else, pass them. You can read the registries yourself: diff --git a/demo/.env b/demo/.env index a1bc921..5e666e7 100644 --- a/demo/.env +++ b/demo/.env @@ -1,9 +1,18 @@ -# VITE_EPOCH_API_BASE_URL=https://testnet-dev.epochprotocol.xyz +VITE_EPOCH_API_BASE_URL=https://mainnet-api.epochprotocol.xyz VITE_TESTNET_API_BASE_URL=https://testnet-dev.epochprotocol.xyz -VITE_TESTNET_API_BASE_URL=http://localhost:3000 -VITE_POSITIONS_API_BASE_URL=http://positions-testnet-dev.epochprotocol.xyz -VITE_TESTNET_POSITIONS_API_BASE_URL=http://localhost:4024 +VITE_POSITIONS_API_BASE_URL=https://positions-mainnet.epochprotocol.xyz +VITE_TESTNET_POSITIONS_API_BASE_URL=https://positions-mainnet.epochprotocol.xyz -# Miden testnet endpoints. -VITE_MIDEN_RPC_URL=https://rpc.testnet.miden.io +# Miden mainnet endpoints. +VITE_MIDEN_RPC_URL=https://rpc.cedar.miden.io VITE_MIDEN_NOTE_TRANSPORT_URL=https://transport.miden.io + + +# VITE_EPOCH_API_BASE_URL=http://localhost:3000 +# VITE_TESTNET_API_BASE_URL=http://localhost:3000 +# VITE_POSITIONS_API_BASE_URL=https://positions-mainnet.epochprotocol.xyz +# VITE_TESTNET_POSITIONS_API_BASE_URL=http://localhost:4024 + +# # Miden mainnet endpoints. +# VITE_MIDEN_RPC_URL=https://rpc.testnet.miden.io +# VITE_MIDEN_NOTE_TRANSPORT_URL=https://transport.miden.io diff --git a/demo/.env.example b/demo/.env.example index b216497..2332105 100644 --- a/demo/.env.example +++ b/demo/.env.example @@ -1,8 +1,27 @@ -# Epoch services for the local demo. +# Local Epoch services. The allocator forwards quotes to local SIO on port 8080, +# which selects the local 1delta adapter. Hosted deployments can use /allocator. VITE_EPOCH_API_BASE_URL=http://localhost:3000 VITE_TESTNET_API_BASE_URL=http://localhost:3000 +VITE_EARN_SOLVER_URL=http://localhost:3011 +VITE_POSITIONS_API_BASE_URL=http://localhost:4023 VITE_TESTNET_POSITIONS_API_BASE_URL=http://localhost:4024 -# Miden testnet endpoints. -VITE_MIDEN_RPC_URL=https://rpc.testnet.miden.io -VITE_MIDEN_NOTE_TRANSPORT_URL=https://transport.miden.io +# Miden mainnet note transport (also the runtime default). +VITE_MIDEN_NOTE_TRANSPORT_URL=https://transport.cedar.miden.io + +# Mainnet defaults come from @epoch-protocol/epoch-flows-sdk. Override only for diagnostics. +# VITE_MIDEN_RPC_URL=https://rpc.cedar.miden.io + +# Base uses https://mainnet.base.org without a key. Optional keyed Ankr override: +# VITE_ANKR_API_KEY= + +# Optional Infura RPC for all configured EVM chains through the Vite proxy. +# Enabled automatically when INFURA_API_KEY is present. Keep the credential +# in ignored .env.local; do not prefix INFURA_API_KEY with VITE_. +# INFURA_API_KEY= +# Miden uses its own RPC; Robinhood is not supported by this Infura proxy. + +# Robinhood uses its own public RPCs, including when Infura is enabled. +# Optional provider overrides: +# VITE_ROBINHOOD_RPC_URL=https://rpc.mainnet.chain.robinhood.com +# VITE_ROBINHOOD_TESTNET_RPC_URL=https://rpc.testnet.chain.robinhood.com diff --git a/demo/.gitignore b/demo/.gitignore index a58d3c1..d5706ae 100644 --- a/demo/.gitignore +++ b/demo/.gitignore @@ -2,4 +2,5 @@ node_modules/ dist/ .DS_Store *.log -.env \ No newline at end of file +.env +.env.local diff --git a/demo/README.md b/demo/README.md index 6c991fc..ecfe51a 100644 --- a/demo/README.md +++ b/demo/README.md @@ -27,20 +27,42 @@ pnpm run typecheck Copy `.env.example` to `.env`, then set the local service URLs as needed. -| Variable | Purpose | -|----------|---------| -| `VITE_EPOCH_API_BASE_URL` | Epoch allocator / API base URL (default `http://0.0.0.0:3000`) | -| `VITE_ALLOCATOR_URL` | Fallback if `VITE_EPOCH_API_BASE_URL` is unset | -| `VITE_MIDEN_RPC_URL` | Miden testnet RPC URL (`https://rpc.testnet.miden.io`) | -| `VITE_MIDEN_NOTE_TRANSPORT_URL` | Miden testnet note transport URL (`https://transport.miden.io`) | -| `VITE_MIDENSCAN_URL` | Optional Miden explorer base (Advanced tab) | +| Variable | Purpose | +| ------------------------------- | ------------------------------------------------------------------ | +| `VITE_EPOCH_API_BASE_URL` | Local allocator: `http://localhost:3000`; forwards to SIO on port 8080 | +| `VITE_EARN_SOLVER_URL` | Local 1delta adapter: `http://localhost:3011` | +| `VITE_POSITIONS_API_BASE_URL` | Local 1delta positions API: `http://localhost:4023` | +| `VITE_TESTNET_API_BASE_URL` | Local testnet allocator: `http://localhost:3000` | +| `VITE_TESTNET_POSITIONS_API_BASE_URL` | Local dummy-lending positions API: `http://localhost:4024` | +| `VITE_MIDEN_RPC_URL` | Optional Miden mainnet RPC override (default Cedar from Flows SDK) | +| `VITE_MIDEN_NOTE_TRANSPORT_URL` | Mainnet note transport (default `https://transport.cedar.miden.io`) | +| `VITE_ANKR_API_KEY` | Optional Ankr Base RPC key; without it, Base uses public `https://mainnet.base.org` | +| `INFURA_API_KEY` | Server-only base64 `key:secret` credential in ignored `.env.local`; enables Infura for all configured EVM chains | +| Miden explorer | Midenscan mainnet from Flows SDK | + +Open `http://localhost:5175/widget/` for the local demo. The service URLs above target local processes; the blockchain RPC and note transport URLs still target Cedar/Base so mainnet asset and position data remain available. Start the local backend services before requesting an Earn quote. Testing a mainnet deposit still requires an explicit wallet transaction. ## Where to copy from -| Path | Use | -|------|-----| -| [`src/pay/scenarios.ts`](src/pay/scenarios.ts) | Example `intent` payloads for Pay | -| [`src/earn/`](src/earn/) | Market list, search filter, APR preview, `buildEarnDepositProps` | -| [`src/app/App.tsx`](src/app/App.tsx) | Wiring `EpochIntentWidget` + `api.baseUrl` + callbacks | +With `INFURA_API_KEY` set, Wagmi, wallet chain metadata, and widget balance reads +share `/widget/rpc/*` endpoints for Ethereum, Base, Optimism, Polygon, Arbitrum, +and the configured Sepolia networks. The Vite dev/preview server adds Infura +authentication; the browser receives only relative paths. Static hosting needs +an equivalent server proxy. Miden keeps its native RPC, and Robinhood requires +its own public RPCs (mainnet `4663`, testnet `46630`) because this Infura +configuration does not support it. Set `VITE_ROBINHOOD_RPC_URL` or +`VITE_ROBINHOOD_TESTNET_RPC_URL` to override them. Both networks are available +in wallet switching and the local signer, and in the widget's chain/token pickers. +Mainnet offers USDG, USDe and WETH; testnet offers the graph's test tokens. + +Miden mainnet includes USDG (6 decimals), faucet +`mm1ar7rgznnerajt52p9ul6rltd8g039qsa`, in the Pay/Swap and Earn token pickers. +The Advanced bridge remains the Base USDC/USDCX example. + +| Path | Use | +| ---------------------------------------------- | ---------------------------------------------------------------- | +| [`src/pay/scenarios.ts`](src/pay/scenarios.ts) | Example `intent` payloads for Pay | +| [`src/earn/`](src/earn/) | Market list, search filter, APR preview, `buildEarnDepositProps` | +| [`src/app/App.tsx`](src/app/App.tsx) | Wiring `EpochIntentWidget` + `api.baseUrl` + callbacks | Earn markets are **static demo data** in [`src/earn/earnMarkets.ts`](src/earn/earnMarkets.ts). Replace with your allocator when you have a real endpoint. diff --git a/demo/package.json b/demo/package.json index 9023c72..55a0f7a 100644 --- a/demo/package.json +++ b/demo/package.json @@ -4,24 +4,25 @@ "version": "0.0.0", "type": "module", "scripts": { - "dev": "vite", - "build": "vite build", + "dev": "pnpm --dir .. build:css && vite", + "build": "pnpm --dir .. build:css && vite build", "typecheck": "tsc --noEmit" }, "dependencies": { - "@epoch-protocol/epoch-commons-sdk": "file:../../epoch-commons-sdk", - "@epoch-protocol/epoch-intents-sdk": "^1.0.38", - "@epoch-protocol/epoch-intent-widget": "file:../", - "@miden-sdk/miden-sdk": "0.16.0", - "@miden-sdk/miden-wallet-adapter-base": "0.16.0", - "@miden-sdk/miden-wallet-adapter-react": "0.16.0", - "@miden-sdk/react": "0.16.0", + "@epoch-protocol/epoch-commons-sdk": "2.1.0", + "@epoch-protocol/epoch-flows-sdk": "file:../../epoch-flows-sdk", + "@epoch-protocol/epoch-intent-widget": "workspace:*", + "@epoch-protocol/epoch-intents-sdk": "2.1.0", + "@miden-sdk/miden-sdk": "0.17.5", + "@miden-sdk/miden-wallet-adapter-base": "0.17.5", + "@miden-sdk/miden-wallet-adapter-react": "0.17.5", + "@miden-sdk/react": "0.17.5", "@rainbow-me/rainbowkit": "^2.2.9", "@tanstack/react-query": "^5.90.10", "react": "^18.3.1", "react-dom": "^18.3.1", "sonner": "^2.0.3", - "viem": "^2.42.1", + "viem": "^2.57.13", "wagmi": "^2.9.0" }, "devDependencies": { diff --git a/demo/src/RuntimeApp.tsx b/demo/src/RuntimeApp.tsx new file mode 100644 index 0000000..4534963 --- /dev/null +++ b/demo/src/RuntimeApp.tsx @@ -0,0 +1,92 @@ +import { useState } from "react"; +import { WagmiProvider, createConfig, http } from "wagmi"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { RainbowKitProvider, getDefaultWallets } from "@rainbow-me/rainbowkit"; +import { Toaster } from "sonner"; +import { getDemoChains, getDemoRpcUrls } from "./config/rpc"; +import { AllowedPrivateData } from "@miden-sdk/miden-wallet-adapter-base"; +import { MidenFiSignerProvider } from "@miden-sdk/miden-wallet-adapter-react"; +import { MidenProvider } from "@miden-sdk/react"; +import { + themeToCssVars, + LIGHT_THEME, +} from "@epoch-protocol/epoch-intent-widget"; +import App from "./app/App"; +import type { DemoNetwork } from "./app/AppShell"; +import { MIDEN_MAINNET } from "./config/miden-mainnet"; +import { MIDEN_TESTNET } from "./config/miden-testnet"; +import { + MIDEN_MAINNET_WALLET_NETWORK, + MIDEN_TESTNET_WALLET_NETWORK, +} from "./miden/lib/mainnet-wallet-compat"; +import { localSigner } from "./wallet/local-signer"; + +// Project the library's `--epoch-*` design tokens onto `:root` so Tailwind +// utilities aliased in `index.css` (`bg-canvas`, `text-fg`, `border-line`, …) +// resolve everywhere — including portalled modals rendered into +// `document.body`. We write to `document.documentElement.style` instead of a +// wrapper `
` because portal children sit outside the React +// tree and can't inherit from a JSX ancestor. +{ + const vars = themeToCssVars(LIGHT_THEME) as Record; + for (const [key, value] of Object.entries(vars)) { + document.documentElement.style.setProperty(key, value); + } +} + +const { connectors } = getDefaultWallets({ + appName: "EpochIntentWidget Demo", + projectId: "demo", // WalletConnect project ID — replace with a real one for WC support +}); + +const rpcUrls = getDemoRpcUrls(import.meta.env); +const config = createConfig({ + connectors: [...connectors, localSigner()], + chains: getDemoChains(rpcUrls), + transports: Object.fromEntries( + Object.entries(rpcUrls).map(([chainId, url]) => [Number(chainId), http(url)]), + ), + ssr: false, +}); + +const queryClient = new QueryClient(); + +export default function RuntimeApp() { + const [network, setNetwork] = useState("mainnet"); + const midenConfig = + network === "testnet" + ? { + rpcUrl: MIDEN_TESTNET.rpcUrl, + noteTransportUrl: MIDEN_TESTNET.noteTransportUrl, + } + : { + rpcUrl: + import.meta.env.VITE_MIDEN_RPC_URL?.trim() || MIDEN_MAINNET.rpcUrl, + noteTransportUrl: + import.meta.env.VITE_MIDEN_NOTE_TRANSPORT_URL?.trim() || + MIDEN_MAINNET.noteTransportUrl, + }; + + return ( + + + + + + + + + + + + + ); +} diff --git a/demo/src/app/App.tsx b/demo/src/app/App.tsx index 444f705..446be76 100644 --- a/demo/src/app/App.tsx +++ b/demo/src/app/App.tsx @@ -1,16 +1,22 @@ -import { useEffect, useMemo, useState } from 'react'; -import { EpochIntentWidget, SegmentedTabs } from '@epoch-protocol/epoch-intent-widget'; -import type { ScenarioProps } from '../pay/scenarios'; -import { PAY_SCENARIOS, PAY_TESTNET_SCENARIOS } from '../pay/scenarios'; -import { getApiBaseUrl } from '../lib/apiBaseUrl'; -import { AppShell } from './AppShell'; -import type { DemoNetwork } from './AppShell'; -import type { DemoSurface } from '../types/surface'; -import { PaySurface } from '../surfaces/PaySurface'; -import { SwapSurface } from '../surfaces/SwapSurface'; -import { EarnSurface } from '../surfaces/EarnSurface'; -import { AdvancedSurface } from '../surfaces/AdvancedSurface'; -import { useEarnMidenAdapter } from '../earn/useEarnMidenAdapter'; +import { useEffect, useMemo, useState } from "react"; +import { + EpochIntentWidget, + SegmentedTabs, +} from "@epoch-protocol/epoch-intent-widget"; +import type { ScenarioProps } from "../pay/scenarios"; +import { PAY_SCENARIOS, PAY_TESTNET_SCENARIOS } from "../pay/scenarios"; +import { getApiBaseUrl } from "../lib/apiBaseUrl"; +import { AppShell } from "./AppShell"; +import type { DemoNetwork } from "./AppShell"; +import type { DemoSurface } from "../types/surface"; +import { PaySurface } from "../surfaces/PaySurface"; +import { SwapSurface } from "../surfaces/SwapSurface"; +import { EarnSurface } from "../surfaces/EarnSurface"; +import { AdvancedSurface } from "../surfaces/AdvancedSurface"; +import { useEarnMidenAdapter } from "../earn/useEarnMidenAdapter"; +import { getDemoRpcUrls } from "../config/rpc"; + +const rpcUrls = getDemoRpcUrls(import.meta.env); /** * Read `?advanced=1` once on mount. When set, the Advanced (Miden → EVM) @@ -18,37 +24,44 @@ import { useEarnMidenAdapter } from '../earn/useEarnMidenAdapter'; */ function useAdvancedFlag(): boolean { return useMemo(() => { - if (typeof window === 'undefined') return false; + if (typeof window === "undefined") return false; const params = new URLSearchParams(window.location.search); - return params.get('advanced') === '1'; + return params.get("advanced") === "1"; }, []); } -const PAY_TAB = { value: 'pay' as const, label: 'Pay' }; -const SWAP_TAB = { value: 'swap' as const, label: 'Swap' }; -const EARN_TAB = { value: 'earn' as const, label: 'Earn' }; -const ADVANCED_TAB = { value: 'advanced' as const, label: 'Advanced' }; +const PAY_TAB = { value: "pay" as const, label: "Pay" }; +const SWAP_TAB = { value: "swap" as const, label: "Swap" }; +const EARN_TAB = { value: "earn" as const, label: "Earn" }; +const ADVANCED_TAB = { value: "advanced" as const, label: "Advanced" }; + +interface AppProps { + network: DemoNetwork; + onNetworkChange: (network: DemoNetwork) => void; +} -export default function App() { +export default function App({ network, onNetworkChange }: AppProps) { const apiBaseUrl = getApiBaseUrl(); const earnSolverUrl = - (import.meta.env.VITE_EARN_SOLVER_URL as string | undefined) ?? 'http://localhost:3011'; + (import.meta.env.VITE_EARN_SOLVER_URL as string | undefined) ?? + "http://localhost:3011"; const positionsBaseUrl = - (import.meta.env.VITE_POSITIONS_API_BASE_URL as string | undefined) ?? 'http://localhost:4023'; + (import.meta.env.VITE_POSITIONS_API_BASE_URL as string | undefined) ?? + "http://localhost:4023"; const showAdvanced = useAdvancedFlag(); - const earnMiden = useEarnMidenAdapter(); - - const [network, setNetwork] = useState('mainnet'); + const earnMiden = useEarnMidenAdapter(network); const tabs = useMemo(() => { const base = [PAY_TAB, SWAP_TAB, EARN_TAB]; return showAdvanced ? [...base, ADVANCED_TAB] : base; }, [showAdvanced]); - const [surface, setSurface] = useState('pay'); + const [surface, setSurface] = useState("pay"); const [payScenarioId, setPayScenarioId] = useState(PAY_SCENARIOS[0].id); const [widgetOpen, setWidgetOpen] = useState(false); - const [widgetProps, setWidgetProps] = useState(PAY_SCENARIOS[0].props); + const [widgetProps, setWidgetProps] = useState( + PAY_SCENARIOS[0].props, + ); const openWidget = (props: ScenarioProps) => { setWidgetProps(props); @@ -58,18 +71,19 @@ export default function App() { // Defensive: if `?advanced=1` is removed mid-session and the saved surface // is `'advanced'`, fall back to Pay so we don't render a hidden tab. useEffect(() => { - if (surface === 'advanced' && !showAdvanced) setSurface('pay'); + if (surface === "advanced" && !showAdvanced) setSurface("pay"); }, [surface, showAdvanced]); // Reset pay scenario when network flips — testnet + mainnet have disjoint // scenario ids so the previously selected id won't match anything. useEffect(() => { - const scenarios = network === 'testnet' ? PAY_TESTNET_SCENARIOS : PAY_SCENARIOS; + const scenarios = + network === "testnet" ? PAY_TESTNET_SCENARIOS : PAY_SCENARIOS; setPayScenarioId(scenarios[0].id); }, [network]); return ( - +
tabs={tabs} @@ -80,7 +94,7 @@ export default function App() {
- {surface === 'pay' && ( + {surface === "pay" && ( )} - {surface === 'swap' && ( + {surface === "swap" && ( )} - {surface === 'earn' && ( + {surface === "earn" && ( )} - {surface === 'advanced' && showAdvanced && } + {surface === "advanced" && showAdvanced && ( + + )}
{(() => { - const widgetMode = widgetProps.mode ?? widgetProps.flow ?? 'pay'; - const isEarnMode = widgetMode === 'earn'; + const widgetMode = widgetProps.mode ?? widgetProps.flow ?? "pay"; + const isEarnMode = widgetMode === "earn"; return ( setWidgetOpen(false)} network={network} @@ -115,19 +131,24 @@ export default function App() { isEarnMode ? { baseUrl: apiBaseUrl, + rpcUrls, positionsBaseUrl, testnetBaseUrl: - (import.meta.env.VITE_TESTNET_API_BASE_URL as string | undefined) ?? - 'http://localhost:3000', + (import.meta.env.VITE_TESTNET_API_BASE_URL as + | string + | undefined) ?? "http://localhost:3000", testnetPositionsBaseUrl: - (import.meta.env.VITE_TESTNET_POSITIONS_API_BASE_URL as string | undefined) ?? - 'http://localhost:4024', + (import.meta.env.VITE_TESTNET_POSITIONS_API_BASE_URL as + | string + | undefined) ?? "http://localhost:4024", } : { baseUrl: apiBaseUrl, + rpcUrls, testnetBaseUrl: - (import.meta.env.VITE_TESTNET_API_BASE_URL as string | undefined) ?? - 'http://localhost:3000', + (import.meta.env.VITE_TESTNET_API_BASE_URL as + | string + | undefined) ?? "http://localhost:3000", } } /> diff --git a/demo/src/config/miden-mainnet.ts b/demo/src/config/miden-mainnet.ts new file mode 100644 index 0000000..27e54ff --- /dev/null +++ b/demo/src/config/miden-mainnet.ts @@ -0,0 +1,63 @@ +import { + EPOCH_MIDEN_MAINNET_CHAIN, + EPOCH_MIDEN_MAINNET_TOKENS, + EPOCH_SUPPORTED_TOKENS, +} from "@epoch-protocol/epoch-flows-sdk"; + +interface ViteApiEnvironment { + VITE_EPOCH_API_BASE_URL?: string; +} + +function required(value: T | undefined, description: string): T { + if (value === undefined) { + throw new Error(`Epoch Flows SDK is missing ${description}`); + } + return value; +} + +const baseUsdc = required( + EPOCH_SUPPORTED_TOKENS.find( + (token) => token.chainId === 8453 && token.symbol === "USDC", + ), + "Base USDC metadata", +); + +const midenUsdg = required( + EPOCH_MIDEN_MAINNET_TOKENS.find((token) => token.symbol === "USDG"), + "Miden mainnet USDG metadata", +); + +const midenUsdcx = required( + EPOCH_MIDEN_MAINNET_TOKENS.find((token) => token.symbol === "USDCX"), + "Miden mainnet USDCX metadata", +); + +export const BASE_MAINNET_USDC = Object.freeze({ + symbol: baseUsdc.symbol, + address: baseUsdc.address, + decimals: baseUsdc.decimals, + chainId: baseUsdc.chainId, +}); + +export const MIDEN_MAINNET = Object.freeze({ + chainId: EPOCH_MIDEN_MAINNET_CHAIN.id, + network: EPOCH_MIDEN_MAINNET_CHAIN.network, + rpcUrl: required(EPOCH_MIDEN_MAINNET_CHAIN.rpcUrl, "Miden Cedar RPC"), + noteTransportUrl: "https://transport.cedar.miden.io", + explorer: required(EPOCH_MIDEN_MAINNET_CHAIN.explorer, "Midenscan URL"), + usdg: Object.freeze({ + symbol: midenUsdg.symbol, + faucetId: midenUsdg.address, + decimals: midenUsdg.decimals, + }), + usdcx: Object.freeze({ + symbol: midenUsdcx.symbol, + faucetId: midenUsdcx.address, + decimals: midenUsdcx.decimals, + }), +}); + +export function resolveEpochApiBaseUrl(env: ViteApiEnvironment): string { + const configured = env.VITE_EPOCH_API_BASE_URL?.trim(); + return configured ? configured.replace(/\/$/, "") : "/allocator"; +} diff --git a/demo/src/config/miden-testnet.ts b/demo/src/config/miden-testnet.ts new file mode 100644 index 0000000..11585af --- /dev/null +++ b/demo/src/config/miden-testnet.ts @@ -0,0 +1,13 @@ +import { testnetGraph } from "@epoch-protocol/epoch-commons-sdk"; + +export const MIDEN_TESTNET = Object.freeze({ + chainId: testnetGraph.chains.Miden.chainId, + network: "miden-testnet", + rpcUrl: + import.meta.env.VITE_MIDEN_TESTNET_RPC_URL?.trim() || + "https://rpc.testnet.miden.io", + noteTransportUrl: + import.meta.env.VITE_MIDEN_TESTNET_NOTE_TRANSPORT_URL?.trim() || + "https://transport.miden.io", + explorer: testnetGraph.chains.Miden.explorer, +}); diff --git a/demo/src/config/rpc.ts b/demo/src/config/rpc.ts new file mode 100644 index 0000000..5333614 --- /dev/null +++ b/demo/src/config/rpc.ts @@ -0,0 +1,71 @@ +import { + mainnet, base, optimism, polygon, arbitrum, + baseSepolia, sepolia, optimismSepolia, robinhood, robinhoodTestnet, +} from "viem/chains"; +import type { Chain } from "viem"; + +// Infura supports these EVM networks. Miden keeps its separate native RPC. +export const INFURA_NETWORKS: Record = { + 1: "mainnet", + 8453: "base-mainnet", + 10: "optimism-mainnet", + 137: "polygon-mainnet", + 42161: "arbitrum-mainnet", + 84532: "base-sepolia", + 11155111: "sepolia", + 11155420: "optimism-sepolia", +}; + +export const DEMO_RPC_PATHS: Record = { + 1: "/widget/rpc/ethereum", + 8453: "/widget/rpc/base", + 10: "/widget/rpc/optimism", + 137: "/widget/rpc/polygon", + 42161: "/widget/rpc/arbitrum", + 84532: "/widget/rpc/base-sepolia", + 11155111: "/widget/rpc/sepolia", + 11155420: "/widget/rpc/optimism-sepolia", +}; + +export function getDemoRpcUrls(env: { + VITE_INFURA_RPC_PROXY_ENABLED?: boolean; + VITE_ANKR_API_KEY?: string; + VITE_BASE_RPC_URL?: string; + VITE_ROBINHOOD_RPC_URL?: string; + VITE_ROBINHOOD_TESTNET_RPC_URL?: string; +}): Record { + return { + ...(env.VITE_INFURA_RPC_PROXY_ENABLED ? DEMO_RPC_PATHS : { + 1: mainnet.rpcUrls.default.http[0], + 8453: getBaseRpcUrl(env.VITE_ANKR_API_KEY, env.VITE_BASE_RPC_URL), + 10: "https://mainnet.optimism.io", + 137: "https://polygon-bor-rpc.publicnode.com", + 42161: "https://arb1.arbitrum.io/rpc", + 84532: "https://sepolia.base.org", + 11155111: "https://eth-sepolia-testnet.api.pocket.network", + 11155420: "https://sepolia.optimism.io", + }), + [robinhood.id]: env.VITE_ROBINHOOD_RPC_URL?.trim() || robinhood.rpcUrls.default.http[0], + [robinhoodTestnet.id]: env.VITE_ROBINHOOD_TESTNET_RPC_URL?.trim() || robinhoodTestnet.rpcUrls.default.http[0], + }; +} + +export function getDemoChains(rpcUrls: Record): [Chain, ...Chain[]] { + // SDK reads may use walletClient.chain.rpcUrls rather than Wagmi's transport. + const withRpc = (chain: Chain): Chain => ({ + ...chain, + rpcUrls: { default: { http: [rpcUrls[chain.id]] } }, + }); + return [withRpc(mainnet), ...[ + base, optimism, polygon, arbitrum, baseSepolia, sepolia, optimismSepolia, + robinhood, robinhoodTestnet, + ].map(withRpc)]; +} + +export function getBaseRpcUrl(apiKey?: string, rpcUrl?: string): string { + if (rpcUrl?.trim()) return rpcUrl.trim(); + const key = apiKey?.trim(); + return key + ? `https://rpc.ankr.com/base/${key}` + : "https://mainnet.base.org"; +} diff --git a/demo/src/earn/useEarnMidenAdapter.ts b/demo/src/earn/useEarnMidenAdapter.ts index f7f77fe..4032d94 100644 --- a/demo/src/earn/useEarnMidenAdapter.ts +++ b/demo/src/earn/useEarnMidenAdapter.ts @@ -3,13 +3,14 @@ import { toast } from 'sonner'; import { type EarnMidenAdapter } from '@epoch-protocol/epoch-intent-widget'; import { useMidenWalletAdapter } from '../miden/hooks/useMidenWalletAdapter'; import { useMidenP2IDNoteFactory } from '../miden/hooks/useMidenP2IDNoteFactory'; +import type { DemoNetwork } from '../app/AppShell'; /** * Bridges the demo's Miden wallet adapter into {@link EarnMidenAdapter}, shared by * the earn and pay/swap flows. */ -export function useEarnMidenAdapter(): EarnMidenAdapter { - const midenWallet = useMidenWalletAdapter({ enabled: true }); +export function useEarnMidenAdapter(network: DemoNetwork): EarnMidenAdapter { + const midenWallet = useMidenWalletAdapter({ enabled: true, network }); const assets = useMemo(() => { // Keep the wallet's exact faucet ids. The widget matches these against graph @@ -44,6 +45,7 @@ export function useEarnMidenAdapter(): EarnMidenAdapter { enabled: true, connected: midenWallet.connected, accountId: midenWallet.accountId?.hex ?? null, + accountIsPublic: midenWallet.accountId?.isPublic ?? null, assets, connect, createP2IDNote, @@ -53,6 +55,7 @@ export function useEarnMidenAdapter(): EarnMidenAdapter { connect, createP2IDNote, midenWallet.accountId?.hex, + midenWallet.accountId?.isPublic, midenWallet.connected, ], ); diff --git a/demo/src/lib/apiBaseUrl.ts b/demo/src/lib/apiBaseUrl.ts index 84e4512..c738238 100644 --- a/demo/src/lib/apiBaseUrl.ts +++ b/demo/src/lib/apiBaseUrl.ts @@ -1,3 +1,5 @@ +import { resolveEpochApiBaseUrl } from "../config/miden-mainnet"; + export function getApiBaseUrl(): string { - return import.meta.env.VITE_EPOCH_API_BASE_URL ?? import.meta.env.VITE_ALLOCATOR_URL ?? 'http://localhost:3000'; + return resolveEpochApiBaseUrl(import.meta.env); } diff --git a/demo/src/main.tsx b/demo/src/main.tsx index 6cdb411..6081ff4 100644 --- a/demo/src/main.tsx +++ b/demo/src/main.tsx @@ -1,81 +1,80 @@ -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import { WagmiProvider, createConfig, http } from 'wagmi'; -import { arbitrum, base, baseSepolia, optimism, optimismSepolia, polygon, sepolia } from 'wagmi/chains'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { RainbowKitProvider, getDefaultWallets } from '@rainbow-me/rainbowkit'; -import './index.css'; -import '@epoch-protocol/epoch-intent-widget/styles.css'; -import '@rainbow-me/rainbowkit/styles.css'; -import 'sonner/dist/styles.css'; -import { Toaster } from 'sonner'; +import React, { useEffect, useState } from "react"; +import ReactDOM from "react-dom/client"; +import { mainnetGraph } from "@epoch-protocol/epoch-commons-sdk"; +import "./index.css"; +import "@epoch-protocol/epoch-intent-widget/styles.css"; +import "@rainbow-me/rainbowkit/styles.css"; +import "sonner/dist/styles.css"; import { - AllowedPrivateData, - WalletAdapterNetwork, -} from '@miden-sdk/miden-wallet-adapter-base'; -import { MidenFiSignerProvider } from '@miden-sdk/miden-wallet-adapter-react'; -import { MidenProvider } from '@miden-sdk/react'; -import { themeToCssVars, LIGHT_THEME } from '@epoch-protocol/epoch-intent-widget'; -import App from './app/App'; -import { localSigner } from './wallet/local-signer'; + DEFAULT_MIDEN_MAINNET_RPC_URL, + ensurePragmaMidenMainnetOracle, + type MainnetOracleGraph, +} from "./miden/lib/mainnet-sdk-compat"; -// Project the library's `--epoch-*` design tokens onto `:root` so Tailwind -// utilities aliased in `index.css` (`bg-canvas`, `text-fg`, `border-line`, …) -// resolve everywhere — including portalled modals rendered into -// `document.body`. We write to `document.documentElement.style` instead of a -// wrapper `
` because portal children sit outside the React -// tree and can't inherit from a JSX ancestor. -{ - const vars = themeToCssVars(LIGHT_THEME) as Record; - for (const [key, value] of Object.entries(vars)) { - document.documentElement.style.setProperty(key, value); - } -} +ensurePragmaMidenMainnetOracle( + mainnetGraph as unknown as MainnetOracleGraph, + import.meta.env.VITE_MIDEN_RPC_URL?.trim() || + DEFAULT_MIDEN_MAINNET_RPC_URL, +); -const { connectors } = getDefaultWallets({ - appName: 'EpochIntentWidget Demo', - projectId: 'demo', // WalletConnect project ID — replace with a real one for WC support -}); +const bootScreenStyle: React.CSSProperties = { + minHeight: "100vh", + display: "grid", + placeItems: "center", + padding: "24px", + color: "#25292e", + background: "#f8f9fb", + fontFamily: + 'SFRounded, ui-rounded, "SF Pro Rounded", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif', +}; -const config = createConfig({ - connectors: [...connectors, localSigner()], - chains: [base, optimism, polygon, arbitrum, baseSepolia, sepolia, optimismSepolia], - transports: { - [base.id]: http('https://mainnet.base.org'), - [optimism.id]: http('https://mainnet.optimism.io'), - [polygon.id]: http('https://polygon.lava.build'), - [arbitrum.id]: http('https://arb1.arbitrum.io/rpc'), - [baseSepolia.id]: http('https://sepolia.base.org'), - [sepolia.id]: http('https://eth-sepolia-testnet.api.pocket.network'), - [optimismSepolia.id]: http('https://sepolia.optimism.io'), - }, - ssr: false, -}); +function Bootstrap() { + const [RuntimeApp, setRuntimeApp] = + useState(null); + const [loadError, setLoadError] = useState(null); -const queryClient = new QueryClient(); + useEffect(() => { + let active = true; -const midenConfig = { - rpcUrl: import.meta.env.VITE_MIDEN_RPC_URL?.trim(), - noteTransportUrl: import.meta.env.VITE_MIDEN_NOTE_TRANSPORT_URL?.trim(), -}; + import("./RuntimeApp") + .then((module) => { + if (active) setRuntimeApp(() => module.default); + }) + .catch((error: unknown) => { + if (!active) return; + setLoadError(error instanceof Error ? error.message : String(error)); + }); + + return () => { + active = false; + }; + }, []); + + if (RuntimeApp) return ; + + if (loadError) { + return ( +
+
+

Miden runtime did not load

+

{loadError}

+ +
+
+ ); + } + + return ( +
+ Loading Miden integration… +
+ ); +} -ReactDOM.createRoot(document.getElementById('root')!).render( +ReactDOM.createRoot(document.getElementById("root")!).render( - - - - - - - - - - - - + , ); diff --git a/demo/src/miden/MidenBridgePanel.tsx b/demo/src/miden/MidenBridgePanel.tsx index 64e3a52..89bb3d2 100644 --- a/demo/src/miden/MidenBridgePanel.tsx +++ b/demo/src/miden/MidenBridgePanel.tsx @@ -2,13 +2,16 @@ * Miden → EVM bridge demo (ported from miden-integration-example CrosschainTab). * Styled with Tailwind (demo shell tokens). */ -import { useEffect, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { useAccount } from "wagmi"; import type { CrossChainIntentParams } from "./types/miden"; import type { IntentResult } from "./types/miden"; import { explorerTxUrl, truncateHash, MIDEN_CHAIN_ID } from "./lib/explorers"; -import { DEFAULT_SEPOLIA_CHAIN_ID_STR } from "./constants/chains"; -import { getMidenFaucetDecimals } from "./constants/miden-tokens"; +import { + getMidenFaucetDecimals, + isMidenMainnetUsdcx, +} from "./constants/miden-tokens"; +import { BASE_MAINNET_USDC, MIDEN_MAINNET } from "../config/miden-mainnet"; import { useMidenWalletAdapter } from "./hooks/useMidenWalletAdapter"; import { useEpochIntent } from "./hooks/useEpochIntent"; import { useIntentFlowStatus } from "./hooks/useIntentFlowStatus"; @@ -18,32 +21,8 @@ import { MidenWalletsSection } from "./components/MidenWalletsSection"; import { useMidenBridgeIntent } from "./hooks/useMidenBridgeIntent"; import { MidenBridgeFields } from "./components/MidenBridgeFields"; -const SEPOLIA_TOKENS: ReadonlyArray<{ - symbol: string; - address: string; - decimals: number; -}> = [ - { - symbol: "USDC", - address: "0x2BB4FfD7E2c6D432b697554Efd77fA13bdbefd69", - decimals: 18, - }, - { - symbol: "DAI", - address: "0xc30f1Ce05d1434d484E9A47283aA925fc8A8699a", - decimals: 18, - }, - { - symbol: "USDT", - address: "0xc04d2869665Be874881133943523723Be5782720", - decimals: 18, - }, - { - symbol: "WETH", - address: "0x7946dd86eE310D0aC16804A37787289Fa5b88A8A", - decimals: 18, - }, -]; +const BASE_TOKENS = [BASE_MAINNET_USDC] as const; +const TERMINAL_OK = new Set(["success", "completed"]); function fallbackMidenNoteId(result: IntentResult | null): string | undefined { if (!result) return undefined; @@ -63,10 +42,9 @@ export function MidenBridgePanel() { const epoch = useEpochIntent(); const { address } = useAccount(); - const [selectedAssetId, setSelectedAssetId] = useState(""); - const [minTokenOut, setMinTokenOut] = useState("1000000000000000000"); - const [outputToken, setOutputToken] = useState(SEPOLIA_TOKENS[0].address); - const [chainId, setChainId] = useState(DEFAULT_SEPOLIA_CHAIN_ID_STR); + const [minTokenOut, setMinTokenOut] = useState("1000000"); + const outputToken = BASE_MAINNET_USDC.address; + const chainId = String(BASE_MAINNET_USDC.chainId); const [evmAddress, setEvmAddress] = useState(""); useEffect(() => { @@ -89,11 +67,17 @@ export function MidenBridgePanel() { Number.isInteger(destinationChainIdNum) && destinationChainIdNum > 0; const resolvedEvmRecipient = (evmAddress.trim() || address || "").trim(); const hasValidEvmRecipient = /^0x[a-fA-F0-9]{40}$/.test(resolvedEvmRecipient); - const selectedAsset = midenWallet.assets.find( + const bridgeAssets = useMemo( + () => + midenWallet.assets.filter((asset) => isMidenMainnetUsdcx(asset.assetId)), + [midenWallet.assets], + ); + const selectedAssetId = bridgeAssets[0]?.assetId ?? ""; + const selectedAsset = bridgeAssets.find( (a) => a.assetId.toLowerCase() === selectedAssetId.toLowerCase(), ); - // Hardcoded map — wallet adapter's reported `decimals` is unreliable (often - // defaults to 8 and silently mis-scales 6-decimal tokens). `undefined` here + // Graph-backed decimals avoid the wallet adapter fallback (often + // 8), which would silently mis-scale six-decimal USDCX. `undefined` here // gates the form via `Number.isFinite` below. const midenFaucetDecimals = selectedAssetId ? getMidenFaucetDecimals(selectedAssetId) @@ -110,7 +94,7 @@ export function MidenBridgePanel() { throw new Error("Destination chain ID must be a positive integer."); } if (!midenWallet.accountId?.hex) { - throw new Error("Connect Miden wallet first"); + throw new Error("Connect a public Miden account first"); } if (midenFaucetDecimals === undefined) { throw new Error( @@ -155,8 +139,7 @@ export function MidenBridgePanel() { effectiveIntentNonce, ); - const midenScanBase = - import.meta.env.VITE_MIDENSCAN_URL ?? "https://testnet.midenscan.com"; + const midenScanBase = MIDEN_MAINNET.explorer; const midenNoteUrl = intent.localMidenNoteId ? `${midenScanBase}/note/${intent.localMidenNoteId}` : undefined; @@ -170,7 +153,6 @@ export function MidenBridgePanel() { const evmStatuses = txStatuses.filter( (s) => Number(s.chainId) !== MIDEN_CHAIN_ID, ); - const TERMINAL_OK = new Set(["success", "completed"]); const evmCompletedStatus = evmStatuses.find( (s) => TERMINAL_OK.has(String(s.status).toLowerCase()) && @@ -191,9 +173,9 @@ export function MidenBridgePanel() {

Miden → EVM bridge

- Connect an Ethereum wallet and a Miden wallet. Pick a Miden asset and - EVM output token, get a quote, then confirm to create the P2IDE note - and submit the cross-chain intent (same flow as{" "} + Connect Base and a public Miden mainnet wallet. Deposit native USDCX + and receive Base USDC, get a quote, then confirm to create the P2IDE + note and submit the cross-chain intent (same flow as{" "} miden-integration-example @@ -207,6 +189,11 @@ export function MidenBridgePanel() { onConnectMiden={() => void midenWallet.connect()} /> + {midenWallet.assetsError ? ( +

+ {midenWallet.assetsError} +

+ ) : null}

Intent details

@@ -216,22 +203,19 @@ export function MidenBridgePanel() {

epoch.clearQuote()} + onDirty={epoch.clearQuote} /> {epoch.pendingQuote && ( @@ -306,7 +290,9 @@ export function MidenBridgePanel() { {intent.localMidenNoteId} ) : ( - {intent.localMidenNoteId} + + {intent.localMidenNoteId} + )}
@@ -350,4 +336,3 @@ export function MidenBridgePanel() {
); } - diff --git a/demo/src/miden/components/MidenBridgeFields.tsx b/demo/src/miden/components/MidenBridgeFields.tsx index d37e7be..b86a10e 100644 --- a/demo/src/miden/components/MidenBridgeFields.tsx +++ b/demo/src/miden/components/MidenBridgeFields.tsx @@ -12,13 +12,10 @@ interface MidenBridgeFieldsProps { isLoadingAssets: boolean; outputTokens: ReadonlyArray; selectedAssetId: string; - setSelectedAssetId: (v: string) => void; outputToken: string; - setOutputToken: (v: string) => void; minTokenOut: string; setMinTokenOut: (v: string) => void; chainId: string; - setChainId: (v: string) => void; evmAddress: string; setEvmAddress: (v: string) => void; /** The connected EVM wallet, offered as a one-click recipient. */ @@ -40,13 +37,10 @@ export function MidenBridgeFields({ isLoadingAssets, outputTokens, selectedAssetId, - setSelectedAssetId, outputToken, - setOutputToken, minTokenOut, setMinTokenOut, chainId, - setChainId, evmAddress, setEvmAddress, connectedAddress, @@ -61,126 +55,115 @@ export function MidenBridgeFields({ return ( <> -
- - -
- Balance: {selectedAssetBalance?.toString() ?? "—"} -
-
+
+ + +
+ Balance: {selectedAssetBalance?.toString() ?? "—"} +
+
-
-
- - -
-
- - { - setMinTokenOut(e.target.value); - onDirty(); - }} - /> -
-
+
+
+ + +
+
+ + { + setMinTokenOut(e.target.value); + onDirty(); + }} + /> +
+
-
- - { - setChainId(e.target.value); - onDirty(); - }} - /> -
+
+ + +
-
- - { - setEvmAddress(e.target.value); - onDirty(); - }} - placeholder={connectedAddress ?? "0x…"} - /> - {connectedAddress && ( - - )} -
+
+ + { + setEvmAddress(e.target.value); + onDirty(); + }} + placeholder={connectedAddress ?? "0x…"} + /> + {connectedAddress && ( + + )} +
); } diff --git a/demo/src/miden/constants/miden-tokens.ts b/demo/src/miden/constants/miden-tokens.ts index 5a0eb9d..559204a 100644 --- a/demo/src/miden/constants/miden-tokens.ts +++ b/demo/src/miden/constants/miden-tokens.ts @@ -1,36 +1,24 @@ -import { normalizeMidenIdToHex } from "../services/epoch-bridge"; - -/** - * Hardcoded Miden faucet → decimals map. - * - * Backend (sio/dex-solver/inventory) does not surface faucet decimals to the - * frontend; relying on the wallet adapter's reported `decimals` is unreliable - * (some adapters return 8 by default which silently mis-scales 6-decimal - * tokens by 100x). Frontends must look up decimals here. - * - * Keys are normalized to lowercase hex without `0x` prefix. Lookups go through - * `normalizeMidenIdToHex` first so bech32 faucet ids from the wallet adapter - * (e.g. `mtst1qxxxxxxxxxxxxx_xxxxxx`) resolve correctly. - */ -const MIDEN_FAUCET_DECIMALS: Record = { - "537c15a622074e91188aa894456c52": 6, // USDC - d17976f0809a8191412f2a126625df: 6, // DAI - "6500ca8c2dd69e9147ab7eafad162c": 6, // USDT - "4a09f13153d9cd114c078bfb62a7ec": 6, // WETH - "5fd2e6fd17712c51404d09c2b847f7": 6, // WBTC -}; +import { normalizeMidenId } from "@epoch-protocol/epoch-commons-sdk"; +import { EPOCH_MIDEN_MAINNET_TOKENS } from "@epoch-protocol/epoch-flows-sdk"; +import { MIDEN_MAINNET } from "../../config/miden-mainnet"; function toMapKey(faucetId: string): string { - const hex = normalizeMidenIdToHex(faucetId); - const lower = hex.trim().toLowerCase(); - return lower.startsWith("0x") ? lower.slice(2) : lower; + return normalizeMidenId(faucetId).trim().toLowerCase().replace(/^0x/, ""); +} + +export function isMidenMainnetUsdcx(faucetId: string): boolean { + if (!faucetId) return false; + try { + return toMapKey(faucetId) === toMapKey(MIDEN_MAINNET.usdcx.faucetId); + } catch { + return false; + } } -/** Returns Miden faucet decimals, or `undefined` if the faucet is unknown. */ export function getMidenFaucetDecimals(faucetId: string): number | undefined { - if (!faucetId) return undefined; try { - return MIDEN_FAUCET_DECIMALS[toMapKey(faucetId)]; + const key = toMapKey(faucetId); + return EPOCH_MIDEN_MAINNET_TOKENS.find((token) => toMapKey(token.address) === key)?.decimals; } catch { return undefined; } diff --git a/demo/src/miden/hooks/useEpochIntent.ts b/demo/src/miden/hooks/useEpochIntent.ts index 0c2ca19..eaccdaa 100644 --- a/demo/src/miden/hooks/useEpochIntent.ts +++ b/demo/src/miden/hooks/useEpochIntent.ts @@ -1,19 +1,28 @@ -import { useState, useCallback, useEffect } from 'react'; -import { useAccount, useWalletClient } from 'wagmi'; +import { useState, useCallback, useEffect } from "react"; +import { useAccount, useWalletClient } from "wagmi"; import { buildCrossChainIntent, getCrossChainQuote, type CrossChainQuote, -} from '../services/epoch-bridge'; -import type { CrossChainIntentParams, IntentResult } from '../types/miden'; -import { CollateralType, type SolveIntentParams } from '@epoch-protocol/epoch-intents-sdk/dist/types'; +} from "../services/epoch-bridge"; +import type { CrossChainIntentParams, IntentResult } from "../types/miden"; +import { + MIDEN_MAINNET, + resolveEpochApiBaseUrl, +} from "../../config/miden-mainnet"; +import { + CollateralType, + type SolveIntentParams, +} from "@epoch-protocol/epoch-intents-sdk/dist/types"; export function useEpochIntent() { const [intentResult, setIntentResult] = useState(null); const [isLoading, setIsLoading] = useState(false); const [isFetchingQuote, setIsFetchingQuote] = useState(false); const [error, setError] = useState(null); - const [pendingQuote, setPendingQuote] = useState(null); + const [pendingQuote, setPendingQuote] = useState( + null, + ); const [sdk, setSdk] = useState(null); const { data: walletClient } = useWalletClient(); @@ -25,106 +34,122 @@ export function useEpochIntent() { return; } let cancelled = false; - import('@epoch-protocol/epoch-intents-sdk').then(({ EpochIntentSDK }) => { - if (cancelled) return; - const apiBaseUrl = - import.meta.env.VITE_EPOCH_API_BASE_URL || - import.meta.env.VITE_ALLOCATOR_URL || - 'http://localhost:3000'; - console.log('apiBaseUrl: ', apiBaseUrl); - const midenWalletClient = { - ...(walletClient as any), - chain: { ...((walletClient as any)?.chain ?? {}), id: 999999999 }, - }; - setSdk(new EpochIntentSDK({ apiBaseUrl, walletClient: midenWalletClient })); - }).catch((err) => { - if (cancelled) return; - console.error('[CrossChain] Failed to load Epoch SDK:', err); - setSdk(null); - }); - return () => { cancelled = true; }; + import("@epoch-protocol/epoch-intents-sdk") + .then(({ EpochIntentSDK }) => { + if (cancelled) return; + const apiBaseUrl = resolveEpochApiBaseUrl(import.meta.env); + console.log("apiBaseUrl: ", apiBaseUrl); + const midenWalletClient = { + ...(walletClient as any), + chain: { + ...((walletClient as any)?.chain ?? {}), + id: MIDEN_MAINNET.chainId, + }, + }; + setSdk( + new EpochIntentSDK({ apiBaseUrl, walletClient: midenWalletClient }), + ); + }) + .catch((err) => { + if (cancelled) return; + console.error("[CrossChain] Failed to load Epoch SDK:", err); + setSdk(null); + }); + return () => { + cancelled = true; + }; }, [walletClient]); /** Step 1: fetch a reverse quote (tokenInAmount=0 → backend computes required Miden input). */ - const fetchQuote = useCallback(async (params: CrossChainIntentParams) => { - if (!sdk) throw new Error('Epoch SDK not ready — connect EVM wallet first'); - if (!address) throw new Error('Connect EVM wallet first'); - setIsFetchingQuote(true); - setError(null); - setPendingQuote(null); - try { - const quote = await getCrossChainQuote(sdk, params, address); - setPendingQuote(quote); - } catch (err) { - const msg = err instanceof Error ? err.message : 'Quote failed'; - setError(msg); - throw err; - } finally { - setIsFetchingQuote(false); - } - }, [sdk, address]); + const fetchQuote = useCallback( + async (params: CrossChainIntentParams) => { + if (!sdk) + throw new Error("Epoch SDK not ready — connect EVM wallet first"); + if (!address) throw new Error("Connect EVM wallet first"); + setIsFetchingQuote(true); + setError(null); + setPendingQuote(null); + try { + const quote = await getCrossChainQuote(sdk, params, address); + setPendingQuote(quote); + } catch (err) { + const msg = err instanceof Error ? err.message : "Quote failed"; + setError(msg); + throw err; + } finally { + setIsFetchingQuote(false); + } + }, + [sdk, address], + ); /** Step 2: execute the stored quote by creating the P2ID note and submitting the intent. */ - const confirmIntent = useCallback(async ( - createMidenP2IDNote: SolveIntentParams['createMidenP2IDNote'], - ) => { - if (!sdk) throw new Error('Epoch SDK not ready'); - if (!pendingQuote) throw new Error('Fetch a quote first'); - setIsLoading(true); - setError(null); - setIntentResult(null); - try { - const result = await buildCrossChainIntent(sdk, { - ...pendingQuote.params, - collateralType: CollateralType.Miden, - midenSourceAccount: pendingQuote.params.midenAccountId, - createMidenP2IDNote, - preFetchedQuote: pendingQuote, - }); - if (result?.error) { - // Keep the existing quote visible so user can retry confirmation. + const confirmIntent = useCallback( + async (createMidenP2IDENote: SolveIntentParams["createMidenP2IDENote"]) => { + if (!sdk) throw new Error("Epoch SDK not ready"); + if (!pendingQuote) throw new Error("Fetch a quote first"); + setIsLoading(true); + setError(null); + setIntentResult(null); + try { + const result = await buildCrossChainIntent(sdk, { + ...pendingQuote.params, + collateralType: CollateralType.Miden, + midenSourceAccount: pendingQuote.params.midenAccountId, + createMidenP2IDENote, + preFetchedQuote: pendingQuote, + }); + if (result?.error) { + // Keep the existing quote visible so user can retry confirmation. + setIntentResult(result); + setError(result.error); + throw new Error(result.error); + } setIntentResult(result); - setError(result.error); - throw new Error(result.error); + setPendingQuote(null); + return result; + } catch (err) { + const msg = + err instanceof Error ? err.message : "Failed to confirm intent"; + setError(msg); + throw err; + } finally { + setIsLoading(false); } - setIntentResult(result); - setPendingQuote(null); - return result; - } catch (err) { - const msg = err instanceof Error ? err.message : 'Failed to confirm intent'; - setError(msg); - throw err; - } finally { - setIsLoading(false); - } - }, [sdk, pendingQuote]); + }, + [sdk, pendingQuote], + ); /** Direct-bridge path: skip quote, call buildCrossChainIntent with explicit midenAmount. */ - const submitDirectIntent = useCallback(async ( - params: CrossChainIntentParams, - createMidenP2IDNote: SolveIntentParams['createMidenP2IDNote'], - ) => { - if (!sdk) throw new Error('Epoch SDK not ready'); - setIsLoading(true); - setError(null); - setIntentResult(null); - try { - const result = await buildCrossChainIntent(sdk, { - ...params, - collateralType: CollateralType.Miden, - midenSourceAccount: params.midenAccountId, - createMidenP2IDNote, - }); - setIntentResult(result); - return result; - } catch (err) { - const msg = err instanceof Error ? err.message : 'Failed to submit direct intent'; - setError(msg); - throw err; - } finally { - setIsLoading(false); - } - }, [sdk]); + const submitDirectIntent = useCallback( + async ( + params: CrossChainIntentParams, + createMidenP2IDENote: SolveIntentParams["createMidenP2IDENote"], + ) => { + if (!sdk) throw new Error("Epoch SDK not ready"); + setIsLoading(true); + setError(null); + setIntentResult(null); + try { + const result = await buildCrossChainIntent(sdk, { + ...params, + collateralType: CollateralType.Miden, + midenSourceAccount: params.midenAccountId, + createMidenP2IDENote, + }); + setIntentResult(result); + return result; + } catch (err) { + const msg = + err instanceof Error ? err.message : "Failed to submit direct intent"; + setError(msg); + throw err; + } finally { + setIsLoading(false); + } + }, + [sdk], + ); const clearQuote = useCallback(() => { setPendingQuote(null); diff --git a/demo/src/miden/hooks/useIntentTransactionStatus.ts b/demo/src/miden/hooks/useIntentTransactionStatus.ts index f7821bb..57c1488 100644 --- a/demo/src/miden/hooks/useIntentTransactionStatus.ts +++ b/demo/src/miden/hooks/useIntentTransactionStatus.ts @@ -1,18 +1,29 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; -import { useWalletClient } from 'wagmi'; -import type { IntentTransactionStatus } from '@epoch-protocol/epoch-intents-sdk/dist/types'; +import { useCallback, useEffect, useRef, useState } from "react"; +import { useWalletClient } from "wagmi"; +import type { IntentTransactionStatus } from "@epoch-protocol/epoch-intents-sdk/dist/types"; +import { resolveEpochApiBaseUrl } from "../../config/miden-mainnet"; const POLL_INTERVAL = 5000; -const LOG = '[useIntentTransactionStatus]'; +const LOG = "[useIntentTransactionStatus]"; -const TERMINAL_STATUSES = new Set(['success', 'completed', 'failed', 'reverted']); +const TERMINAL_STATUSES = new Set([ + "success", + "completed", + "failed", + "reverted", +]); function isTerminal(statuses: IntentTransactionStatus[]): boolean { if (statuses.length === 0) return false; - return statuses.every((s) => TERMINAL_STATUSES.has(String(s.status).toLowerCase())); + return statuses.every((s) => + TERMINAL_STATUSES.has(String(s.status).toLowerCase()), + ); } -export function useIntentTransactionStatus(userAddress?: string, intentNonce?: string) { +export function useIntentTransactionStatus( + userAddress?: string, + intentNonce?: string, +) { const [statuses, setStatuses] = useState([]); const [isPolling, setIsPolling] = useState(false); const [error, setError] = useState(null); @@ -29,18 +40,18 @@ export function useIntentTransactionStatus(userAddress?: string, intentNonce?: s return; } let cancelled = false; - const apiBaseUrl = - import.meta.env.VITE_EPOCH_API_BASE_URL || - import.meta.env.VITE_ALLOCATOR_URL || - 'http://localhost:3000'; + const apiBaseUrl = resolveEpochApiBaseUrl(import.meta.env); console.log(`${LOG} loading SDK, apiBaseUrl=${apiBaseUrl}`); - import('@epoch-protocol/epoch-intents-sdk') + import("@epoch-protocol/epoch-intents-sdk") .then(({ EpochIntentSDK }) => { if (cancelled) { console.log(`${LOG} SDK load cancelled`); return; } - const instance = new EpochIntentSDK({ apiBaseUrl, walletClient: walletClient as any }); + const instance = new EpochIntentSDK({ + apiBaseUrl, + walletClient: walletClient as any, + }); console.log(`${LOG} SDK ready`); setSdk(instance); }) @@ -74,9 +85,14 @@ export function useIntentTransactionStatus(userAddress?: string, intentNonce?: s } pollCountRef.current += 1; const attempt = pollCountRef.current; - console.log(`${LOG} poll #${attempt} → getIntentStatus(${userAddress}, ${intentNonce})`); + console.log( + `${LOG} poll #${attempt} → getIntentStatus(${userAddress}, ${intentNonce})`, + ); try { - const result: IntentTransactionStatus[] = await sdk.getIntentStatus(userAddress, intentNonce); + const result: IntentTransactionStatus[] = await sdk.getIntentStatus( + userAddress, + intentNonce, + ); const arr = Array.isArray(result) ? result : []; console.log(`${LOG} poll #${attempt} result:`, arr); setStatuses(arr); @@ -86,7 +102,8 @@ export function useIntentTransactionStatus(userAddress?: string, intentNonce?: s stopPolling(); } } catch (err) { - const msg = err instanceof Error ? err.message : 'Failed to fetch intent status'; + const msg = + err instanceof Error ? err.message : "Failed to fetch intent status"; console.error(`${LOG} poll #${attempt} error:`, err); setError(msg); } diff --git a/demo/src/miden/hooks/useMidenBridgeIntent.ts b/demo/src/miden/hooks/useMidenBridgeIntent.ts index 5d8b40e..2a85d5c 100644 --- a/demo/src/miden/hooks/useMidenBridgeIntent.ts +++ b/demo/src/miden/hooks/useMidenBridgeIntent.ts @@ -9,7 +9,7 @@ interface UseMidenBridgeIntentOptions { pendingQuote: unknown; fetchQuote: (params: CrossChainIntentParams) => Promise; confirmIntent: ( - createNote: SolveIntentParams["createMidenP2IDNote"], + createNote: SolveIntentParams["createMidenP2IDENote"], ) => Promise; }; midenAccountIdHex: string | undefined; @@ -84,7 +84,7 @@ export function useMidenBridgeIntent({ // Mints the P2IDE note *with* its reclaim height and mandate-binding // attachment — a plain wallet send carries neither, and the allocator rejects // such a note as "not bound to the intent mandate". - const createMidenP2IDNote = useMidenP2IDNoteFactory({ + const createMidenP2IDENote = useMidenP2IDNoteFactory({ midenAccountId: midenAccountIdHex ?? null, onStatus: setConfirmStatus, onNoteCreated: setLocalMidenNoteId, @@ -95,7 +95,7 @@ export function useMidenBridgeIntent({ void toast.promise( (async () => { setConfirmStatus("Submitting intent…"); - const result = await epoch.confirmIntent(createMidenP2IDNote); + const result = await epoch.confirmIntent(createMidenP2IDENote); if ( result && typeof result === "object" && diff --git a/demo/src/miden/hooks/useMidenWalletAdapter.ts b/demo/src/miden/hooks/useMidenWalletAdapter.ts index 8b4df1a..0c52645 100644 --- a/demo/src/miden/hooks/useMidenWalletAdapter.ts +++ b/demo/src/miden/hooks/useMidenWalletAdapter.ts @@ -4,14 +4,20 @@ import { useMidenFiWallet } from "@miden-sdk/miden-wallet-adapter-react"; import { AllowedPrivateData, PrivateDataPermission, - WalletAdapterNetwork, WalletReadyState, } from "@miden-sdk/miden-wallet-adapter-base"; import { useAssetMetadata, toBech32AccountId } from "@miden-sdk/react"; import { AccountId, Address } from "@miden-sdk/miden-sdk"; +import { + MIDEN_MAINNET_WALLET_NETWORK, + MIDEN_TESTNET_WALLET_NETWORK, + normalizeMidenAccount, +} from "../lib/mainnet-wallet-compat"; +import type { DemoNetwork } from "../../app/AppShell"; export interface NormalizedMidenAccountId { hex: string; + isPublic: boolean; } export interface MidenWalletAsset { @@ -24,6 +30,7 @@ export interface MidenWalletAsset { export interface UseMidenWalletAdapterOptions { enabled?: boolean; + network?: DemoNetwork; } export interface UseMidenWalletAdapterResult { @@ -39,7 +46,10 @@ export interface UseMidenWalletAdapterResult { /** Strip `miden:` prefix and `_BasicWallet`-style interface suffixes before parsing. */ const stripMidenIdDecorators = (raw: string): string => { - const trimmed = raw.replace(/\s+/g, "").trim().replace(/^miden:/i, ""); + const trimmed = raw + .replace(/\s+/g, "") + .trim() + .replace(/^miden:/i, ""); const underscore = trimmed.indexOf("_"); if (underscore > 0 && (trimmed.startsWith("m") || trimmed.startsWith("M"))) { return trimmed.slice(0, underscore); @@ -51,7 +61,9 @@ const stripMidenIdDecorators = (raw: string): string => { * Parse a Miden account id to canonical hex. Requires WASM — returns null when * the SDK is not ready or the format is unrecognized. */ -const resolveAccountId = (rawAddress: string | null): NormalizedMidenAccountId | null => { +const resolveAccountId = ( + rawAddress: string | null, +): NormalizedMidenAccountId | null => { if (!rawAddress) return null; const input = stripMidenIdDecorators(rawAddress); if (!input) return null; @@ -81,7 +93,7 @@ const resolveAccountId = (rawAddress: string | null): NormalizedMidenAccountId | if (!id) return null; try { - return { hex: id.toString() }; + return normalizeMidenAccount(id); } catch { return null; } @@ -90,7 +102,7 @@ const resolveAccountId = (rawAddress: string | null): NormalizedMidenAccountId | export function useMidenWalletAdapter( options: UseMidenWalletAdapterOptions = {}, ): UseMidenWalletAdapterResult { - const { enabled = true } = options; + const { enabled = true, network = "mainnet" } = options; const { connected, connect: adapterConnect, @@ -102,10 +114,12 @@ export function useMidenWalletAdapter( wallets, } = useMidenFiWallet(); - const [accountId, setAccountId] = useState(null); + const [accountId, setAccountId] = useState( + null, + ); - // AccountId parsing touches WASM and often fails on first render. Keep the raw - // wallet address usable immediately, then upgrade to canonical hex once ready. + // AccountId parsing touches WASM and often fails on first render. Keep quote + // eligibility disabled until the address parses. useEffect(() => { if (!address?.trim()) { setAccountId(null); @@ -119,11 +133,7 @@ export function useMidenWalletAdapter( return; } - if (connected) { - setAccountId({ hex: trimmed }); - } else { - setAccountId(null); - } + setAccountId(null); let cancelled = false; void import("@miden-sdk/miden-sdk/lazy") @@ -134,7 +144,7 @@ export function useMidenWalletAdapter( if (retry) setAccountId(retry); }) .catch(() => { - // Keep fallback raw id when WASM never becomes available. + // Keep quote eligibility disabled when WASM never becomes available. }); return () => { @@ -147,29 +157,34 @@ export function useMidenWalletAdapter( error: assetsRequestError, refetch, } = useQuery({ - queryKey: ["miden-assets", address], + // The same wallet address can be connected on both Miden networks, but + // its faucet ids and balances are network-specific. Include the selected + // network/account so a cached mainnet asset list cannot mask testnet funds. + queryKey: ["miden-assets", network, address, accountId?.hex ?? null], queryFn: async () => (await requestAssets!()) ?? [], enabled: enabled && connected && !!address && !!requestAssets, - staleTime: Infinity, - refetchOnWindowFocus: false, - refetchOnMount: false, - refetchOnReconnect: false, + staleTime: 15_000, + refetchOnWindowFocus: true, + refetchOnReconnect: true, }); const assetsError = - enabled && connected && !requestAssets + (enabled && connected && !requestAssets ? "Connected wallet does not support requestAssets()" : assetsRequestError instanceof Error ? assetsRequestError.message : assetsRequestError ? "Failed to load assets" - : null; + : null); const refreshAssets = useCallback(async () => { await refetch(); }, [refetch]); - const faucetIds = useMemo(() => rawAssets.map((a) => a.faucetId), [rawAssets]); + const faucetIds = useMemo( + () => rawAssets.map((a) => a.faucetId), + [rawAssets], + ); const { assetMetadata } = useAssetMetadata(faucetIds); const assets = useMemo( @@ -198,11 +213,13 @@ export function useMidenWalletAdapter( return; } - const target = wallet ?? wallets.find( - ({ readyState }) => - readyState === WalletReadyState.Installed || - readyState === WalletReadyState.Loadable, - ); + const target = + wallet ?? + wallets.find( + ({ readyState }) => + readyState === WalletReadyState.Installed || + readyState === WalletReadyState.Loadable, + ); if (!target) { throw new Error("No Miden wallet adapter is available"); } @@ -213,7 +230,9 @@ export function useMidenWalletAdapter( select(target.adapter.name); await target.adapter.connect( PrivateDataPermission.UponRequest, - WalletAdapterNetwork.Testnet, + network === "testnet" + ? MIDEN_TESTNET_WALLET_NETWORK + : MIDEN_MAINNET_WALLET_NETWORK, AllowedPrivateData.Assets, ); return; @@ -223,11 +242,13 @@ export function useMidenWalletAdapter( wallet.readyState !== WalletReadyState.Installed && wallet.readyState !== WalletReadyState.Loadable ) { - throw new Error("Miden wallet is initializing. Wait a moment and try again."); + throw new Error( + "Miden wallet is initializing. Wait a moment and try again.", + ); } await adapterConnect(); - }, [adapterConnect, connected, connecting, select, wallet, wallets]); + }, [adapterConnect, connected, connecting, network, select, wallet, wallets]); return { connected, diff --git a/demo/src/miden/lib/explorers.ts b/demo/src/miden/lib/explorers.ts index 17a9783..97f4caf 100644 --- a/demo/src/miden/lib/explorers.ts +++ b/demo/src/miden/lib/explorers.ts @@ -1,26 +1,26 @@ +import { MIDEN_MAINNET } from "../../config/miden-mainnet"; // Centralized explorer URL helpers. SIO surfaces a synthetic Miden settlement // row using `chainId === MIDEN_CHAIN_ID` (999_999_999); everything else is an // EVM chain mapped here. -export const MIDEN_CHAIN_ID = 999_999_999; +export const MIDEN_CHAIN_ID = MIDEN_MAINNET.chainId; -export const MIDENSCAN_BASE = 'https://testnet.midenscan.com'; +export const MIDENSCAN_BASE = MIDEN_MAINNET.explorer; const EVM_EXPLORERS: Record = { - 1: 'https://etherscan.io', - 10: 'https://optimistic.etherscan.io', - 137: 'https://polygonscan.com', - 8453: 'https://basescan.org', - 42161: 'https://arbiscan.io', - 11155111: 'https://sepolia.etherscan.io', - 11155420: 'https://sepolia-optimism.etherscan.io', - 84532: 'https://sepolia.basescan.org', + 1: "https://etherscan.io", + 10: "https://optimistic.etherscan.io", + 137: "https://polygonscan.com", + 8453: "https://basescan.org", + 4663: "https://robinhoodchain.blockscout.com", + 46630: "https://explorer.testnet.chain.robinhood.com", + 42161: "https://arbiscan.io", + 11155111: "https://sepolia.etherscan.io", + 11155420: "https://sepolia-optimism.etherscan.io", + 84532: "https://sepolia.basescan.org", }; -export const explorerTxUrl = ( - chainId: number, - hash: string, -): string | null => { +export const explorerTxUrl = (chainId: number, hash: string): string | null => { if (chainId === MIDEN_CHAIN_ID) return `${MIDENSCAN_BASE}/tx/${hash}`; const base = EVM_EXPLORERS[chainId]; return base ? `${base}/tx/${hash}` : null; @@ -34,7 +34,7 @@ export const truncateHash = ( head = 10, tail = 8, ): string => { - if (!hash) return '—'; + if (!hash) return "—"; if (hash.length <= head + tail + 1) return hash; return `${hash.slice(0, head)}…${hash.slice(-tail)}`; }; diff --git a/demo/src/miden/lib/mainnet-sdk-compat.ts b/demo/src/miden/lib/mainnet-sdk-compat.ts new file mode 100644 index 0000000..7e04079 --- /dev/null +++ b/demo/src/miden/lib/mainnet-sdk-compat.ts @@ -0,0 +1,19 @@ +export interface MainnetOracleGraph { + oracles?: Record; +} + +export const DEFAULT_MIDEN_MAINNET_RPC_URL = "https://rpc.cedar.miden.io"; + +/** + * commons-sdk 2.0.0's published mainnet graph omits the oracle entry that the + * pinned flows SDK reads at module initialization. Populate that missing + * compatibility field before importing the flows SDK. + */ +export function ensurePragmaMidenMainnetOracle( + graph: MainnetOracleGraph, + rpcUrl: string, +): { oracles: Record } { + graph.oracles ??= {}; + graph.oracles.PragmaMidenV1 ??= { rpcUrl }; + return { oracles: graph.oracles }; +} diff --git a/demo/src/miden/lib/mainnet-wallet-compat.ts b/demo/src/miden/lib/mainnet-wallet-compat.ts new file mode 100644 index 0000000..003279e --- /dev/null +++ b/demo/src/miden/lib/mainnet-wallet-compat.ts @@ -0,0 +1,30 @@ +import type { WalletAdapterNetwork } from "@miden-sdk/miden-wallet-adapter-base"; + +/** + * Bread already accepts the mainnet wire value, while the 0.17.5 adapter enum + * still declares only devnet/testnet/localnet. Keep the unavoidable cast at + * this single compatibility boundary so it can be removed when the enum adds + * Mainnet. Never substitute Testnet here: that silently connects the demo to + * the wrong network. + */ +export const MIDEN_MAINNET_WALLET_NETWORK = "mainnet" as WalletAdapterNetwork; +export const MIDEN_TESTNET_WALLET_NETWORK = "testnet" as WalletAdapterNetwork; + +interface MidenAccountId { + isPublic(): boolean; + toString(): string; +} + +/** Reject private accounts before a quote can be requested. */ +export function normalizeMidenAccount( + accountId: MidenAccountId, +): { hex: string; isPublic: boolean } { + return { hex: accountId.toString(), isPublic: accountId.isPublic() }; +} + +export function requirePublicMidenAccount(accountId: MidenAccountId): string { + if (!accountId.isPublic()) { + throw new Error("A public Miden account is required for this bridge"); + } + return normalizeMidenAccount(accountId).hex; +} diff --git a/demo/src/miden/services/epoch-bridge.ts b/demo/src/miden/services/epoch-bridge.ts index 7e7a942..cf7156b 100644 --- a/demo/src/miden/services/epoch-bridge.ts +++ b/demo/src/miden/services/epoch-bridge.ts @@ -192,7 +192,7 @@ export async function buildCrossChainIntent( params: CrossChainIntentParams & { collateralType?: CollateralType; midenSourceAccount?: string; - createMidenP2IDNote?: SolveIntentParams["createMidenP2IDNote"]; + createMidenP2IDENote?: SolveIntentParams["createMidenP2IDENote"]; /** Pre-fetched quote from getCrossChainQuote — skips getTaskData step. */ preFetchedQuote?: CrossChainQuote; }, @@ -224,7 +224,7 @@ export async function buildCrossChainIntent( collateralType: (params.collateralType ?? "miden") as CollateralType, midenFaucetId: midenFaucetIdHex, midenSourceAccount: midenSourceHex, - createMidenP2IDNote: params.createMidenP2IDNote, + createMidenP2IDENote: params.createMidenP2IDENote, }); console.log("[EpochBridge] SDK.solveIntent() response:", solveResult); diff --git a/demo/src/pay/scenarios.ts b/demo/src/pay/scenarios.ts index e7afc51..e3ca911 100644 --- a/demo/src/pay/scenarios.ts +++ b/demo/src/pay/scenarios.ts @@ -1,8 +1,4 @@ import type { EpochIntentWidgetProps } from "@epoch-protocol/epoch-intent-widget"; -import { - DEFAULT_MIDEN_FAUCET, - MIDEN_VIRTUAL_CHAIN_ID, -} from "@epoch-protocol/epoch-intent-widget"; export type ScenarioProps = Omit< EpochIntentWidgetProps, @@ -66,8 +62,7 @@ export const PAY_SCENARIOS: Scenario[] = [ ]; // Base Sepolia USDC — public Circle test faucet token. -const BASE_SEPOLIA_USDC = - "0x036CbD53842c5426634e7929541eC2318f3dCF7e" as const; +const BASE_SEPOLIA_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e" as const; export const PAY_TESTNET_SCENARIOS: Scenario[] = [ { @@ -163,8 +158,7 @@ export const SWAP_SCENARIOS: Scenario[] = [ }, ]; -const OP_SEPOLIA_USDC = - "0x2BB4FfD7E2c6D432b697554Efd77fA13bdbefd69" as const; +const OP_SEPOLIA_USDC = "0x2BB4FfD7E2c6D432b697554Efd77fA13bdbefd69" as const; const SWAP_TESTNET_INITIAL_INTENT = { requiredToken: { @@ -229,53 +223,4 @@ export const SWAP_TESTNET_SCENARIOS: Scenario[] = [ }, }, }, - { - id: "swap-miden-to-evm", - name: "Swap (Miden → Base Sepolia)", - tagline: - "Source funds on Miden — the wallet mints a P2ID note the allocator claims — and receive test USDC on Base Sepolia. Opens with Miden preselected; connect a Miden wallet to sign.", - props: { - mode: "swap", - network: "testnet", - allowNetworkToggle: true, - title: "Swap from Miden", - ctaLabels: SHARED_CTA_LABELS, - usdPriceFor: SHARED_USD_ORACLE, - intent: SWAP_TESTNET_INITIAL_INTENT, - defaultSourceChainId: MIDEN_VIRTUAL_CHAIN_ID, - defaultSourceTokenAddress: DEFAULT_MIDEN_FAUCET.faucetId, - }, - }, - { - id: "swap-evm-to-miden", - name: "Swap (Base Sepolia → Miden)", - tagline: - "Pay with test USDC on an EVM chain, receive USDC on Miden. The EVM wallet signs; the recipient is your connected Miden account.", - props: { - mode: "swap", - network: "testnet", - allowNetworkToggle: true, - title: "Swap to Miden", - ctaLabels: SHARED_CTA_LABELS, - usdPriceFor: SHARED_USD_ORACLE, - intent: { - requiredToken: { - address: DEFAULT_MIDEN_FAUCET.faucetId, - symbol: DEFAULT_MIDEN_FAUCET.symbol, - decimals: DEFAULT_MIDEN_FAUCET.decimals, - }, - requiredAmount: BigInt(1_000_000), // 1 USDC (Miden faucet, 6 decimals) - destinationChainName: "Miden", - positionLabel: "1 USDC on Miden", - config: { - protocol: "swap", - action: "swap", - fixedOutput: true, - destinationTestnetChainId: MIDEN_VIRTUAL_CHAIN_ID, - }, - }, - defaultSourceChainId: 84532, - defaultSourceTokenAddress: BASE_SEPOLIA_USDC, - }, - }, ]; diff --git a/demo/src/surfaces/EarnSurface.tsx b/demo/src/surfaces/EarnSurface.tsx index aa9beb8..529d2a6 100644 --- a/demo/src/surfaces/EarnSurface.tsx +++ b/demo/src/surfaces/EarnSurface.tsx @@ -120,8 +120,8 @@ export function EarnSurface({ onOpenWidget }: Props) { Show a list of lending and yield markets right inside your app. Users deposit with any token they hold; withdrawals come back to the same wallet. Use the Mainnet / Testnet toggle in the modal header to try dummy-lending on Base Sepolia and Ethereum Sepolia (fund from - Optimism Sepolia, Ethereum Sepolia, Base Sepolia, or Miden on testnet), with - optional Miden as a deposit source on testnet. + Optimism Sepolia, Ethereum Sepolia, or Base Sepolia), with + Miden USDCX as a deposit source on mainnet.

@@ -157,8 +157,8 @@ export function EarnSurface({ onOpenWidget }: Props) {
Deposit

- Pick a lending market and deposit from an EVM wallet or Miden (testnet). Toggle{' '} - Testnet in the modal, then use the EVM / Miden source switch on the + Pick a lending market and deposit from an EVM wallet or Miden USDCX on mainnet. Keep{' '} + Mainnet selected, then use the EVM / Miden source switch on the deposit form.

+
+ )} void; label?: string; + error?: string | null; }) { return ( +
+ {error && ( +
+ {error} +
+ )} +
); } diff --git a/src/earn/dummy-lending-markets.ts b/src/earn/dummy-lending-markets.ts index 184c2e2..bd74aa8 100644 --- a/src/earn/dummy-lending-markets.ts +++ b/src/earn/dummy-lending-markets.ts @@ -13,6 +13,7 @@ export const DUMMY_LENDING_SOURCE_EVM_CHAIN_IDS = [ 84532, // Base Sepolia 11155111, // Ethereum Sepolia 11155420, // Optimism Sepolia — fund only; markets are on other testnets + 46630, // Robinhood Testnet — fund only ] as const; /** Chains where dummy-lending earn markets can be selected (deposit destination). */ diff --git a/src/earn/earn-cta.ts b/src/earn/earn-cta.ts index 51b7636..2d52338 100644 --- a/src/earn/earn-cta.ts +++ b/src/earn/earn-cta.ts @@ -25,6 +25,8 @@ export interface ResolveEarnCtaParams { }; isConnected: boolean; midenConnected: boolean; + /** Miden account + faucet metadata required to build a Miden-funded quote. */ + midenSourceReady: boolean; hasSelectedMarket: boolean; depositAmount: string; hasSelectedPosition: boolean; @@ -62,6 +64,7 @@ export function resolveEarnCta({ flow, isConnected, midenConnected, + midenSourceReady, hasSelectedMarket, depositAmount, hasSelectedPosition, @@ -93,6 +96,10 @@ export function resolveEarnCta({ return { action: 'connectMiden', label: 'Connect Miden wallet' }; } + if (earnTab === 'deposit' && fundingSource === 'miden' && !midenSourceReady) { + return { action: 'disabled', label: 'Preparing Miden account…' }; + } + if (earnTab === 'deposit' && !hasSelectedMarket) { return { action: 'disabled', label: 'Select market' }; } diff --git a/src/earn/earn-props.ts b/src/earn/earn-props.ts index af51edd..297d53b 100644 --- a/src/earn/earn-props.ts +++ b/src/earn/earn-props.ts @@ -42,7 +42,7 @@ export interface EarnIntentWidgetProps { earnWithdrawDefaults?: EarnWithdrawIntentDefaults; /** Override the 1delta-solver base URL (`POST /earn/quote`). Defaults to `api.baseUrl`. */ earnSolverUrl?: string; - /** Optional Miden wallet adapter for testnet earn deposits funded from Miden. */ + /** Optional Miden wallet adapter for earn deposits funded from Miden. */ earnMiden?: EarnMidenAdapter; /** * Chain IDs to fan /pools fetches over. Forwarded as one `chainId=` per diff --git a/src/earn/miden.ts b/src/earn/miden.ts index 5337c66..ed0052b 100644 --- a/src/earn/miden.ts +++ b/src/earn/miden.ts @@ -1,14 +1,20 @@ -import { mainnetGraph, testnetGraph } from "@epoch-protocol/epoch-commons-sdk"; +import { + mainnetGraph, + normalizeMidenId, + testnetGraph, +} from "@epoch-protocol/epoch-commons-sdk"; import { EVM_ZERO_ADDRESS, MIDEN_TO_EVM_EXTRA_TYPESTRING, MIDEN_VIRTUAL_CHAIN_ID, } from "@epoch-protocol/epoch-intents-sdk"; +import { EPOCH_MIDEN_MAINNET_TOKENS } from "@epoch-protocol/epoch-flows-sdk"; import type { EpochChain, EpochToken } from "../types"; // Re-exported (not re-declared) so the widget's public surface keeps these names // while the SDK stays the single source of truth — the chain id and the sentinel // are the same values the SDK branches its EVM→Miden intent build on. +export { normalizeMidenId }; export { EVM_ZERO_ADDRESS, MIDEN_VIRTUAL_CHAIN_ID }; /** @@ -49,6 +55,13 @@ export interface MidenGraphToken { decimals: number; } +// Keep older epoch-commons-sdk versions accurate until their bundled graph has +// the chain-specific Miden decimals. The WETH faucet on Cedar mainnet has 8 +// decimals; EVM WETH continues to use the token's default 18 decimals. +const MIDEN_MAINNET_DECIMALS_FALLBACKS: Record = { + WETH: 8, +}; + /** * Miden tokens declared in the Epoch graph — every token that carries a * `contractAddress.Miden` faucet id (USDC/DAI/USDT/WETH/WBTC on testnet). This is @@ -74,9 +87,21 @@ export function getMidenGraphTokens(isTestnet: boolean): MidenGraphToken[] { out.push({ symbol, faucetId, - decimals: def?.decimalsByChain?.Miden ?? def?.decimals ?? 6, + decimals: + def?.decimalsByChain?.Miden ?? + (!isTestnet ? MIDEN_MAINNET_DECIMALS_FALLBACKS[symbol] : undefined) ?? + def?.decimals ?? + 6, }); } + // Commons releases can lag newly supported faucets. Include the canonical + // Flows registry without duplicating graph entries in another encoding. + if (!isTestnet) { + for (const token of EPOCH_MIDEN_MAINNET_TOKENS) { + if (out.some((entry) => midenFaucetKey(entry.faucetId) === midenFaucetKey(token.address))) continue; + out.push({ symbol: token.symbol, faucetId: token.address, decimals: token.decimals }); + } + } return out; } @@ -104,88 +129,3 @@ export function getMidenChainTokens( chain: MIDEN_CHAIN, })); } - -const BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; -const BECH32_CHECKSUM = 1; -const BECH32M_CHECKSUM = 0x2bc830a3; -/** A Miden account id is 15 bytes; bech32 prefixes it with one address-type byte. */ -const MIDEN_ACCOUNT_ID_BYTES = 15; - -function bech32Polymod(values: number[]): number { - const generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; - let chk = 1; - for (const value of values) { - const top = chk >>> 25; - chk = ((chk & 0x1ffffff) << 5) ^ value; - for (let i = 0; i < 5; i += 1) { - if ((top >>> i) & 1) chk ^= generator[i]; - } - } - return chk >>> 0; -} - -function bech32HrpExpand(hrp: string): number[] { - const out: number[] = []; - for (let i = 0; i < hrp.length; i += 1) out.push(hrp.charCodeAt(i) >> 5); - out.push(0); - for (let i = 0; i < hrp.length; i += 1) out.push(hrp.charCodeAt(i) & 31); - return out; -} - -/** - * Decode a Miden bech32 address/account id to `0x`-prefixed hex, or null when the - * input isn't a checksum-valid bech32(m) string. - * - * Hand-rolled rather than delegating to `@miden-sdk/miden-sdk`: that decoder is - * WASM, and the widget must stay a dependency-light React package. The checksum - * is verified so a non-bech32 string can never be silently mangled into a hex id - * that then travels into intent extraData. - */ -function decodeMidenBech32(input: string): string | null { - // `AccountId.toBech32` appends an `_` tag; the address itself is the - // part before it (`mtst1ar7f…_qr7qqq9wr6w`). - const raw = input.split("_")[0].toLowerCase(); - const sep = raw.lastIndexOf("1"); - if (sep < 1 || sep + 7 > raw.length) return null; - - const words: number[] = []; - for (const ch of raw.slice(sep + 1)) { - const value = BECH32_CHARSET.indexOf(ch); - if (value < 0) return null; - words.push(value); - } - - const checksum = bech32Polymod([...bech32HrpExpand(raw.slice(0, sep)), ...words]); - if (checksum !== BECH32_CHECKSUM && checksum !== BECH32M_CHECKSUM) return null; - - let acc = 0; - let bits = 0; - const bytes: number[] = []; - for (const word of words.slice(0, -6)) { - acc = (acc << 5) | word; - bits += 5; - while (bits >= 8) { - bits -= 8; - bytes.push((acc >> bits) & 0xff); - } - } - if (bytes.length < MIDEN_ACCOUNT_ID_BYTES + 1) return null; - - return `0x${bytes - .slice(1, 1 + MIDEN_ACCOUNT_ID_BYTES) - .map((b) => b.toString(16).padStart(2, "0")) - .join("")}`; -} - -/** - * Normalize a Miden account/faucet id to hex. Hex passes through; bech32 — which - * is what the wallet adapter hands back for `requestAssets()` faucet ids — is - * decoded, so wallet-reported ids compare equal to the graph's hex ones. - */ -export function normalizeMidenId(id: string): string { - const raw = (id ?? "").trim(); - if (!raw) return raw; - if (raw.startsWith("0x") || raw.startsWith("0X")) return raw; - if (/^[0-9a-fA-F]+$/.test(raw) && raw.length % 2 === 0) return `0x${raw}`; - return decodeMidenBech32(raw) ?? raw; -} diff --git a/src/earn/use-earn-engine.ts b/src/earn/use-earn-engine.ts index d3c21fe..07964fb 100644 --- a/src/earn/use-earn-engine.ts +++ b/src/earn/use-earn-engine.ts @@ -1,6 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useAccount, useChainId, useSwitchChain, useWalletClient } from "wagmi"; import { getEpochChains, getEpochTokensByChainEnv } from "../epoch-config"; +import { NATIVE_ETH_ADDRESS } from "@epoch-protocol/epoch-flows-sdk"; import { useTokenBalance } from "../use-token-balance"; import { exceedsBalance, positionWithdrawableRaw } from "./balance"; import { useSessionId } from "../session"; @@ -162,8 +163,8 @@ export function useEarnEngine(props: EarnIntentWidgetProps) { smartDestChainId, smartDestTokenAddress, } = selection; - // Miden funding only exists on testnet, so it can't survive a flip to mainnet. - const fundingSource = isTestnet ? selection.fundingSource : "evm"; + // Miden funding is available on either network when the host supplies an enabled adapter. + const fundingSource = selection.fundingSource; const setEarnSelectedMarket = useCallback( (market: EpochEarnMarket | null) => patchSelection({ market }), @@ -212,7 +213,6 @@ export function useEarnEngine(props: EarnIntentWidgetProps) { const [gasless, setGasless] = useState(gaslessProp); const networkEnv: "mainnet" | "testnet" = isTestnet ? "testnet" : "mainnet"; const midenEnabled = - networkEnv === "testnet" && earnMiden != null && earnMiden.enabled !== false; const resolvedApi = useMemo( @@ -230,6 +230,7 @@ export function useEarnEngine(props: EarnIntentWidgetProps) { const allTokens = useMemo(() => { const allowed = new Set(DUMMY_LENDING_SUPPORTED_ADDRESSES); + allowed.add(NATIVE_ETH_ADDRESS); const deprecated = DEPRECATED_DUMMY_LENDING_USDC_ADDRESS.toLowerCase(); return availableChains.flatMap((chain) => getEpochTokensByChainEnv(chain.id, isTestnet).flatMap((tok) => { @@ -363,6 +364,7 @@ export function useEarnEngine(props: EarnIntentWidgetProps) { effectiveAllowGasless && (earnTab === "withdraw" || fundingSource === "evm"), apiBaseUrl: resolvedApi.baseUrl, + rpcUrls: resolvedApi.rpcUrls, gasless, setGasless, walletClient, @@ -617,6 +619,7 @@ export function useEarnEngine(props: EarnIntentWidgetProps) { }, isConnected, midenConnected: !!earnMiden?.connected, + midenSourceReady: !!miden.quoteSource, hasSelectedMarket: !!earnSelectedMarket, depositAmount: earnAmount, hasSelectedPosition: !!selectedPosition, @@ -668,6 +671,7 @@ export function useEarnEngine(props: EarnIntentWidgetProps) { return; } if (ctaState.action !== "submit") return; + if (fundingSource === "miden" && !miden.quoteSource) return; if ( effectiveSourceChainId == null || !effectiveSourceToken || diff --git a/src/earn/use-earn-intent-flow.ts b/src/earn/use-earn-intent-flow.ts index 8382339..ad12e3e 100644 --- a/src/earn/use-earn-intent-flow.ts +++ b/src/earn/use-earn-intent-flow.ts @@ -13,6 +13,7 @@ import { ZERO_BYTES32, isUserWalletRejection, } from '@epoch-protocol/epoch-intents-sdk'; +import { isNativeEthAddress } from '@epoch-protocol/epoch-flows-sdk'; import type { RoutingAndLiquidityOptions } from '../types'; import type { EarnMidenCreateP2IDNote, @@ -221,8 +222,9 @@ function smartWithdrawDestAsset(input: EarnQuoteInput): string { /** * Compact quote/submit uses `walletClient.chain.id` as the intent origin chain. - * Miden-funded earn deposits must override this to the virtual Miden chain id even - * when the connected EVM wallet is on Sepolia (same pattern as demo Miden bridge). + * Quotes must use the position's chain for withdrawals, and the virtual Miden + * chain for Miden-funded deposits, regardless of the connected wallet network. + * Withdrawal submission separately requires the wallet on the position's chain. */ function createEarnIntentSdk( apiBaseUrl: string, @@ -292,7 +294,7 @@ export function useEarnIntentFlow({ taskTypeString: string; intentData: any; quoteResult: any; - /** Origin chain forwarded to Compact/SIO (Miden virtual id for P2ID deposits). */ + /** Quote origin: position chain for withdrawals, virtual chain for Miden deposits. */ originChainId?: number; } | null>(null); @@ -450,6 +452,10 @@ export function useEarnIntentFlow({ extraData, isSameChain, isMidenDeposit, + isNativeSource: + !isWithdraw && + !isMidenDeposit && + isNativeEthAddress(tokenInAddress), midenSource: input.midenSource, }; }, @@ -494,7 +500,13 @@ export function useEarnIntentFlow({ setQuoteError(null); pendingQuoteRef.current = null; try { - const sdk = createEarnIntentSdk(apiBaseUrl, walletClient); + // The underlying belongs to the position's chain. Using the connected + // wallet chain here can quote Ethereum USDC against an Arbitrum RPC. + const sdk = createEarnIntentSdk( + apiBaseUrl, + walletClient, + market.chainId ?? input.sourceChainId, + ); const { taskTypeString, intentData } = await sdk.getTaskData( buildSwapLegTaskInput(input, { underlyingAddress, @@ -553,7 +565,10 @@ export function useEarnIntentFlow({ pendingQuoteRef.current = null; try { - const originChainId = params.isMidenDeposit ? input.sourceChainId : undefined; + const originChainId = + input.tab === 'withdraw' + ? ((input.market ?? input.position?.market)?.chainId ?? input.sourceChainId) + : params.isMidenDeposit ? input.sourceChainId : undefined; const sdk = createEarnIntentSdk(apiBaseUrl, walletClient, originChainId); const { taskTypeString, intentData } = await sdk.getTaskData({ @@ -576,7 +591,7 @@ export function useEarnIntentFlow({ sponsorAddress: address as `0x${string}`, taskTypeString, intentData, - isNative: false, + isNative: params.isNativeSource, ...(routingAndLiquidityOptions ? { routingAndLiquidityOptions } : {}), @@ -718,6 +733,7 @@ export function useEarnIntentFlow({ setStatus('error'); return; } + const market = input.market ?? input.position?.market; if (!market) { setError('Market missing'); @@ -852,6 +868,20 @@ export function useEarnIntentFlow({ return; } + // Previewing another chain is safe; executing must use the real wallet + // network. Do not let the quote's chain override hide a stale wallet client. + const withdrawChainId = + (input.market ?? input.position?.market)?.chainId ?? input.sourceChainId; + if (input.tab === 'withdraw' && walletClient.chain?.id !== withdrawChainId) { + const error = new Error( + `Switch your wallet to chain ${withdrawChainId} before withdrawing`, + ); + setError(error.message); + setStatus('error'); + onErrorRef.current?.({ sessionId, error }); + return; + } + // Smart Withdraw takes the dedicated batch path (withdraw → swap). if (isSmartWithdrawInput(input)) { swLog('submit: routing → submitSmartWithdraw (smart path)'); @@ -921,7 +951,7 @@ export function useEarnIntentFlow({ onSignRef.current?.({ sessionId }); const solvePayload: Record = { - isNative: false, + isNative: submitParams.isNativeSource, sponsorAddress: address as `0x${string}`, taskTypeString, intentData, @@ -935,7 +965,7 @@ export function useEarnIntentFlow({ solvePayload.collateralType = CollateralType.Miden; solvePayload.midenFaucetId = normalizeMidenId(input.midenSource.faucetId); solvePayload.midenSourceAccount = normalizeMidenId(input.midenSource.accountId); - solvePayload.createMidenP2IDNote = input.midenSource.createP2IDNote; + solvePayload.createMidenP2IDENote = input.midenSource.createP2IDNote; } if (gaslessRef.current && !submitParams.isMidenDeposit) { diff --git a/src/earn/use-earn-miden.ts b/src/earn/use-earn-miden.ts index 79ccd67..d42e38a 100644 --- a/src/earn/use-earn-miden.ts +++ b/src/earn/use-earn-miden.ts @@ -171,6 +171,7 @@ export function useEarnMiden({ [ fundingSource, earnMiden?.accountId, + earnMiden?.accountIsPublic, earnMiden?.createP2IDNote, selectedAsset, ], @@ -222,6 +223,7 @@ export function useEarnMiden({ smartDestChainId, smartDestTokenAddress, earnMiden?.accountId, + earnMiden?.accountIsPublic, graphTokens, ]); diff --git a/src/epoch-config.ts b/src/epoch-config.ts index 2551d6c..94f9b26 100644 --- a/src/epoch-config.ts +++ b/src/epoch-config.ts @@ -3,6 +3,8 @@ export { EPOCH_TESTNET_CHAINS, EPOCH_SUPPORTED_TOKENS, EPOCH_TESTNET_TOKENS, + NATIVE_ETH_ADDRESS, + isNativeEthAddress, getEpochChains, getEpochTokensByChainEnv, getEpochTokensBySymbol, diff --git a/src/hooks/use-gasless-wallet-check.ts b/src/hooks/use-gasless-wallet-check.ts index c2d651d..38d0f2a 100644 --- a/src/hooks/use-gasless-wallet-check.ts +++ b/src/hooks/use-gasless-wallet-check.ts @@ -12,6 +12,7 @@ import { getEpochChainById } from "../epoch-config"; interface UseGaslessWalletParams { allowGasless: boolean; apiBaseUrl: string; + rpcUrls?: Record; gasless: boolean; setGasless: (next: boolean) => void; walletClient?: WalletClient; @@ -42,6 +43,7 @@ export type UseGaslessWalletResult = { export function useGaslessWallet({ allowGasless, apiBaseUrl, + rpcUrls, gasless, setGasless, walletClient, @@ -81,12 +83,15 @@ export function useGaslessWallet({ try { const epochChain = getEpochChainById(chainIdForCheck); const rpcUrl = + rpcUrls?.[chainIdForCheck] ?? + (walletClient.chain?.id === chainIdForCheck + ? walletClient.chain.rpcUrls?.default?.http?.[0] + : undefined) ?? epochChain?.rpcUrl ?? - walletClient.chain?.rpcUrls?.default?.http?.[0] ?? ""; const publicClient = createPublicClient({ - chain: walletClient.chain ?? undefined, + chain: walletClient.chain?.id === chainIdForCheck ? walletClient.chain : undefined, transport: http(rpcUrl), }); @@ -122,7 +127,7 @@ export function useGaslessWallet({ } finally { setChecking(false); } - }, [allowGasless, walletClient, address, chainIdForCheck]); + }, [allowGasless, apiBaseUrl, walletClient, address, chainIdForCheck, rpcUrls]); useEffect(() => { void probe(); diff --git a/src/index.ts b/src/index.ts index da13103..54c6dda 100644 --- a/src/index.ts +++ b/src/index.ts @@ -45,7 +45,7 @@ export type { } from './types'; export { DEFAULT_THEME, LIGHT_THEME, DARK_THEME, resolveTheme, themeToCssVars } from './theme'; export { cn } from './lib/cn'; -export { MIDEN_VIRTUAL_CHAIN_ID, DEFAULT_MIDEN_FAUCET, midenFaucetKey, isDefaultMidenFaucet, getMidenGraphTokens } from './earn/miden'; +export { MIDEN_VIRTUAL_CHAIN_ID, DEFAULT_MIDEN_FAUCET, midenFaucetKey, normalizeMidenId, isDefaultMidenFaucet, getMidenGraphTokens } from './earn/miden'; export type { MidenGraphToken } from './earn/miden'; export { useEarnMarkets, useUserPositions, useEarnConfigs, useLendingPools, DEFAULT_EARN_CONFIGS } from './earn/api'; export { HARDCODED_ONEDELTA_CONFIGS, chainLabelFor } from './earn/onedelta-markets'; diff --git a/src/pay/use-pay-swap-engine.ts b/src/pay/use-pay-swap-engine.ts index 2e2322d..9b0902b 100644 --- a/src/pay/use-pay-swap-engine.ts +++ b/src/pay/use-pay-swap-engine.ts @@ -37,6 +37,17 @@ const PLACEHOLDER_INTENT: IntentProps = { config: { protocol: 'transfer', action: 'pay', fixedOutput: false }, }; +function rescaleAmount( + amount: bigint, + fromDecimals: number, + toDecimals: number, +): bigint { + if (fromDecimals === toDecimals) return amount; + const decimalShift = BigInt(Math.abs(toDecimals - fromDecimals)); + const scale = 10n ** decimalShift; + return fromDecimals < toDecimals ? amount * scale : amount / scale; +} + export interface PaySwapEngine { spec: PaySwapVariantSpec; source: SourceSelection; @@ -207,6 +218,16 @@ export function usePaySwapEngine(props: PaySwapIntentWidgetProps): PaySwapEngine locked: lockDestinationToken, }); + // For fixed-output swaps, `requiredAmount` belongs to the destination token. + // Fixed-input swaps use it as the source amount, so preserve its precision. + const requiredAmountForDestination = intentConfig.fixedOutput + ? rescaleAmount( + requiredAmount, + requiredToken.decimals, + destination.requiredToken.decimals, + ) + : requiredAmount; + const { isMidenSource, isMidenDest, @@ -238,6 +259,7 @@ export function usePaySwapEngine(props: PaySwapIntentWidgetProps): PaySwapEngine const gaslessWallet = useGaslessWallet({ allowGasless: effectiveAllowGasless, apiBaseUrl, + rpcUrls, gasless, setGasless, walletClient, @@ -271,9 +293,10 @@ export function usePaySwapEngine(props: PaySwapIntentWidgetProps): PaySwapEngine walletClient, address, requiredToken: destination.requiredToken, - requiredAmount, + requiredAmount: requiredAmountForDestination, intentConfig: destination.intentConfig, isTestnet, + originChainId: isMidenSource ? MIDEN_VIRTUAL_CHAIN_ID : undefined, sessionId, mode: variant, receiver, diff --git a/src/pay/use-pay-swap-miden.ts b/src/pay/use-pay-swap-miden.ts index 4a1857e..ebe5b0f 100644 --- a/src/pay/use-pay-swap-miden.ts +++ b/src/pay/use-pay-swap-miden.ts @@ -1,15 +1,19 @@ -import { useMemo } from 'react'; -import type { EarnMidenAdapter } from '../types'; -import { MIDEN_VIRTUAL_CHAIN_ID, midenFaucetKey } from '../earn/miden'; -import type { SourceSelection } from './use-source-selection'; -import type { DestinationSelection } from './use-destination-selection'; +import { useMemo } from "react"; +import type { EarnMidenAdapter } from "../types"; +import { + MIDEN_VIRTUAL_CHAIN_ID, + midenFaucetKey, + normalizeMidenId, +} from "../earn/miden"; +import type { SourceSelection } from "./use-source-selection"; +import type { DestinationSelection } from "./use-destination-selection"; /** Miden→EVM funding payload — the source is a Miden P2ID note. */ export interface PaySwapMidenSource { accountId: string; faucetId: string; decimals: number; - createP2IDNote: EarnMidenAdapter['createP2IDNote']; + createP2IDNote: EarnMidenAdapter["createP2IDNote"]; } /** EVM→Miden delivery payload — the output lands on a Miden account. */ @@ -61,8 +65,8 @@ export function usePaySwapMiden({ return undefined; } return { - accountId, - faucetId: source.token.address, + accountId: normalizeMidenId(accountId), + faucetId: normalizeMidenId(source.token.address), decimals: source.token.decimals, createP2IDNote: miden!.createP2IDNote, }; @@ -71,8 +75,8 @@ export function usePaySwapMiden({ const midenDest = useMemo(() => { if (!isMidenDest || !midenConnected || !accountId) return undefined; return { - recipientAccount: accountId, - faucetId: destination.tokenAddress, + recipientAccount: normalizeMidenId(accountId), + faucetId: normalizeMidenId(destination.tokenAddress), decimals: destination.requiredToken.decimals, }; }, [ @@ -86,10 +90,13 @@ export function usePaySwapMiden({ const midenBalance = useMemo(() => { if (!isMidenSource) return null; const key = midenFaucetKey(source.tokenAddress); - const match = (miden?.assets ?? []).find( - (a) => midenFaucetKey(a.faucetId) === key, + const matches = (miden?.assets ?? []).filter( + (asset) => midenFaucetKey(asset.faucetId) === key, ); - return match?.balance ?? null; + if (matches.length === 0) return null; + // Wallet adapters may return several fungible entries for one faucet; + // sum them instead of showing only whichever matching row comes first. + return matches.reduce((total, asset) => total + (asset.balance ?? 0n), 0n); }, [isMidenSource, miden?.assets, source.tokenAddress]); return { diff --git a/src/types.ts b/src/types.ts index 198268a..2633668 100644 --- a/src/types.ts +++ b/src/types.ts @@ -133,7 +133,7 @@ export interface OnStatusCtx extends SessionCtx { } // --------------------------------------------------------------------------- -// Earn — Miden funding (optional, testnet) +// Earn — Miden funding (optional) // --------------------------------------------------------------------------- /** Miden faucet asset surfaced in the earn deposit source picker. */ @@ -190,6 +190,8 @@ export interface EarnMidenAdapter { enabled?: boolean; connected: boolean; accountId?: string | null; + /** Whether the connected account uses public storage. Unknown adapters may omit it. */ + accountIsPublic?: boolean | null; assets: EarnMidenAsset[]; connect?: () => void | Promise; createP2IDNote: EarnMidenCreateP2IDNote; @@ -317,15 +319,15 @@ export interface EpochIntentWidgetProps { earnPoolsSortDir?: 'ASC' | 'DESC'; /** @deprecated retained for backwards compatibility. */ earnUseMockData?: boolean; - /** Optional Miden wallet adapter for funding earn deposits from Miden (testnet). + /** Optional Miden wallet adapter for funding earn deposits from Miden on the active network. * Requires a connected EVM wallet as intent sponsor; Miden supplies collateral via P2IDE note. */ earnMiden?: EarnMidenAdapter; /** * Miden wallet adapter shared by every flow (earn AND pay/swap). Same shape as * {@link earnMiden}, which stays as a back-compat alias — the widget resolves - * `miden ?? earnMiden`. Testnet only: mainnet has no Miden faucets, so Miden - * never appears in the pickers there. + * `miden ?? earnMiden`. The active network graph determines which Miden faucets + * appear in the pickers. */ miden?: EarnMidenAdapter; diff --git a/src/use-intent-flow.ts b/src/use-intent-flow.ts index f429803..cc3cd49 100644 --- a/src/use-intent-flow.ts +++ b/src/use-intent-flow.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useLatestRef } from './hooks/use-latest-ref'; import { type Address, type WalletClient } from 'viem'; import { @@ -27,6 +27,8 @@ interface UseIntentFlowParams { requiredToken: { address: string; symbol: string; decimals: number }; requiredAmount: bigint; intentConfig: IntentConfig; + /** Override the Compact origin chain when funds originate from Miden. */ + originChainId?: number; isTestnet: boolean; sessionId: string; mode: WidgetFlow; @@ -71,6 +73,7 @@ export function useIntentFlow(params: UseIntentFlowParams): UseIntentFlowReturn requiredToken, requiredAmount, intentConfig, + originChainId, isTestnet, sessionId, mode, @@ -112,6 +115,24 @@ export function useIntentFlow(params: UseIntentFlowParams): UseIntentFlowReturn const gaslessRef = useLatestRef(gasless); const mountedRef = useRef(true); + // Compact's origin chain is read from walletClient.chain.id by the intents + // SDK. A Miden-funded intent still uses the connected EVM wallet to sign, but + // its Compact origin must be the Miden virtual chain rather than the EVM + // network that hosts the sponsor wallet. + const flowWalletClient = useMemo(() => { + if ( + !walletClient || + originChainId == null || + walletClient.chain?.id === originChainId + ) { + return walletClient; + } + return { + ...walletClient, + chain: { ...(walletClient.chain ?? {}), id: originChainId }, + } as WalletClient; + }, [walletClient, originChainId]); + useEffect(() => { mountedRef.current = true; return () => { @@ -120,7 +141,7 @@ export function useIntentFlow(params: UseIntentFlowParams): UseIntentFlowReturn }, []); useEffect(() => { - if (!walletClient || !address) { + if (!flowWalletClient || !address) { sessionRef.current?.dispose(); sessionRef.current = null; return; @@ -129,7 +150,7 @@ export function useIntentFlow(params: UseIntentFlowParams): UseIntentFlowReturn const session = new PaySession({ apiBaseUrl, address, - walletClient, + walletClient: flowWalletClient, sessionId, mode, requiredToken, @@ -180,11 +201,12 @@ export function useIntentFlow(params: UseIntentFlowParams): UseIntentFlowReturn }; }, [ apiBaseUrl, - walletClient, + flowWalletClient, address, sessionId, mode, isTestnet, + originChainId, receiver, routingAndLiquidityOptions, // Hot deps for the session config — recreating on intent shape changes is diff --git a/test/base-rpc.test.ts b/test/base-rpc.test.ts new file mode 100644 index 0000000..8ead4ec --- /dev/null +++ b/test/base-rpc.test.ts @@ -0,0 +1,21 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { getBaseRpcUrl } from "../demo/src/config/rpc"; + +test("uses the local Infura proxy when configured", () => { + assert.equal(getBaseRpcUrl("ankr-key", " /widget/rpc/base "), "/widget/rpc/base"); +}); + +test("uses the Ankr Base RPC with the provided key", () => { + assert.equal( + getBaseRpcUrl(" test-key "), + "https://rpc.ankr.com/base/test-key", + ); +}); + +test("uses public Base mainnet RPC when no usable key is configured", () => { + for (const key of [undefined, "", " "]) { + assert.equal(getBaseRpcUrl(key), "https://mainnet.base.org"); + } +}); diff --git a/test/earn-miden-mainnet.test.tsx b/test/earn-miden-mainnet.test.tsx new file mode 100644 index 0000000..52866dd --- /dev/null +++ b/test/earn-miden-mainnet.test.tsx @@ -0,0 +1,169 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { WagmiProvider, createConfig, http } from "wagmi"; +import { base } from "wagmi/chains"; + +import { useEarnEngine } from "../src/earn/use-earn-engine"; +import type { EarnMidenAdapter } from "../src/types"; +import { resolveEarnCta } from "../src/earn/earn-cta"; +import { useEarnMiden } from "../src/earn/use-earn-miden"; +import { DEFAULT_MIDEN_FAUCET, MIDEN_VIRTUAL_CHAIN_ID } from "../src/earn/miden"; + +const wagmiConfig = createConfig({ + chains: [base], + transports: { [base.id]: http() }, +}); + +const midenAdapter: EarnMidenAdapter = { + enabled: true, + connected: false, + assets: [], + createP2IDNote: async () => ({ success: false }), +}; + +function MainnetMidenProbe() { + const engine = useEarnEngine({ + isOpen: true, + onClose: () => undefined, + api: { baseUrl: "https://allocator.example.test" }, + network: "mainnet", + earnMiden: midenAdapter, + }); + + return createElement("output", null, String(engine.midenEnabled)); +} + +test("mainnet earn exposes Miden when an enabled adapter is supplied", () => { + const queryClient = new QueryClient(); + const markup = renderToStaticMarkup( + createElement( + WagmiProvider, + { config: wagmiConfig }, + createElement( + QueryClientProvider, + { client: queryClient }, + createElement(MainnetMidenProbe), + ), + ), + ); + + assert.equal(markup, "true"); +}); + +const midenCtaParams = { + earnTab: "deposit" as const, + fundingSource: "miden" as const, + flow: { isQuoting: false, status: "idle", quoteError: null }, + isConnected: true, + midenConnected: true, + midenSourceReady: false, + hasSelectedMarket: true, + depositAmount: "0.1", + hasSelectedPosition: false, + withdrawAmount: "", + availableChains: [], + selectedChain: null, + effectiveSourceChainId: 999999999, + effectiveSourceToken: { + address: "0x0000000000000000000000000000000000000000", + symbol: "USDCX", + name: "USDCX", + decimals: 6, + chainId: 999999999, + }, + isWrongNetwork: false, + insufficientBalance: false, + insufficientBalanceSymbol: "", + buildOk: true, + isSmartWithdrawDegenerate: false, + midenSmartDestNotReady: false, + isCrossChain: true, +}; + +test("Miden earn cannot submit before source metadata is ready", () => { + assert.deepEqual(resolveEarnCta(midenCtaParams), { + action: "disabled", + label: "Preparing Miden account…", + }); +}); + +test("Miden earn submits once source metadata is ready", () => { + assert.deepEqual( + resolveEarnCta({ ...midenCtaParams, midenSourceReady: true }), + { action: "submit", label: "Bridge from Miden + Deposit" }, + ); +}); + +function PrivateMidenDestinationProbe() { + const miden = useEarnMiden({ + earnMiden: { + enabled: true, + connected: true, + accountId: "0x0e9089055fb6f54170bbf6159da028", + accountIsPublic: false, + assets: [], + createP2IDNote: async () => ({ success: false }), + } as EarnMidenAdapter, + isTestnet: false, + midenEnabled: true, + fundingSource: "evm", + selectedMidenFaucetId: DEFAULT_MIDEN_FAUCET.faucetId, + earnTab: "withdraw", + smartWithdraw: true, + smartDestChainId: MIDEN_VIRTUAL_CHAIN_ID, + smartDestTokenAddress: DEFAULT_MIDEN_FAUCET.faucetId, + }); + + return createElement("output", null, `${miden.smartDestNotReady}:${miden.smartDest?.recipientAccount}`); +} + +test("private Miden accounts can receive public P2ID withdrawal notes", () => { + assert.equal( + renderToStaticMarkup(createElement(PrivateMidenDestinationProbe)), + "false:0x0e9089055fb6f54170bbf6159da028", + ); +}); + + +test("ready private Miden destinations can submit without reconnecting", () => { + assert.deepEqual(resolveEarnCta({ + ...midenCtaParams, + earnTab: "withdraw", + hasSelectedPosition: true, + withdrawAmount: "0.1", + midenConnected: true, + midenSmartDestNotReady: false, + }), { action: "submit", label: "Withdraw" }); +}); + +test("a disconnected Miden withdrawal destination still offers connection", () => { + assert.deepEqual(resolveEarnCta({ + ...midenCtaParams, + earnTab: "withdraw", + hasSelectedPosition: true, + withdrawAmount: "0.1", + midenConnected: false, + midenSmartDestNotReady: true, + }), { action: "connectMiden", label: "Connect Miden wallet" }); +}); + +test("Robinhood testnet is offered as an Earn funding source", () => { + function Probe() { + const engine = useEarnEngine({ + isOpen: true, + onClose: () => undefined, + api: { baseUrl: "https://allocator.example.test" }, + network: "testnet", + }); + return createElement("output", null, String(engine.allTokens.some((t) => t.chainId === 46630))); + } + const markup = renderToStaticMarkup(createElement( + WagmiProvider, { config: wagmiConfig }, + createElement(QueryClientProvider, { client: new QueryClient() }, createElement(Probe)), + )); + assert.equal(markup, "true"); +}); diff --git a/test/earn-withdraw-origin.test.tsx b/test/earn-withdraw-origin.test.tsx new file mode 100644 index 0000000..cd29cae --- /dev/null +++ b/test/earn-withdraw-origin.test.tsx @@ -0,0 +1,139 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createElement } from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { createWalletClient, custom } from 'viem'; +import { arbitrum } from 'viem/chains'; +import { EpochIntentSDK } from '@epoch-protocol/epoch-intents-sdk'; +import { + useEarnIntentFlow, + type EarnQuoteInput, +} from '../src/earn/use-earn-intent-flow'; + +const address = '0x050134E8Ff88f79F422EF33CD5c0FaC93f709566'; +const usdc = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'; +const walletClient = createWalletClient({ + account: address, + chain: arbitrum, + transport: custom({ + request: async () => { + throw new Error('Unexpected wallet request'); + }, + }), +}); +const input: EarnQuoteInput = { + tab: 'withdraw', + amount: '0.000513', + sourceChainId: 1, + sourceToken: { + address: usdc, + symbol: 'USDC', + name: 'USDC', + decimals: 6, + chainId: 1, + }, + network: 'mainnet', + market: { + id: 'ethereum-usdc', + displayName: 'USDC', + chainLabel: 'Ethereum', + aprDecimal: 0, + vaultAddress: usdc, + destinationChainName: 'Ethereum', + chainId: 1, + oneDeltaMarketUid: `AAVE_V3:1:${usdc}`, + token: { address: usdc, symbol: 'USDC', decimals: 6 }, + }, +}; + +for (const destination of ['miden', 'evm', 'underlying'] as const) { + test(`${destination} withdrawal preview quotes Ethereum USDC on Ethereum while wallet is on Arbitrum`, async (t) => { + const quotedChains: number[] = []; + t.mock.method(EpochIntentSDK.prototype, 'getTaskData', async (params) => ({ + taskTypeString: 'test', + intentData: params.intentData, + })); + t.mock.method( + EpochIntentSDK.prototype, + 'getIntentQuote', + async function (this: EpochIntentSDK) { + quotedChains.push(Reflect.get(this, 'config').walletClient.chain.id); + return { + success: true, + tokenOut: '500', + transactions: [], + resourceLockRequired: true, + }; + }, + ); + let flow!: ReturnType; + function Probe() { + flow = useEarnIntentFlow({ + address, + walletClient, + apiBaseUrl: 'http://localhost:3000', + sessionId: 'origin-test', + }); + return null; + } + renderToStaticMarkup(createElement(Probe)); + await flow.fetchQuote({ + ...input, + smartWithdraw: destination !== 'underlying', + smartDestChainId: destination === 'miden' ? 999999999 : 8453, + smartDestTokenAddress: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', + ...(destination === 'miden' + ? { + midenDest: { + recipientAccount: '0xc8f8016eff9bbf516610db9b34751c', + faucetId: '0xe69e6ca6e39df1b10c1e5399399feb', + decimals: 6, + }, + } + : {}), + }); + assert.deepEqual(quotedChains, [1]); + assert.equal( + walletClient.chain.id, + 42161, + 'Preview must not switch the wallet', + ); + }); +} + +for (const smartWithdraw of [false, true]) { + test(`${smartWithdraw ? 'smart' : 'plain'} withdrawal refuses execution on the wrong wallet chain`, async (t) => { + let taskCalls = 0; + let errorMessage: string | undefined; + t.mock.method(EpochIntentSDK.prototype, 'getTaskData', async () => { + taskCalls++; + throw new Error('Should reject before building an execution'); + }); + let flow!: ReturnType; + function Probe() { + flow = useEarnIntentFlow({ + address, + walletClient, + apiBaseUrl: 'http://localhost:3000', + sessionId: 'origin-test', + onError: ({ error }) => { + errorMessage = error.message; + }, + }); + return null; + } + renderToStaticMarkup(createElement(Probe)); + await flow.submit({ + ...input, + quote: null, + smartWithdraw, + smartDestChainId: 8453, + smartDestTokenAddress: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', + }); + assert.equal( + errorMessage, + 'Switch your wallet to chain 1 before withdrawing', + ); + assert.equal(taskCalls, 0); + }); +} diff --git a/test/infura-rpc.test.ts b/test/infura-rpc.test.ts new file mode 100644 index 0000000..e38736d --- /dev/null +++ b/test/infura-rpc.test.ts @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createPublicClient, http } from "viem"; +import { getDemoChains, getDemoRpcUrls } from "../demo/src/config/rpc"; + +test("Infura routing also replaces chain metadata used by SDK-created clients", async () => { + const urls = getDemoRpcUrls({ VITE_INFURA_RPC_PROXY_ENABLED: true }); + assert.equal(urls[137], "/widget/rpc/polygon"); + const chains = getDemoChains(urls); + for (const chain of chains) { + if (![4663, 46630].includes(chain.id)) { + assert.match(chain.rpcUrls.default.http[0], /^\/widget\/rpc\//); + } + assert.equal(chain.rpcUrls.default.http[0], urls[chain.id]); + } + const polygon = chains.find((chain) => chain.id === 137)!; + const calls: { url: string; body: unknown }[] = []; + const client = createPublicClient({ + chain: polygon, + transport: http(new URL(polygon.rpcUrls.default.http[0], "https://demo.example").href, { + fetchFn: async (input, init) => { + const request = input instanceof Request ? input : new Request(input, init); + const body = await request.json(); + calls.push({ url: request.url, body }); + return new Response(JSON.stringify({ jsonrpc: "2.0", id: body.id, result: "0x2" })); + }, + }), + }); + assert.equal(await client.getTransactionCount({ + address: "0x4235215114484bACDfF0071dB54Dc9faaD3489a9", + blockTag: "pending", + }), 2); + assert.equal(calls[0].url, "https://demo.example/widget/rpc/polygon"); + assert.equal((calls[0].body as { method: string }).method, "eth_getTransactionCount"); +}); + +test("public RPC defaults remain usable without a server-side Infura credential", () => { + const urls = getDemoRpcUrls({}); + assert.equal(urls[137], "https://polygon-bor-rpc.publicnode.com"); + assert.equal(urls[8453], "https://mainnet.base.org"); +}); + +test("proxy routes distinguish mainnet and Sepolia paths and keep authentication server-side", async () => { + const { default: configFactory } = await import("../demo/vite.config"); + const previous = process.env.INFURA_API_KEY; + process.env.INFURA_API_KEY = Buffer.from(`${"0".repeat(32)}:test-secret`).toString("base64"); + try { + const config = await configFactory({ command: "serve", mode: "test" }); + const proxy = config.server!.proxy!; + for (const [path, hostname] of [ + ["/widget/rpc/polygon", "polygon-mainnet.infura.io"], + ["/widget/rpc/base", "base-mainnet.infura.io"], + ["/widget/rpc/base-sepolia", "base-sepolia.infura.io"], + ["/widget/rpc/optimism-sepolia", "optimism-sepolia.infura.io"], + ]) { + const matches = Object.keys(proxy).filter((key) => new RegExp(key).test(path)); + assert.equal(matches.length, 1, `${path} must match exactly one upstream`); + const route = proxy[matches[0]] as { + target: string; headers: { Authorization: string }; rewrite(path: string): string; + }; + assert.equal(new URL(route.target).hostname, hostname); + assert.equal(route.rewrite(path), ""); + assert.equal(Buffer.from(route.headers.Authorization.slice(6), "base64").toString(), ":test-secret"); + } + assert.equal(config.define!["import.meta.env.VITE_INFURA_RPC_PROXY_ENABLED"], "true"); + assert.ok(!JSON.stringify(config.define).includes("test-secret")); + } finally { + if (previous === undefined) delete process.env.INFURA_API_KEY; + else process.env.INFURA_API_KEY = previous; + } +}); diff --git a/test/miden-mainnet-demo.test.ts b/test/miden-mainnet-demo.test.ts new file mode 100644 index 0000000..32917c4 --- /dev/null +++ b/test/miden-mainnet-demo.test.ts @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +import { + BASE_MAINNET_USDC, + MIDEN_MAINNET, + resolveEpochApiBaseUrl, +} from "../demo/src/config/miden-mainnet"; +import { + MIDEN_MAINNET_WALLET_NETWORK, + requirePublicMidenAccount, +} from "../demo/src/miden/lib/mainnet-wallet-compat"; +import viteConfig from "../demo/vite.config"; + +test("Miden bridge exposes only Base USDC to native Miden USDCX at six decimals", () => { + assert.deepEqual(BASE_MAINNET_USDC, { + symbol: "USDC", + address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + decimals: 6, + chainId: 8453, + }); + assert.equal(MIDEN_MAINNET.chainId, 999_999_999); + assert.equal(MIDEN_MAINNET.network, "miden-mainnet"); + assert.equal(MIDEN_MAINNET.rpcUrl, "https://rpc.cedar.miden.io"); + assert.equal(MIDEN_MAINNET.noteTransportUrl, "https://transport.cedar.miden.io"); + assert.equal(MIDEN_MAINNET.explorer, "https://midenscan.com"); + assert.equal(MIDEN_MAINNET.usdcx.symbol, "USDCX"); + assert.equal(MIDEN_MAINNET.usdcx.decimals, 6); + assert.match(MIDEN_MAINNET.usdcx.faucetId, /^mm1/); +}); + +test("browser API configuration uses the Vite value and otherwise stays same-origin", () => { + assert.equal( + resolveEpochApiBaseUrl({ + VITE_EPOCH_API_BASE_URL: " https://api.example.test/ ", + }), + "https://api.example.test", + ); + assert.equal(resolveEpochApiBaseUrl({}), "/allocator"); +}); + +test("widget demo is built beneath the hosted /widget/ path", async () => { + const config = await viteConfig({ command: "build", mode: "production" }); + assert.equal(config.base, "/widget/"); +}); + +test("positions API permits localhost HTTP and requires HTTPS for remote hosts", () => { + const env = readFileSync(new URL("../demo/.env", import.meta.url), "utf8"); + const value = env.match(/^VITE_POSITIONS_API_BASE_URL=(.+)$/m)?.[1]; + assert.ok(value, "VITE_POSITIONS_API_BASE_URL must be configured"); + + const url = new URL(value); + const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); + assert.ok(url.protocol === "https:" || (local && url.protocol === "http:")); +}); + +test("Bread compatibility boundary sends the raw mainnet wire value", () => { + assert.equal(MIDEN_MAINNET_WALLET_NETWORK, "mainnet"); +}); + +test("private Miden accounts are rejected before quote construction", () => { + assert.throws( + () => + requirePublicMidenAccount({ + toString: () => "0xprivate", + isPublic: () => false, + }), + /public Miden account/i, + ); + assert.equal( + requirePublicMidenAccount({ + toString: () => "0xpublic", + isPublic: () => true, + }), + "0xpublic", + ); +}); + +test("a private Bread account still resolves as Miden source metadata", async () => { + const compatModule = await import( + "../demo/src/miden/lib/mainnet-wallet-compat" + ); + const normalizeMidenAccount = ( + compatModule as typeof compatModule & { + normalizeMidenAccount?: (accountId: { + toString(): string; + isPublic(): boolean; + }) => { hex: string; isPublic: boolean }; + } + ).normalizeMidenAccount; + + assert.equal(typeof normalizeMidenAccount, "function"); + assert.deepEqual( + normalizeMidenAccount?.({ + toString: () => "0x0e9089055fb6f54170bbf6159da028", + isPublic: () => false, + }), + { + hex: "0x0e9089055fb6f54170bbf6159da028", + isPublic: false, + }, + ); +}); diff --git a/test/miden-mainnet-sdk-compat.test.ts b/test/miden-mainnet-sdk-compat.test.ts new file mode 100644 index 0000000..a72415d --- /dev/null +++ b/test/miden-mainnet-sdk-compat.test.ts @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { ensurePragmaMidenMainnetOracle } from "../demo/src/miden/lib/mainnet-sdk-compat"; + +test("fills the Pragma Miden mainnet RPC missing from commons SDK 2.0.0", () => { + const graph = { chains: { Miden: { chainId: 999_999_999 } } }; + + const configured = ensurePragmaMidenMainnetOracle( + graph, + "https://rpc.cedar.miden.io", + ); + + assert.deepEqual(configured.oracles, { + PragmaMidenV1: { rpcUrl: "https://rpc.cedar.miden.io" }, + }); +}); + +test("preserves a Pragma Miden RPC supplied by the commons graph", () => { + const graph = { + oracles: { PragmaMidenV1: { rpcUrl: "https://configured.example" } }, + }; + + const configured = ensurePragmaMidenMainnetOracle( + graph, + "https://rpc.cedar.miden.io", + ); + + assert.equal( + configured.oracles.PragmaMidenV1.rpcUrl, + "https://configured.example", + ); +}); diff --git a/test/native-eth.test.ts b/test/native-eth.test.ts new file mode 100644 index 0000000..da05555 --- /dev/null +++ b/test/native-eth.test.ts @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + EPOCH_SUPPORTED_TOKENS, + EPOCH_TESTNET_TOKENS, + NATIVE_ETH_ADDRESS, + getEpochTokensByChainEnv, +} from "../src/epoch-config.js"; + +test("the widget token registry offers ETH separately from WETH", () => { + for (const [isTestnet, chainIds, tokens] of [ + [false, [1, 10, 8453, 42161, 4663], EPOCH_SUPPORTED_TOKENS], + [true, [84532, 11155111, 11155420, 46630], EPOCH_TESTNET_TOKENS], + ] as const) { + for (const chainId of chainIds) { + const chainTokens = getEpochTokensByChainEnv(chainId, isTestnet); + assert.ok(chainTokens.some((token) => token.symbol === "ETH" && token.address === NATIVE_ETH_ADDRESS)); + } + } + + const baseTokens = getEpochTokensByChainEnv(8453, false); + assert.ok(baseTokens.some((token) => token.symbol === "WETH" && token.address !== NATIVE_ETH_ADDRESS)); + assert.equal(getEpochTokensByChainEnv(137, false).some((token) => token.symbol === "ETH"), false); + assert.equal( + EPOCH_SUPPORTED_TOKENS.some((token) => token.symbol === "ETH" && token.chainId === 999999999), + false, + ); +}); diff --git a/test/robinhood-miden-usdg.test.ts b/test/robinhood-miden-usdg.test.ts new file mode 100644 index 0000000..04ac723 --- /dev/null +++ b/test/robinhood-miden-usdg.test.ts @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { normalizeMidenId } from "@epoch-protocol/epoch-commons-sdk"; +import { getMidenFaucetDecimals } from "../demo/src/miden/constants/miden-tokens"; +import { getDemoChains, getDemoRpcUrls } from "../demo/src/config/rpc"; +import { getMidenChainTokens } from "../src/earn/miden"; + +test("Robinhood wallet chains retain their own RPC with Infura enabled", () => { + for (const proxy of [false, true]) { + const urls = getDemoRpcUrls({ VITE_INFURA_RPC_PROXY_ENABLED: proxy }); + const chains = getDemoChains(urls); + assert.equal(chains.find((c) => c.id === 4663)?.rpcUrls.default.http[0], + "https://rpc.mainnet.chain.robinhood.com"); + assert.equal(chains.find((c) => c.id === 46630)?.rpcUrls.default.http[0], + "https://rpc.testnet.chain.robinhood.com"); + } +}); + +test("Miden USDG is selectable on mainnet with the supplied faucet and six decimals", () => { + const token = getMidenChainTokens(false).find((t) => t.symbol === "USDG"); + assert.ok(token); + assert.equal(token.address, "mm1ar7rgznnerajt52p9ul6rltd8g039qsa"); + assert.equal(token.decimals, 6); + assert.equal(token.chainId, 999999999); + assert.ok(!getMidenChainTokens(true).some((t) => t.symbol === "USDG")); +}); + +test("Robinhood RPC overrides apply to transports and wallet chain metadata", () => { + const urls = getDemoRpcUrls({ + VITE_INFURA_RPC_PROXY_ENABLED: true, + VITE_ROBINHOOD_RPC_URL: " https://mainnet.example.test/rpc ", + VITE_ROBINHOOD_TESTNET_RPC_URL: " https://testnet.example.test/rpc ", + }); + assert.equal(urls[4663], "https://mainnet.example.test/rpc"); + assert.equal(urls[46630], "https://testnet.example.test/rpc"); + assert.equal(getDemoChains(urls).find((c) => c.id === 4663)?.rpcUrls.default.http[0], urls[4663]); +}); + + +test("Miden USDG wallet hex IDs resolve to the configured faucet decimals", () => { + const hex = normalizeMidenId("mm1ar7rgznnerajt52p9ul6rltd8g039qsa"); + assert.equal(getMidenFaucetDecimals(hex), 6); + assert.equal(getMidenFaucetDecimals("mm1ar7rgznnerajt52p9ul6rltd8g039qsa"), 6); + assert.equal(getMidenFaucetDecimals("unknown-faucet"), undefined); +}); diff --git a/test/withdraw-error.test.tsx b/test/withdraw-error.test.tsx new file mode 100644 index 0000000..7252867 --- /dev/null +++ b/test/withdraw-error.test.tsx @@ -0,0 +1,21 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { WithdrawFundsButton } from "../src/components/WithdrawDetailPanel"; + +test("withdraw footer exposes execution errors instead of appearing unresponsive", () => { + const html = renderToStaticMarkup(createElement(WithdrawFundsButton, { + onClick: () => undefined, + error: "Transaction cancelled", + })); + assert.match(html, /role="alert"/); + assert.match(html, /Transaction cancelled/); +}); + +test("withdraw footer has no alert when there is no execution error", () => { + const html = renderToStaticMarkup(createElement(WithdrawFundsButton, { + onClick: () => undefined, + })); + assert.doesNotMatch(html, /role="alert"/); +});