@spicenet-io/spiceflow-ui 5.0.0 → 5.0.1-release.a53b763a.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +758 -0
  2. package/dist/auth-privy.cjs +1 -1
  3. package/dist/auth-privy.js +1 -1
  4. package/dist/components/SpiceDeposit/lib/executors.d.ts +1 -0
  5. package/dist/components/SpiceDeposit/lib/feePreview.d.ts +12 -0
  6. package/dist/components/SpiceDeposit/lib/normalizedCredit.d.ts +2 -0
  7. package/dist/components/SpiceDeposit/steps/DepositModal.d.ts +3 -1
  8. package/dist/components/SpiceDeposit/steps/NormalizedDepositModal.d.ts +7 -0
  9. package/dist/components/SpiceDeposit/steps/SelectTokenModal.d.ts +3 -1
  10. package/dist/components/SpiceSupply/lib/actionProceeds.d.ts +2 -1
  11. package/dist/components/SpiceSupply/lib/buildBatches.d.ts +1 -0
  12. package/dist/components/SpiceSupply/lib/feeConversion.d.ts +1 -1
  13. package/dist/components/SpiceSupply/lib/feePreview.d.ts +2 -0
  14. package/dist/components/SpiceWithdraw/lib/useEmbeddedWithdraw.d.ts +5 -0
  15. package/dist/execution/conditionalBundle.d.ts +32 -0
  16. package/dist/execution/fundEmbeddedWallet.d.ts +1 -0
  17. package/dist/execution/monadSourceSwap.d.ts +46 -0
  18. package/dist/hooks/useSpiceAction.d.ts +4 -0
  19. package/dist/hooks/useSpiceConditionalIntents.d.ts +3 -1
  20. package/dist/hooks/useSpiceExecution.d.ts +1 -0
  21. package/dist/hooks/useSpiceLimitOrders.d.ts +2 -0
  22. package/dist/hooks/useSpiceLock.d.ts +4 -0
  23. package/dist/hooks/useSpiceSupply.d.ts +5 -0
  24. package/dist/hooks/useWalletBalances.d.ts +1 -0
  25. package/dist/index.cjs +9 -9
  26. package/dist/index.d.ts +2 -2
  27. package/dist/index.js +7 -7
  28. package/dist/privy-CpxYyPRI.js +2 -0
  29. package/dist/privy-DvXXQv3w.cjs +1 -0
  30. package/dist/types/conditionalIntents.d.ts +32 -0
  31. package/dist/types/deposit.d.ts +8 -0
  32. package/dist/types/withdraw.d.ts +7 -0
  33. package/dist/utils/chains/index.d.ts +1 -1
  34. package/dist/utils/crossChainRouter/uniV3.d.ts +3628 -2
  35. package/dist/utils/relayer/index.d.ts +37 -1
  36. package/package.json +2 -2
  37. package/dist/privy-BYW5c3wU.cjs +0 -1
  38. package/dist/privy-CQIs-ZGr.js +0 -2
package/README.md ADDED
@@ -0,0 +1,758 @@
1
+ # SpiceFlow UI SDK
2
+
3
+ A React component library for building DeFi swap interfaces with multi-chain support.
4
+
5
+ ## Version and migration
6
+
7
+ Release `4.11.0` includes quote prewarming, scoped fee-hint reuse, concurrent fee
8
+ checks, configurable fee-estimate tolerance, and faster execution-status polling.
9
+ It uses `@spicenet-io/spiceflow-core@0.7.3`. Source spend caps, destination minimums
10
+ and required destination receipts remain enforced. See the fee-estimate tolerance
11
+ section below for the default and configuration.
12
+
13
+ Check the actual registry tag and client pin before adopting it. See
14
+ [CONSISTENCY-MIGRATION.md](CONSISTENCY-MIGRATION.md) for the earlier inventory/action
15
+ migration. Publishing the SDK does not upgrade consuming apps automatically.
16
+
17
+ ## Installation and provider setup
18
+
19
+ Select an approved exact version, preserving the app's dependency-age and security policies:
20
+
21
+ ```bash
22
+ bun add --exact @spicenet-io/spiceflow-ui@4.11.0
23
+ ```
24
+
25
+ Reuse compatible host-owned Privy, wagmi and QueryClient providers. Read the exact
26
+ package's peer dependencies; do not replace the wallet stack as part of a version bump.
27
+
28
+ The SDK adds its stylesheet (spinner keyframes, focus ring, reduced-motion rule) to the
29
+ page when it loads, so no CSS import is needed. `@spicenet-io/spiceflow-ui/styles.css`
30
+ is still exported for a host whose Content Security Policy forbids inline styles;
31
+ importing it as well is harmless.
32
+
33
+ ```tsx
34
+ import { SpiceFlowProvider } from "@spicenet-io/spiceflow-ui";
35
+
36
+ // Inside the host's existing WagmiProvider → QueryClientProvider → PrivyProvider stack.
37
+ <SpiceFlowProvider
38
+ provider="privy"
39
+ network="mainnet"
40
+ nativeChainId={8453}
41
+ rpcOverrides={clientRpcUrls}
42
+ >
43
+ {children}
44
+ </SpiceFlowProvider>;
45
+ ```
46
+
47
+ Configure Privy credentials/policy on the host's `PrivyProvider`. Supply client RPCs
48
+ through `rpcOverrides` for the chains you exercise, and keep the SDK/wallet chain sets
49
+ aligned. An entry in `rpcOverrides` always wins; a chain without one uses the chain's
50
+ built-in endpoint, so an integration that passes none keeps working. Wallet-library
51
+ transports alone do not configure SDK reads. Rollup price lookups read only a
52
+ host-configured RPC. Keep private credentials out of browser bundles.
53
+
54
+ ## Integration ownership
55
+
56
+ - Use stock components when they fit the approved UI; use `useSpiceSupply` for custom
57
+ action forms. `useSpiceLock` and legacy `useSpiceAction` delegate to that controller.
58
+ - In this source (not yet published), `useSpiceSupply` defaults `enabled` to `true`.
59
+ Omit it for a mounted action form, or pass `enabled: isOpen` when a hidden form stays
60
+ mounted. Use `canExecute` for submit-button readiness; fee calculation does not
61
+ require toggling `enabled`. Published 4.10.0 still requires an explicit value.
62
+ - Declare the destination token by chain and address:
63
+ `destinationToken={{ chainId: 8453, address: USDC }}`. The SDK takes the symbol and
64
+ decimals from the chain's token registry, then from the token contract, and holds the
65
+ action until they are known. Decimals that cannot be read block the action; a symbol
66
+ that cannot be read falls back to the shortened address. Any field you pass wins, so a
67
+ full `{ address, symbol, decimals, chainId }` object behaves exactly as before.
68
+ - Supply destination metadata, protocol `buildActionCalls` or destination-only
69
+ `lockBatches`, beneficiary semantics, and awaited application updates. The SDK owns
70
+ inventory, routing, Max, fees, accepted plans, funding, execution and recovery.
71
+ - For the account, use `useSpiceAccount()` instead of reading `SpiceFlowProviderContext`:
72
+ `mode` (`"embedded"` or `"external"`), `setMode`, `ownerAddress` for the current mode,
73
+ both wallet addresses and the whitelist state. A provider with a fixed `mode` prop
74
+ ignores `setMode`.
75
+ - For custom holdings, use `useSpiceInventory` and `assetPositionId`. Keep raw balance,
76
+ default visibility and spend eligibility separate. Preserve rows during refresh;
77
+ stale/failed balances cannot authorize spending, and confirmed zero wins.
78
+ - In this unreleased source, eligible External-mode actions with a matching wallet token
79
+ and destination chain execute directly from the external signer, without embedded funding.
80
+ Other assets/chains still use embedded funding and the shared routed executor.
81
+ A controlled ERC20 action can opt into `actionExecution: { wallet: "external", recoveryKey: "my-action" }`
82
+ when its contract requires the external caller. The SDK routes funds to that wallet,
83
+ verifies delivery, then submits the captured host calls. This also permits a matching
84
+ external source to execute directly while the app remains in Embedded mode.
85
+ `onPayExecute` and `onLockExecute` remain blocked. Verify contract caller/beneficiary and NFT receiver behavior.
86
+ Published `.16` does not contain this restoration.
87
+ - Routed external execution now requires the API's `externalExecution` capability
88
+ before any source funding. The original action retains its positive ERC20 delivery,
89
+ accepted protocol calls and canonical receipt ownership. Native matching-token,
90
+ same-chain direct execution retains its existing behavior.
91
+ - Use the normal `submitSupply()`, `submitPay()` or `submit()` button after an
92
+ interrupted routed external action. `canExecute` includes its retry readiness;
93
+ render "Try again" when `status.canRetry` is true. The SDK refreshes wallet
94
+ inventory and reconciles the original calls before simulating and signing only
95
+ the remaining direct work. It never repeats delivery or a confirmed conversion,
96
+ mint or stake. A confirmed revert can be retried only after canonical proof and
97
+ fresh simulation; pending/unknown outcomes cannot authorize another send.
98
+ Do not apply the old source's quote/balance gates to this retry. Host ownership,
99
+ sale/receiver and protocol availability checks still apply. `refreshStatus()`
100
+ and `retrySupply()` remain read-only and never prompt automatically.
101
+ The earlier `resumeExternalAction()` alias is retained for compatibility; a
102
+ separate Continue control is unnecessary. This source requires the compatible
103
+ API146 retry preparation contract and is not a published SDK recommendation.
104
+ - Canonical nonce recovery covers direct top-level transactions from the accepted
105
+ external account. The provider must submit the requested call with its reserved
106
+ nonce; account bytecode alone does not prove every provider's execution model.
107
+ A deployed contract account without an EIP-7702 delegation designator keeps its
108
+ existing provider sends and local receipt success behavior. Its outer hashes are
109
+ explicitly unverified analytics observations, without inner-call volume attribution
110
+ or durable recovery after reload. An uncertain mounted operation is held and is
111
+ never automatically resent. Unsupported history does not forbid a distinct action
112
+ that the user explicitly reviews and submits.
113
+ - Supply `input` adds fees to principal; `input-inclusive` uses a total budget; Pay
114
+ `output` fixes the destination amount. Use controller readiness/Max/status instead of
115
+ constructing an executor context or duplicating fee arithmetic in the host.
116
+ - Use controller recovery for uncertain funding and `retryFinalization()` for failed
117
+ application updates after settlement. Preserve original host terms across reload.
118
+ - Deposit and rollup Withdraw retain distinct execution semantics while sharing
119
+ inventory/policy. Account wallet withdrawal uses the inclusive Supply controller and its fee hierarchy.
120
+
121
+ Inventory isolation does not establish support for simultaneous differently configured
122
+ providers: underlying quote/execution transports still have global state.
123
+
124
+ ## Liquidity venues
125
+
126
+ When a flow has to swap on the destination chain, the SDK quotes every liquidity
127
+ venue that covers that chain and takes the best fill: the most output on a
128
+ supply, the least input on a pay. Routing is decided in the SDK using venue RPC
129
+ or API quotes. The solver only executes the calls the winning quote produced.
130
+
131
+ Leave `liquidityVenues` off and you get the built-in venues. Declare it once on
132
+ the provider to add your own, and every component picks them up.
133
+
134
+ ```tsx
135
+ <SpiceFlowProvider
136
+ network="mainnet"
137
+ nativeChainId={4663}
138
+ rpcOverrides={{ 4663: ROBINHOOD_RPC }}
139
+ liquidityVenues={{
140
+ venues: [
141
+ {
142
+ protocol: "uniswap-v3",
143
+ chainId: 4663,
144
+ swapRouter: "0x1e406484F1F204b23cE84B9901C0171a738fd406",
145
+ quoterV2: "0x3E290e5E01818002A0b672148BdC7514D861C7B3",
146
+ hubCurrencies: ["0x0bd7d308f8e1639fab988df18a8011f41eacad73"],
147
+ },
148
+ ],
149
+ }}
150
+ >
151
+ ```
152
+
153
+ Your venues race the built-ins on price; they do not override them. Set
154
+ `includeDefaults: false` to drop the built-ins and route only through what you
155
+ declared. On a chain with no venue at all, quoting fails with that chain named
156
+ rather than falling back to something you did not configure.
157
+
158
+ Every entry names one chain and one protocol family, and serves both swap
159
+ directions. Supply the **deployment's** addresses, not a pool address: a
160
+ v3-style pool calls back into `msg.sender`, so swaps go through the router and
161
+ quotes through the quoter. The SDK finds the pools from the fee tiers (or tick
162
+ spacings) and hub currencies.
163
+
164
+ | `protocol` | Required | Optional |
165
+ | ---------------------- | ------------------------------------------------- | -------------------------------------------------------- |
166
+ | `uniswap-v3` | `chainId`, `swapRouter`, `quoterV2` | `name`, `feeTiers`, `hubCurrencies`, `routerHasDeadline` |
167
+ | `uniswap-v4` | `chainId`, `quoter`, `universalRouter`, `permit2` | `name`, `hubCurrencies` |
168
+ | `aerodrome-slipstream` | `chainId`, `swapRouter`, `quoterV2` | `name`, `tickSpacings`, `hubCurrencies` |
169
+ | `metric` | `chainId` | `name`, `apiUrl`, `swapRouter` |
170
+
171
+ Metric uses the tx API's `/liquidity/metric` proxy when running inside
172
+ `SpiceFlowProvider`, derived from its existing `apiUrl`. The backend injects
173
+ `METRIC_API_KEY`; no credential is included in the browser or SDK config.
174
+ Deploy the backend proxy and configure its secret before adopting this SDK.
175
+
176
+ Partner defaults cover Ethereum, BSC, Polygon, Monad, HyperEVM, MegaETH,
177
+ Robinhood, Base, Arbitrum, and Avalanche. This adds venue coverage only: the
178
+ app's supported chains, token policy and `includeDefaults: false` remain intact.
179
+ Standalone factories without a proxy retain the three public-chain defaults.
180
+ Set `liquidityVenues.metricApiUrl` to override the proxy base URL, or set a
181
+ Metric venue's `apiUrl` for that individual venue. Both exact-input and
182
+ exact-output use the same proxy and selected-pool metadata. Split routes are
183
+ not requested; the SDK encodes v1 router calls with recipient/slippage bounds.
184
+ A quote is not execution proof: pool extensions and oracle freshness can reject
185
+ a swap, and Ethereum conditional-update pools require compatible submission
186
+ ordering. Verify the actual caller and submission path before release.
187
+
188
+ `name` is the label shown to the user as "via <name>" once a swap is quoted, so
189
+ give it the name people know the venue by. It defaults to the protocol, which
190
+ means a swap always names something real rather than a family it does not belong
191
+ to.
192
+
193
+ `hubCurrencies` are the intermediate tokens tried for two-hop routes, usually
194
+ wrapped native and the chain's main stablecoin. Set `routerHasDeadline` when the
195
+ deployment forked the original Uniswap `SwapRouter`, whose exact-output structs
196
+ carry a deadline; SwapRouter02 forks do not.
197
+
198
+ Most DEXs are forks of one of these families, so adding one is addresses only.
199
+ A venue from a different family (a Uniswap v2 pair, Curve, Balancer) needs an
200
+ adapter in the SDK — send us the chain, router, quoter and one funded pool and
201
+ it becomes a `protocol` everyone can name.
202
+
203
+ ## Components
204
+
205
+ - **SwapWidget** - Main swap interface component
206
+ - **AssetSelector** - Token selection component
207
+ - **SpiceDeposit** - Deposit modal component
208
+ - **StatusDisplay** - Transaction status display
209
+ - **ProviderLogin** - Wallet connection component
210
+ - **DebugWidget** - Development debugging component
211
+ - **Button**, **Input**, **Modal** - UI primitives
212
+
213
+ ## Development
214
+
215
+ ### Rollup balance pricing
216
+
217
+ Rollup USD values use the host-configured RPC provider's pricing capability when the balance API has no valid value. The built-in account panel and withdrawal modal enable this while open; custom `useSpiceAssets` consumers can opt in with `priceEnabled`. Quantities arrive independently. Lookups follow receipt mappings, prefer `nativeChainId`, and fall back to other supported chains with a configured Alchemy endpoint. Explicit account `tokenPrices` overrides still take precedence over provider quotes.
218
+
219
+ Wallet discovery and rollup balances share a one-minute quote cache. Pricing polls only while the view is open and the page is visible. A failed refresh can retain a marked stale quote for up to five minutes; an unavailable quote displays `—`. No extra key, internal RPC, or symbol-based ERC-20 price fallback is used.
220
+
221
+ ### Host tokens
222
+
223
+ A token the SDK does not know (a protocol's own token, a receipt token) is declared
224
+ once on the provider. Every surface that lists balances then reads it: Supply, Pay,
225
+ Lock, the account panel and Withdraw.
226
+
227
+ ```tsx
228
+ <SpiceFlowProvider
229
+ additionalSourceTokens={[{ address: TOKEN, chainId: 8453, symbol: "TOKEN", decimals: 18 }]}
230
+ >
231
+ ```
232
+
233
+ A component's or hook's own `additionalSourceTokens` still works and is added to the
234
+ provider's list.
235
+
236
+ ### Host token prices
237
+
238
+ A host token usually has no price the SDK can find, so the account panel lists it
239
+ without a USD value. `AccountDisplay.tokenPrices` takes the host's own price for it,
240
+ keyed by `chainId:address`. The value counts toward the account total and the row
241
+ sorts with the rest.
242
+
243
+ ```tsx
244
+ <AccountDisplay tokenPrices={{ [`8453:${TOKEN}`]: tokenUsdPrice }} />
245
+ ```
246
+
247
+ The SDK's own price wins whenever it has one. A symbol key prices rollup balances
248
+ only: any wallet token can carry any symbol, so a wallet balance is matched by address
249
+ alone. The price is for display and never changes which balance an action spends.
250
+
251
+ ### Host-supplied token logos
252
+
253
+ `AccountDisplay.tokenLogos` maps a token symbol to a logo URL, the same key
254
+ shape `tokenPrices` uses. A discovered embedded-wallet balance falls back to
255
+ it when the RPC provider returns no logo, which is what happens for a token
256
+ that is not in the chain's configured token list. Provider metadata still
257
+ wins when it has a logo.
258
+
259
+ ```tsx
260
+ <AccountDisplay tokenLogos={{ TOKEN: tokenLogoUrl }} />
261
+ ```
262
+
263
+ For a host-rendered asset row, this source also exports the SDK's existing logo
264
+ resolver from the package root:
265
+
266
+ ```tsx
267
+ const logo = useTokenLogo(asset.logoURI, asset.chainId, asset.address);
268
+ ```
269
+
270
+ Import `useTokenLogo` from `@spicenet-io/spiceflow-ui`. It returns the supplied logo
271
+ immediately, otherwise resolves the shared chain/address token list asynchronously.
272
+ Until a logo is available, it returns `undefined`; keep the balance and selection
273
+ usable and render the host's usual fallback. This source export requires an SDK
274
+ release before a consuming app can adopt it.
275
+
276
+ ### Account with Deposit and Withdraw
277
+
278
+ `SpiceAccount` renders `AccountDisplay` together with `SpiceDeposit` and
279
+ `SpiceWithdraw`, and owns their open state. Withdraw on an idle rollup balance opens
280
+ the modal with that balance selected. It takes every `AccountDisplay` prop except the
281
+ two click handlers; `depositProps` and `withdrawProps` pass through to the modals.
282
+ `styles` and `onDepositSuccess` are shared with the modals unless those props set
283
+ their own.
284
+
285
+ ```tsx
286
+ <SpiceAccount appName="MyApp" onDepositSuccess={refresh} />
287
+ ```
288
+
289
+ Use `AccountDisplay` directly to hide one of the buttons or to open your own flow
290
+ from them.
291
+
292
+ ### Withdraw from an account balance
293
+
294
+ `AccountDisplay.onWithdrawClick` receives the rollup receipt-token ID when a
295
+ user clicks Withdraw on an idle rollup balance. The main Withdraw button calls
296
+ it without an ID. Pass the ID to `SpiceWithdraw.initialSourceAssetId` to open
297
+ the existing modal with that asset selected; the user chooses the destination
298
+ network inside the modal. Existing callbacks that take no arguments continue
299
+ to work.
300
+
301
+ Pass `destinationChainIds` to limit withdrawal delivery to specific networks.
302
+ The selected balance still needs a compatible route to one of those networks.
303
+ Omit this option to offer all compatible networks.
304
+
305
+ `beforeSubmit` can validate a new withdrawal's `chainId`, `token` address, and
306
+ `recipient` before signing. Throwing or rejecting prevents the new withdrawal.
307
+ An accepted action continues through the SDK's existing recovery path.
308
+
309
+ ```tsx
310
+ const [withdrawOpen, setWithdrawOpen] = useState(false);
311
+ const [withdrawAssetId, setWithdrawAssetId] = useState<string>();
312
+
313
+ <AccountDisplay
314
+ onWithdrawClick={(receiptTokenId) => {
315
+ setWithdrawAssetId(receiptTokenId);
316
+ setWithdrawOpen(true);
317
+ }}
318
+ />
319
+ <SpiceWithdraw
320
+ isOpen={withdrawOpen}
321
+ onClose={() => setWithdrawOpen(false)}
322
+ initialSourceAssetId={withdrawAssetId}
323
+ />
324
+ ```
325
+
326
+ `buildSpicenetBatch` defaults to the SDK's `buildSpicenetWithdrawalBatch`. An
327
+ integration that already passes a builder keeps it as an override, and its
328
+ callbacks are unchanged.
329
+ `initialSourceAssetId` selects a current balance by ID; it does not supply a
330
+ cached balance or change the receipt's supported withdrawal routes.
331
+
332
+ Accepted, signed 7702 actions continue on the backend after the browser closes or
333
+ loses connectivity. This applies to Withdraw and shared Supply, Pay, Lock and
334
+ custom-action execution. The SDK discovers recent wallet activity on reopen and
335
+ reconnect; stock modals display it and controlled hooks expose `status.activity`.
336
+ Activity is read-only and never changes the current form, signs, funds, or invokes
337
+ a success callback for an unrelated action. No saved browser journal or Web Lock
338
+ is required. Existing wallet balances remain inventory.
339
+
340
+ Deploy the backend continuation companion (including its API #109 durable execution
341
+ dependency and database migration) before this SDK. The SDK detects
342
+ `GET /actions/capabilities`, requests automatic continuation in `POST /actions`,
343
+ and observes the original action. API #91 submission lookup resolves a lost POST
344
+ response by its original idempotency key without a second POST. An unresolved
345
+ lookup stays unknown; it does not prove failure. Older APIs without the capability
346
+ retain foreground execution and do not gain automatic continuation from this SDK
347
+ alone. Takeover must be enabled for the new capability.
348
+
349
+ The backend retains the accepted authorization and ordered steps. It reconciles
350
+ an ambiguous broadcast by its original relayer submission or receipt, waits for
351
+ source credit, and stops remaining work when authorization has expired or a fresh
352
+ wallet signature is required. Completed steps stay completed. Funding before
353
+ backend acceptance, direct external-wallet calls and host-owned non-7702 execution
354
+ cannot continue without their wallet/host; funds left behind appear in inventory.
355
+ Application finalization stays awaited in the current session, with callback-only
356
+ retry after confirmed execution. After reload the SDK exposes backend status and
357
+ balances; it does not reconstruct or replay host application callbacks.
358
+
359
+ ### Funding sources
360
+
361
+ Supply, Pay and Lock list every balance that can fund the action: the embedded wallet
362
+ and rollup balances, and the connected external wallet, in either wallet mode. To keep a
363
+ mode to its own wallet, pass `includeExternalWalletAssets={false}` (Embedded mode) or
364
+ `includeCrossChainEmbeddedAssets={false}` (External mode). A user who holds the same
365
+ token in both wallets sees one row per wallet; a host that preselects a source should
366
+ match on `assetPositionId`, not on symbol or address alone.
367
+
368
+ ### Routed external callers
369
+
370
+ The controlled hook supports positive ERC20 input, input-inclusive and fixed-output
371
+ actions with an explicit external caller. Configure `rpcOverrides` for the destination
372
+ and any wallet-source chain. Quotes bind the source spend cap, destination delivery,
373
+ external caller and host calls before funding. The SDK checks the destination receipt,
374
+ ERC20 transfer amount and caller balance before requesting the host transactions.
375
+ Only the final external transaction hash reaches awaited application finalization.
376
+
377
+ Below one destination transaction's native gas cost, the accepted route buys gas for
378
+ the pending external calls plus three later transactions. At or above that threshold
379
+ it adds no reserve; direct execution still pays its own native gas. Native destinations,
380
+ zero-principal, proceeds-funded and explicit source-escrow caller actions remain
381
+ unsupported capability gaps. This does not add a stock-component prop or a durable
382
+ execution journal: after signing fails, delivered tokens remain ordinary wallet assets
383
+ and retrying the original route can fund again. Use `retryFinalization()` to retry only
384
+ a failed application callback after the external action has confirmed.
385
+
386
+ ### Action Fee Readiness
387
+
388
+ - Routed Supply, Pay and Lock actions must surface fee estimation before enabling submission.
389
+ - Eligible direct external actions still require an accepted plan but charge no Spicenet fee. Network gas remains payable in the external wallet; native Max reserves gas.
390
+ - Deposit gas and rollup withdrawal semantics remain distinct from action intent fees. Preserve their existing quote/readiness requirements.
391
+ - Account wallet withdrawal uses the shared input-inclusive Supply controller and its fee-only planner for local fees. Do not bypass its fee/readiness gates based on the label "withdraw".
392
+ - Custom actions use the shared controller's `canExecute`; an available balance or old quote alone is insufficient.
393
+ - `onSubmit` on `SpiceSupply`, `SpiceLock`, `SpiceDeposit` and the shared controller fires once when the user submits and the SDK accepts it, before any wallet prompt. Use it for "transaction in progress" feedback instead of listening for clicks on SDK buttons.
394
+ - `max()` on the shared controller (`useSpiceSupply`, `useSpiceLock`) resolves the fee-aware Max for the selected source, or `null` when there is none or the action fixes its output. The host sets the result as the amount.
395
+
396
+ ### USDC cash deposits
397
+
398
+ Pass `isSourceAssetAllowed` to limit fresh `SpiceDeposit` wallet selections by
399
+ chain and token identity. Earlier pending deposits keep their recovery path.
400
+
401
+ In 7702 mode, `<SpiceDeposit normalizeToUsdc />` converts non-USDC wallet
402
+ assets into the source chain's supported USDC and deposits the result into
403
+ escrow. This opt-in is for standalone Add cash flows. It uses the existing
404
+ source chooser, Supply quote/execution controller and backend recovery. It
405
+ keeps ordinary supported-USDC deposits on the existing gas-only deposit path.
406
+ Other wallet modes and consumers that omit the option retain their defaults.
407
+
408
+ Conversions include quoted conversion/intent fees within the entered source
409
+ budget. The form shows the minimum USDC cash received before submission.
410
+ Conversion success requires a successful USDC transfer from the embedded wallet
411
+ to the configured escrow and observed rollup credit; delayed credit can be
412
+ checked again without executing the transaction again. Do not combine this
413
+ standalone cash option with `depositBatches` or `onDepositExecute` actions.
414
+
415
+ Local rehearsal: `bun test tests/hooks/useSpiceSupply.test.tsx --test-name-pattern
416
+ 'normalizes a deposit'` (external source, embedded source, delayed credit and
417
+ wallet-only receipt). Receipt negatives are in
418
+ `tests/components/SpiceDeposit/normalizedCredit.test.ts`. These offline fixtures
419
+ do not establish funded dev acceptance or live liquidity.
420
+
421
+ ### Combined Cash balance
422
+
423
+ `SpiceDeposit` opens a new Add cash flow by default, even when the embedded
424
+ wallet holds leftover funds. With combined Cash enabled, those funds remain
425
+ available to Cash actions.
426
+ Clients that still need the legacy incomplete-deposit prompt can set
427
+ `skipRecovery={false}`. This also discovers existing escrow-eligible wallet balances
428
+ by default. Set `discoverWalletBalances={false}` alongside `skipRecovery={false}`
429
+ to retain recorded incomplete-deposit recovery without prompting to deposit
430
+ ordinary wallet inventory. This option does not disable execution recovery or
431
+ change explicit deposits.
432
+
433
+ Set `combineSourceBalances: true` on `SpiceSupply`, `SpiceLock`, `useSpiceSupply`,
434
+ `useSpiceLock` or `useSpiceAction` to show a token in the embedded wallet and its
435
+ mapped escrow balance on the same chain as one row, and to fund an action from
436
+ both. It is off by default; without it, wallet and escrow balances stay separate
437
+ rows and each action spends only the selected row.
438
+
439
+ Routed actions use escrow first and deposit only the wallet shortfall. Actions
440
+ paid in place keep wallet funds where they are and withdraw only the escrow
441
+ shortfall. The reviewed quote fixes the amount taken from each balance, and both
442
+ are checked again before signing.
443
+
444
+ Custom presentations read `assets.selectable` and
445
+ `assets.getAvailableBalance(asset)`, which returns the combined amount in the
446
+ asset's raw units, or `undefined` while a balance cannot be verified. Pass the
447
+ same getter to `AssetSelector`. Each physical `Asset.balance` is unchanged.
448
+
449
+ Native limit orders include shortfall funding fees inside the reviewed budget.
450
+ Use `canPrepare`, `canPlace` and `status.pending` to honor original action
451
+ recovery. Automatic funding requires the backend continuation contract. Unknown
452
+ submissions are reconciled by their original key; no financial POST is retried.
453
+ Backend-owned funding remains pending until original processed credit is proven,
454
+ including across reloads. The SDK stores no browser transaction journal.
455
+
456
+ ### Native action review
457
+
458
+ `SpiceSupply` displays the actual fee total for `feeOnlyAction` even when no
459
+ source is selected and the principal payment is zero. It omits the zero-value
460
+ payment estimate. Pass `feeFundingReserve: { asset, amount }` when principal
461
+ already in the executor must remain unavailable for fee funding.
462
+
463
+ Use `onStateChange(state: SupplyModalState)` to review the native controller's
464
+ `feeQuote`, `feePreview`, selected asset, operation key, readiness, progress and
465
+ transaction hash. Do not create a second controller to approximate its fees.
466
+ `submitDisabled` vetoes a new confirmation while native quoting remains active.
467
+
468
+ `beforeSubmit(review: SupplySubmissionReview)` can await application checks such
469
+ as a fresh position read. The SDK captures the accepted quote and rejects changed
470
+ quotes, wallets, policies, closed forms and retired components before calling
471
+ the synchronous `onSubmit` callback or starting execution. Use `onSubmit` for
472
+ application feedback that the action was accepted. The controller
473
+ holds submission readiness while those checks run, including across rerenders.
474
+ After acceptance, `submitDisabled` may become true to reflect host busy state;
475
+ it does not cancel that accepted execution. Application checks
476
+ must still reject revoked consent in their `beforeSubmit` callback.
477
+
478
+ Return the application receipt-verification promise from `onSuccess`. A failed
479
+ application update uses the existing finalization retry without submitting the
480
+ financial action again.
481
+
482
+ ### Native limit order funding
483
+
484
+ Without `combineSourceBalances: true`, orders can register unfunded and the SDK
485
+ does not deposit wallet funds. The reviewed funding choice stays with that order
486
+ if the host changes its option later.
487
+
488
+ Use `useSpiceLimitOrders({ combineSourceBalances: true }).prepareOrder` to enable
489
+ wallet funding, review its result, then pass that exact result to `signOrder` and
490
+ its returned request to `placeOrder`. `grossAmount` in
491
+ the input is the total cash budget. Preparation deducts any automatic funding
492
+ fee before constructing the order. The prepared `grossAmount` includes the
493
+ order's execution fees, `amountIn` is the swap input, and `feeAmount` is the
494
+ order's execution fee total. The requested `minimumOutput` stays fixed.
495
+
496
+ When available escrow cash does not cover that budget, `funding` describes the
497
+ SDK's same-chain embedded-wallet deposit: `source` identifies its token, chain,
498
+ owner and location; `sourceSpendCap` caps its debit; `depositAmount` is the cash
499
+ credit; and `feeAmount` is the funding fee. All funding amounts use that source's
500
+ decimals. Review both fee totals in the same confirmation. The inclusive cash
501
+ budget is `prepared.grossAmount + (prepared.funding?.feeAmount ?? 0n)`.
502
+
503
+ `placeOrder` validates current cash and backend order reservations, executes the
504
+ accepted native deposit, awaits its successful destination receipt and usable
505
+ cash credit, then registers the captured signed order. Its `status` reports
506
+ funding, credit and placement progress. Use `status.message` for outcome text;
507
+ `status.error` retains the original diagnostic error. Funding is never repeated
508
+ for the same signed request, including after an ambiguous result. An interrupted
509
+ unregistered order leaves confirmed funding as ordinary cash inventory. Check
510
+ wallet activity and the backend order list before creating another order.
511
+ Changing wallets or provider policy retires prepared and signed requests. No
512
+ browser transaction journal or parallel recovery tracker is required.
513
+
514
+ ### Conditional Limit/Stop orders
515
+
516
+ `useSpiceLimitOrders({ combineSourceBalances: true }).conditional` bridges
517
+ `prepareOrder(input, condition, fundingPolicy, triggerForCash?)`, `sign(prepared)`
518
+ and `register(signed)` to the conditional service. Use `"cash-first"` for an
519
+ inclusive cash budget with same-chain wallet shortfall funding, or
520
+ `"execution-balances"` for a fixed-input swap using the existing conditional
521
+ swap planner. The host owns the evaluator criteria and chosen policy.
522
+
523
+ For cash-first orders, `fees.amount` includes execution and upfront funding
524
+ fees, `fundingFeeAmount` identifies the funding portion, and `swapAmountIn`
525
+ is the resulting fixed swap input. `triggerForCash`, when supplied, receives
526
+ the gross execution budget after the funding fee; encode that amount into the
527
+ signed evaluator criteria. Preparation and conditional signing never deposit
528
+ funds. Registration uses the same funding, receipt, credit and pending-outcome
529
+ controller as native limit orders; consume the parent `status` and
530
+ `refreshStatus`. A signed amendment (`condition.replacesIntentId`) never creates
531
+ a new funding deposit. Backend validation must enforce amendment ownership and
532
+ claim races.
533
+
534
+ The root export `CONDITIONAL_INTENT_UNTIL_CANCELLED` is the only accepted expiry
535
+ beyond the normal 30-day window. Pass it as `condition.expiresAt` and
536
+ `Number(CONDITIONAL_INTENT_UNTIL_CANCELLED)` as `input.expiresAt`. The service and
537
+ evaluator must support that exact expiry and the selected trigger kind.
538
+ This bridge does not add bundles, sequences or deferred Supply creation.
539
+
540
+ ### Fee funding for funded actions
541
+
542
+ Set `feeFunding: ["input", "proceeds", "balance"]` on `useSpiceSupply`,
543
+ `SpiceSupply`, `useSpiceAction`, `useSpiceLock` or `SpiceLock` to use the shared
544
+ hierarchy for wallet-funded actions on the destination chain. This applies to
545
+ arbitrary protocol calls: swaps, deposits, staking, lending and repayments.
546
+ Direct payment precedes conversion **within each tier**. Existing defaults remain
547
+ unchanged; `feeFunding: []` retains the existing selected-source path.
548
+
549
+ - `amountDirection: "input-inclusive"` offers the selected budget as input.
550
+ Fees reduce that input and the SDK requotes the conversion before building
551
+ protocol calls. The builder must honour the amount passed to it.
552
+ - `"input"` preserves the selected principal; `"output"` preserves the exact
553
+ payment or repayment. Neither offers required principal to the input tier.
554
+ - `actionProceeds: { token, resolve }` declares an amount remaining in the
555
+ executor **after all protocol calls**. Conversion output that is deposited,
556
+ staked, used for repayment or sent away is not available for fees. The SDK
557
+ resolves proceeds only if it reaches that tier and rechecks them before signing.
558
+ The object declaration alone does not opt a funded action in: it requires a
559
+ nonempty `feeFunding` order, preserving existing callers' selected-source planning.
560
+ - Balance fallback reserves the selected principal. Only the remaining amount
561
+ of that exact position can pay fees. `fees.sourceSpendCap` includes fee spending
562
+ from the same position, and `fees.fundingSource` reports the chosen source.
563
+
564
+ For an input-inclusive swap whose output stays in the executor,
565
+ `actionProceeds: "output"` enables the same hierarchy and declares the output as
566
+ available proceeds. If proceeds pay fees, `fees.destinationAmount` and
567
+ `quote.estimatedOutput` show the net minimum and expected output respectively.
568
+ Do not use this shortcut for calls that consume or send away the conversion output.
569
+
570
+ Local external-wallet funding still transfers the principal to the executor
571
+ first. Direct external execution keeps its native-gas path. External native Max
572
+ reserves transfer gas, and fixed-principal Max reserves execution fees.
573
+ Cross-chain and rollup **principal** routes retain their existing funding planner;
574
+ this extension does not let destination proceeds pay earlier source or bridge
575
+ costs, or add balance fallback to those routes. Custom fee orders on those routes fail
576
+ explicitly instead of silently charging a different tier. Rollup balances can still fund
577
+ fees for a local action through the existing fee-funding withdrawal leg. Standalone
578
+ `SpiceDeposit` and rollup `SpiceWithdraw` retain their distinct transfer semantics;
579
+ protocol deposits/withdrawals through the action controller use the contract above.
580
+
581
+ All paths retain fee readiness and accepted-plan validation. This capability
582
+ requires an SDK release and explicit integration opt-in; it does not upgrade
583
+ published packages or deployed apps.
584
+
585
+ ### Supply fee-estimate tolerance
586
+
587
+ `SpiceFlowProvider` defaults `feeToleranceBps` to
588
+ `20000` (200%). Clients can override it, for example:
589
+
590
+ ```tsx
591
+ <SpiceFlowProvider {...config} feeToleranceBps={100}>
592
+ {children}
593
+ </SpiceFlowProvider>
594
+ ```
595
+
596
+ `100` is 1%; `0` disables the drift allowance. Existing conservative fixed-fee
597
+ retention still applies when estimates fall. Values must be non-negative safe
598
+ integers. The allowance is relative to each accepted fee component: a fee of 100
599
+ allows a fresh estimate up to 300 at the default. A zero fee cannot become positive.
600
+
601
+ This setting covers fee convergence and pre-sign validation for user-transfer
602
+ Supply plans, including signed-fee pricing, source gas checks, stock/controlled
603
+ Supply and input-mode Lock consumers.
604
+ Within tolerance, the SDK keeps the quoted fee amounts and transaction calls;
605
+ it does not add a 200% fee buffer, increase the source spend cap, or relax swap
606
+ slippage/minimum outputs. Changing the setting invalidates prepared plans.
607
+ Backend acceptance and funding checks still apply. Exact-output Pay, fee-only
608
+ funding, deposits and backend-transfer convergence retain their separate rules.
609
+
610
+ Routed embedded withdrawals quote a 1% gas/bridge reserve, rounded up in the fee
611
+ token's raw units. It is part of the displayed fee and deducted before the
612
+ displayed receive amount; the signed calls pay those exact amounts. It does not
613
+ compound on quote refresh. Submission checks estimate drift using the same
614
+ `feeToleranceBps`, while signed
615
+ fee amounts, source cap and receive amount stay fixed. If drift exceeds the
616
+ configured tolerance, use **Refresh quote** and review the new terms before
617
+ submitting again. Same-chain withdrawals keep their existing fee policy.
618
+
619
+ The open Supply controller retains fee construction hints for at most 30 seconds
620
+ across amount edits in the same wallet, route and configuration scope. These hints
621
+ do not enable submission: the SDK rebuilds the current calls, then checks source
622
+ gas and destination fees concurrently. User-transfer source gas uses the same
623
+ configured fee tolerance; accepted amounts and source caps stay unchanged. A hint
624
+ that no longer fits falls back to full preparation. Closing the form clears hints.
625
+ Servers advertising fee validation price the already constructed destination fee
626
+ calls; older servers retain the estimate path. Cold preparation still sizes fees
627
+ from scratch. Input route quotes debounce for 100 ms; routed fee preparation adds
628
+ no second debounce. These optimizations do not establish a latency SLA.
629
+
630
+ Fee-inclusive, user-transfer Supply also prewarms when an eligible source is
631
+ selected with an empty/zero amount. It constructs a provisional quote for at most
632
+ one token, capped by the available balance, and retains only fee hints. The amount,
633
+ fee preview and executable plan remain empty. Typing can await in-flight prewarming
634
+ before validating the real amount; closing or changing wallet/configuration
635
+ cancels it. Failed provisional preparation leaves normal quoting available.
636
+ This does not apply to direct external actions, exact-output Pay, fee-only actions
637
+ or actions with explicit funding inputs/proceeds. No signature or submission occurs
638
+ during prewarming. The time available before typing determines how much work it hides.
639
+
640
+ ### Fee funding for fee-only actions
641
+
642
+ - A fee-only action (`feeOnlyAction`) runs on what the executing wallet already holds; the SDK funds only the Spicenet fees, in the chain's fee token (`destinationToken`).
643
+ - With no `selectedAsset`, the SDK picks the fee source and the user is never asked. The action's input (`actionInput`) comes first, then its proceeds (`actionProceeds`), so the fee stays inside the action the user submitted; then other balances: same-chain embedded wallet before rollup, and within each, balances already in the fee token before balances that swap into it. The first source that simulates and covers the fee wins and is reported as `fees.fundingSource`; a source whose swap has no route, or that cannot cover the fee within slippage, is skipped for the next.
644
+ - For multiple withdrawal outputs, pass `actionProceeds: { resolve: async (signal) => [{ token: token0, amount: amount0 }, { token: token1, amount: amount1 }] }`. Return each amount in its token’s base units, only for proceeds left in the execution wallet. The SDK prefers direct fee-token proceeds, then tries conversion routes for the other outputs before other balances. It rechecks the chosen token’s proceeds before signing; another output cannot cover a shortfall in an accepted plan. Existing `{ token, resolve }` declarations remain supported.
645
+ - Declare `actionInput` for every token the action consumes and honour the amount passed to `buildActionCalls`: when fees come from an input, the action is built for the remainder. Declare `actionProceeds` for a token the action leaves in the wallet. Both are optional; with neither, only balances can pay. Omit `actionProceeds` when the output is delivered to another owner.
646
+ - `feeFunding` overrides the level order per transaction, for example `["proceeds", "input", "balance"]`; the order inside the balance level is fixed. An empty list leaves the choice to the host's `selectedAsset`.
647
+ - A `selectedAsset` on a fee-only action is an explicit host choice and funds the fee from that balance as before.
648
+ - Account wallet withdrawals use this hierarchy automatically and display the chosen fee asset without a selector. Entered amounts and Max are total source-token budgets; applicable fees reduce the net received amount. Same-chain transfers retain the selected token. Choosing another supported chain routes through USDC escrow and delivers registered USDC, with the net output shown before submission. Withdraw discovers permitted embedded balances by default alongside escrow balances; `walletAssets` optionally supplies extra token metadata or an initial wallet selection. Custom `useSpiceSupply` actions that must preserve an exact principal can declare `feeFundingReserve: { asset, amount }` instead of offering that principal as `actionInput`.
649
+ - `feeOnlyAction` alone declares the action: `amountDirection` defaults to `"output"` and `paymentAmount` to `"0"`. Explicit values still win.
650
+ - `submit()` on the controller runs the executor that matches `amountDirection`. `submitSupply()` and `submitPay()` remain for existing callers.
651
+
652
+ ### Updating and releasing
653
+
654
+ Change the shared inventory/policy/controller owner and audit affected stock and custom
655
+ consumers. Use the central team's `workflow`, `ui-quality` and `shared/sdk.md` guidance;
656
+ keep skills in the skills repo rather than copying them here.
657
+
658
+ Read the central `shared/client-design-decisions.md` register before an upgrade. Map
659
+ applicable decision IDs to affected consumers and regression scenarios, and report each
660
+ result with exact candidate evidence. Preserve agreed behavior and ownership even when
661
+ types compile; a deliberate change needs an explicit product decision and migration plan.
662
+
663
+ Run focused regressions, `bun test`, `bun run typecheck` and `bun run build`, then validate
664
+ affected consumer builds and rendered/financial behavior on the exact candidate. Record
665
+ package identity, configuration, acceptance coverage and untested cases. Earlier candidate
666
+ results do not automatically apply to newer main or a new client.
667
+
668
+ If core/API changes are needed, resolve those dependencies before their UI/app consumers.
669
+ An inventory/controller-only change does not inherently require a core release. After
670
+ explicit release authorization, publish a prerelease with a non-`latest` tag, verify its
671
+ registry artifact, and pin/test that exact version in each adopting app. Stable promotion,
672
+ client deployment and docs targeting are separate release decisions. This refactor adds
673
+ no automatic npm publishing.
674
+
675
+ ### Building the Library
676
+
677
+ ```bash
678
+ bun run build
679
+ ```
680
+
681
+ ### Type Checking
682
+
683
+ ```bash
684
+ bun run typecheck
685
+ ```
686
+
687
+ CI runs this on every pull request, so a type error fails the build.
688
+
689
+ ### Formatting
690
+
691
+ ```bash
692
+ bun run format
693
+ ```
694
+
695
+ Prettier runs over staged files on commit via lint-staged. There is no ESLint
696
+ setup in this repository.
697
+
698
+ ## Component Playground
699
+
700
+ This repository includes a lightweight React playground app for viewing and testing all components without the complexity of Storybook.
701
+
702
+ ### Running the Playground
703
+
704
+ 1. Install dependencies (if not already done):
705
+
706
+ ```bash
707
+ bun install --frozen-lockfile
708
+ ```
709
+
710
+ 2. Navigate to the playground directory:
711
+
712
+ ```bash
713
+ cd playground
714
+ ```
715
+
716
+ 3. Install playground dependencies:
717
+
718
+ ```bash
719
+ bun install --frozen-lockfile
720
+ ```
721
+
722
+ 4. Start the development server:
723
+
724
+ ```bash
725
+ bun run dev
726
+ ```
727
+
728
+ The playground will open automatically at `http://localhost:3000`
729
+
730
+ ### Using the Playground
731
+
732
+ - **Left Sidebar**: Browse available components
733
+ - **Main Area**: View the selected component with different example variants
734
+ - **Example Tabs**: Switch between different states/examples for each component
735
+
736
+ ### Adding a New Component Example
737
+
738
+ To add a new example variant for a component:
739
+
740
+ 1. Open `playground/src/ComponentRegistry.tsx`
741
+ 2. Find the component's entry in the `examples` object
742
+ 3. Add a new entry to the array:
743
+ ```tsx
744
+ {
745
+ label: 'Your Example Name',
746
+ render: () => <YourComponent {...props} />,
747
+ }
748
+ ```
749
+
750
+ The playground will automatically pick up the new example and display it as a tab.
751
+
752
+ ## License
753
+
754
+ MIT
755
+
756
+ ### Stocks prerelease line
757
+
758
+ Stocks prereleases accumulate on `update/stocks-prerelease` and publish under the npm `stocks` tag (`4.23.2-stocks.N`). Continue from the latest published commit on that branch and preserve all preceding Stocks changes, including deposit discovery/loading, normalized cash conversion/recovery and combined wallet/escrow funding. Do not restart a Stocks fix from main or publish it as an isolated fix line. Consumers pin the verified exact version; eventual main integration includes the entire cumulative branch.