@xochi/widget 0.1.0 → 0.1.1

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.
package/CHANGELOG.md CHANGED
@@ -1,9 +1,12 @@
1
1
  # Changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [0.1.1] - 2026-11-20
4
4
 
5
5
  ### Fixed
6
6
 
7
+ - Default to exact Permit2 approvals, require explicit consent for unlimited approval, and identify confirmed execution failures where no funds moved (xochi-fi/xochi-widget#177).
8
+ - Adopt a host wallet that already has an account without prompting again on mobile, and request accounts before attempting a chain switch (xochi-fi/xochi-widget#178).
9
+
7
10
  - Clear the React 19 release gate with documented WalletConnect 2.26 overrides
8
11
  for npm, pnpm, and Yarn. The packed consumer requires zero React peer problems.
9
12
  Review of the Reown license remains an open legal item outside this release gate.
@@ -1,6 +1,6 @@
1
1
  import { jsxs, jsx, Fragment } from "react/jsx-runtime";
2
2
  import { useState, useEffect, useMemo } from "react";
3
- import { getErrorInfo, MAY_HAVE_MOVED_NOTICE } from "../lib/errorCategory.js";
3
+ import { getErrorInfo, MAY_HAVE_MOVED_NOTICE, NO_FUNDS_MOVED_NOTICE } from "../lib/errorCategory.js";
4
4
  function computeRemaining(retryAfter) {
5
5
  if (!retryAfter) return null;
6
6
  const diff = retryAfter - Math.floor(Date.now() / 1e3);
@@ -23,7 +23,8 @@ function ErrorDisplay({
23
23
  className = "",
24
24
  originTokens,
25
25
  errorCategory,
26
- mayHaveMoved = false
26
+ mayHaveMoved = false,
27
+ notExecuted = false
27
28
  }) {
28
29
  const errorInfo = useMemo(() => {
29
30
  if (!error) return null;
@@ -40,6 +41,7 @@ function ErrorDisplay({
40
41
  mayHaveMoved ? /* @__PURE__ */ jsx("span", { className: "error-suggestion", children: MAY_HAVE_MOVED_NOTICE.detail }) : /* @__PURE__ */ jsxs(Fragment, { children: [
41
42
  errorInfo.reason && /* @__PURE__ */ jsx("span", { className: "error-reason", children: errorInfo.reason }),
42
43
  errorInfo.suggestion && /* @__PURE__ */ jsx("span", { className: "error-suggestion", children: errorInfo.suggestion }),
44
+ notExecuted && /* @__PURE__ */ jsx("span", { className: "error-suggestion", children: NO_FUNDS_MOVED_NOTICE }),
43
45
  isWaitingForRetry && /* @__PURE__ */ jsxs("span", { className: "error-countdown", children: [
44
46
  "Retry in ",
45
47
  countdown,
@@ -48,13 +50,13 @@ function ErrorDisplay({
48
50
  ] })
49
51
  ] })
50
52
  ] }),
51
- onRetry && errorInfo.canRetry && !mayHaveMoved && /* @__PURE__ */ jsx(
53
+ onRetry && (notExecuted || errorInfo.canRetry) && !mayHaveMoved && /* @__PURE__ */ jsx(
52
54
  "button",
53
55
  {
54
56
  className: "btn btn--ghost btn--sm error-retry-btn",
55
57
  onClick: onRetry,
56
58
  disabled: isRetrying || isWaitingForRetry,
57
- children: isRetrying ? "..." : isWaitingForRetry ? `${countdown}s` : errorInfo.retryLabel ?? "Retry"
59
+ children: isRetrying ? "..." : isWaitingForRetry ? `${countdown}s` : notExecuted ? "New quote" : errorInfo.retryLabel ?? "Retry"
58
60
  }
59
61
  )
60
62
  ] });
@@ -1,5 +1,5 @@
1
1
  import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
- import { useRef, useEffect, useMemo } from "react";
2
+ import { useCallback, useRef, useEffect, useMemo } from "react";
3
3
  import { createPortal } from "react-dom";
4
4
  import { isCantonDestinationChainId, EXTENDED_CHAIN_NAMES } from "@xochi/client";
5
5
  import { buildFailureRef } from "../lib/swapFlowPhase.js";
@@ -53,7 +53,7 @@ function refusalLine(refusal, fromSymbol) {
53
53
  }
54
54
  }
55
55
  function SwapFlowModal(props) {
56
- const { open, intent, onClose } = props;
56
+ const { open, intent, onClose: closeFlow } = props;
57
57
  const tabsShown = useWidgetTabsShown();
58
58
  const {
59
59
  status,
@@ -69,6 +69,8 @@ function SwapFlowModal(props) {
69
69
  refundReason,
70
70
  permitType,
71
71
  approval,
72
+ unlimitedApproval,
73
+ setUnlimitedApproval,
72
74
  awaitingPull,
73
75
  isSigningPull,
74
76
  quoteExpiresIn,
@@ -80,6 +82,10 @@ function SwapFlowModal(props) {
80
82
  } = intent;
81
83
  const trapRef = useFocusTrap();
82
84
  const { originTokens } = useCapabilities();
85
+ const onClose = useCallback(() => {
86
+ setUnlimitedApproval(false);
87
+ closeFlow();
88
+ }, [setUnlimitedApproval, closeFlow]);
83
89
  const isSigning = status === "signing";
84
90
  const refusal = receipt.signing.kind === "refused" ? receipt.signing.refusal : null;
85
91
  const busy = receipt.signing.kind === "busy" ? receipt.signing : null;
@@ -224,6 +230,9 @@ function SwapFlowModal(props) {
224
230
  isLoading: isSigning,
225
231
  permitType,
226
232
  approval,
233
+ approvalMayNeedReset: intent.approvalMayNeedReset,
234
+ unlimitedApproval,
235
+ setUnlimitedApproval,
227
236
  quoteExpiresIn
228
237
  }
229
238
  )
@@ -357,6 +366,7 @@ function SwapFlowModal(props) {
357
366
  SwapResult,
358
367
  {
359
368
  variant: phase,
369
+ notExecuted: intent.notExecuted,
360
370
  isStealth: props.destination.type === "stealth",
361
371
  stealthPayee: props.stealthPayee,
362
372
  sendRecipientDisplay,
@@ -1,4 +1,5 @@
1
1
  import { jsxs, Fragment, jsx } from "react/jsx-runtime";
2
+ import { useId } from "react";
2
3
  import { resolvePaymentMethod, PAYMENT_METHODS, paysNoGas } from "../types/intent.js";
3
4
  import { safeBigInt, formatTokenAmount, payoutDisplayDecimals } from "../utils/format.js";
4
5
  import { extractPullAmount, destinationDisclosure, EXTENDED_CHAIN_NAMES } from "@xochi/client";
@@ -27,8 +28,13 @@ function TransactionPreview({
27
28
  isLoading,
28
29
  permitType,
29
30
  approval,
31
+ approvalMayNeedReset,
32
+ unlimitedApproval,
33
+ setUnlimitedApproval,
30
34
  quoteExpiresIn
31
35
  }) {
36
+ const approvalNoteId = useId();
37
+ const action = sendRecipientDisplay ? "send" : "swap";
32
38
  const tabsShown = useWidgetTabsShown();
33
39
  const claimInXochiApp = useClaimInXochiApp();
34
40
  const { estimateUsd, prices } = usePrices();
@@ -188,6 +194,23 @@ function TransactionPreview({
188
194
  children: paymentSummary(paymentMethod, false, approval)
189
195
  }
190
196
  )
197
+ ] }),
198
+ permitType === "permit2" && !isDepositRoute && /* @__PURE__ */ jsxs("div", { className: "tx-preview-approval", children: [
199
+ approval !== "covered" && /* @__PURE__ */ jsxs("label", { className: "tx-preview-approval-choice", children: [
200
+ /* @__PURE__ */ jsx(
201
+ "input",
202
+ {
203
+ type: "checkbox",
204
+ checked: unlimitedApproval,
205
+ onChange: (event) => setUnlimitedApproval(event.currentTarget.checked),
206
+ disabled: isLoading,
207
+ "aria-describedby": approvalNoteId
208
+ }
209
+ ),
210
+ "Unlimited approval"
211
+ ] }),
212
+ /* @__PURE__ */ jsx("p", { id: approvalNoteId, className: "tx-preview-approval-note", children: approval === "covered" ? `Existing allowance covers this ${action}. Any existing unlimited approval stays active.` : unlimitedApproval ? `Allow Permit2 to spend an unlimited amount of ${fromSymbol}. This permission remains after this ${action}.` : `Approve this ${action}’s exact amount. Later transactions may need approval gas again.` }),
213
+ approval !== "covered" && /* @__PURE__ */ jsx("p", { className: "tx-preview-approval-note", children: approvalMayNeedReset ? "An existing non-zero allowance must be reset first, requiring another approval and gas." : "A sufficient existing allowance stays active." })
191
214
  ] })
192
215
  ] })
193
216
  ] }),
@@ -199,7 +222,7 @@ function TransactionPreview({
199
222
  ] })
200
223
  ] }),
201
224
  expiryLabel && /* @__PURE__ */ jsx("p", { className: "tx-preview-expiry", children: expiryLabel }),
202
- /* @__PURE__ */ jsx("p", { className: "modal-note", children: isDepositRoute ? `Next: an address to send the ${fromSymbol} to. Nothing to sign.` : `Paid as quoted, or a full refund. ${approvalFirst === "required" ? `Next: approve ${fromSymbol} once (gas), then sign ${signCount} in the wallet.` : approvalFirst === "unknown" ? `Next: sign ${signCount} in the wallet, after a one-time approval if one is needed.` : `Next: sign ${signCount} in the wallet.`}` })
225
+ /* @__PURE__ */ jsx("p", { className: "modal-note", children: isDepositRoute ? `Next: an address to send the ${fromSymbol} to. Nothing to sign.` : `Paid as quoted, or a full refund. ${approvalFirst === "required" ? `Next: approve ${fromSymbol} (gas), then sign ${signCount} in the wallet.` : approvalFirst === "unknown" ? `Next: sign ${signCount} in the wallet, after an approval (gas) if needed.` : `Next: sign ${signCount} in the wallet.`}` })
203
226
  ] });
204
227
  }
205
228
  export {
@@ -4,7 +4,7 @@ import { sentToRecipient } from "../../pages/send/sendCopy.js";
4
4
  import { useState, useRef, useEffect } from "react";
5
5
  import { isSelectableChainId, CHAIN_SHORT_NAMES, isTronChainId, getExplorerTxUrl } from "@xochi/client";
6
6
  import { settlementTxChainId } from "../../lib/explorerLinks.js";
7
- import { getErrorInfo, MAY_HAVE_MOVED_NOTICE } from "../../lib/errorCategory.js";
7
+ import { getErrorInfo, MAY_HAVE_MOVED_NOTICE, NO_FUNDS_MOVED_NOTICE } from "../../lib/errorCategory.js";
8
8
  import { useCountdown } from "../ErrorDisplay.js";
9
9
  import { formatFailureRef, supportMailto } from "../../lib/swapFlowPhase.js";
10
10
  import { reportSwapFailure } from "../../lib/reportClient.js";
@@ -38,6 +38,7 @@ function TxLink({
38
38
  }
39
39
  function SwapResult({
40
40
  variant,
41
+ notExecuted = false,
41
42
  isStealth,
42
43
  stealthPayee,
43
44
  sendRecipientDisplay,
@@ -297,6 +298,7 @@ function SwapResult({
297
298
  ) }),
298
299
  /* @__PURE__ */ jsx("h3", { className: "swap-result__title", children: info?.message ?? (sendRecipientDisplay ? "Send failed" : "Swap failed") }),
299
300
  info?.suggestion && /* @__PURE__ */ jsx("p", { className: "swap-result__desc", children: info.suggestion }),
301
+ notExecuted && /* @__PURE__ */ jsx("p", { className: "swap-result__desc", children: NO_FUNDS_MOVED_NOTICE }),
300
302
  failureRef && !tagLookupFailure && /* @__PURE__ */ jsxs("div", { className: "swap-result__ref", children: [
301
303
  /* @__PURE__ */ jsx("code", { className: "swap-result__ref-line", children: formatFailureRef(failureRef) }),
302
304
  /* @__PURE__ */ jsxs("div", { className: "swap-result__ref-actions", children: [
@@ -306,13 +308,13 @@ function SwapResult({
306
308
  ] }),
307
309
  /* @__PURE__ */ jsxs("div", { className: "swap-result__actions", children: [
308
310
  /* @__PURE__ */ jsx("button", { className: "modal-btn modal-btn--cancel", onClick: onClose, children: "Dismiss" }),
309
- info?.canRetry !== false && /* @__PURE__ */ jsx(
311
+ (notExecuted || info?.canRetry !== false) && /* @__PURE__ */ jsx(
310
312
  "button",
311
313
  {
312
314
  className: "modal-btn modal-btn--confirm",
313
315
  onClick: onRetry,
314
316
  disabled: isWaitingForRetry,
315
- children: isWaitingForRetry ? `Try again in ${countdown}s` : info?.retryLabel ?? "Try again"
317
+ children: isWaitingForRetry ? `Try again in ${countdown}s` : notExecuted ? "New quote" : info?.retryLabel ?? "Try again"
316
318
  }
317
319
  )
318
320
  ] })
@@ -1,4 +1,4 @@
1
- import { useState, useEffect, useCallback, useMemo, useRef } from "react";
1
+ import { useState, useRef, useEffect, useCallback, useMemo } from "react";
2
2
  import { useAccount, useSignTypedData } from "wagmi";
3
3
  import { isChainId, init, POLL_INFLIGHT_STATES, view, canAllocateDepositQuote, canSignQuote, LOADING_STATES, update } from "@xochi/client";
4
4
  import { intentAPI } from "../lib/intentAPI.js";
@@ -53,6 +53,22 @@ function createRuntime(initial) {
53
53
  }
54
54
  const [after, fx] = update(model, { ...body, ...stamp });
55
55
  effects.push(...fx);
56
+ const adoptedOrder = body.type === "ResumeRequested" && after.intent !== model.intent && after.intent.intentId === body.intentId;
57
+ if (adoptedOrder || body.type === "ResetRequested" || after.intent.intentId !== rt.model.intent.intentId || after.intent.quotedAddress !== rt.model.intent.quotedAddress || effects.some((effect) => effect.type === "Api" && effect.call.op === "quote")) {
58
+ rt.executionIntentId = null;
59
+ rt.failureSubstatus = null;
60
+ }
61
+ if (effects.some(
62
+ (effect) => effect.type === "Api" && (effect.call.op === "execute" || effect.call.op === "status")
63
+ ) || adoptedOrder) {
64
+ rt.executionIntentId = after.intent.intentId;
65
+ }
66
+ if (body.type === "StatusReplied" && body.result.ok && body.result.status && !("notFound" in body.result.status) && body.result.status.status === "failed" && model.intent.status !== "failed" && after.intent.status === "failed" && after.intent.intentId !== null && after.intent.intentId === model.intent.intentId && rt.executionIntentId === after.intent.intentId) {
67
+ rt.failureSubstatus = {
68
+ intentId: after.intent.intentId,
69
+ substatus: body.result.status.substatus ?? null
70
+ };
71
+ }
56
72
  if (hostBridge) {
57
73
  for (const event of tradeEvents(model, after, body, attempted)) {
58
74
  try {
@@ -190,6 +206,8 @@ function createRuntime(initial) {
190
206
  const rt = {
191
207
  model: initial,
192
208
  live: true,
209
+ executionIntentId: null,
210
+ failureSubstatus: null,
193
211
  bindings: null,
194
212
  dispatch,
195
213
  allocate: () => new Promise((resolve) => {
@@ -244,6 +262,8 @@ function useIntent(params) {
244
262
  paused: params.paused ?? false,
245
263
  wallet: { address: address ?? null, chainId: chainId ?? null, stepwise }
246
264
  };
265
+ const { paused: _paused, wallet: _wallet, ...trade } = ctx;
266
+ const quoteKey = JSON.stringify([trade, address, chainId]);
247
267
  const ctxKey = JSON.stringify(ctx);
248
268
  const [rt] = useState(
249
269
  () => createRuntime(
@@ -261,6 +281,13 @@ function useIntent(params) {
261
281
  )
262
282
  );
263
283
  const [model, setModel] = useState(rt.model);
284
+ const approvalQuote = useRef({ quote: model.intent.quote, revision: 0 });
285
+ if (approvalQuote.current.quote !== model.intent.quote) {
286
+ approvalQuote.current = {
287
+ quote: model.intent.quote,
288
+ revision: approvalQuote.current.revision + 1
289
+ };
290
+ }
264
291
  const dispatch = rt.dispatch;
265
292
  const permit = usePermit({
266
293
  token: fromToken,
@@ -268,8 +295,22 @@ function useIntent(params) {
268
295
  pullAuthorization: model.intent.quote?.pullAuthorization,
269
296
  servedMethod: model.intent.quote?.paymentMethod,
270
297
  amount: model.intent.quotedFromAmount || model.intent.quote?.eip712Data?.message?.fromAmount || null,
271
- enabled: !isDepositOrigin
298
+ enabled: !isDepositOrigin,
299
+ approvalContext: JSON.stringify([
300
+ approvalQuote.current.revision,
301
+ model.intent.quoteId,
302
+ model.amount,
303
+ quoteKey
304
+ ])
272
305
  });
306
+ const previousCeremony = useRef({ sign: model.sign, status: model.intent.status });
307
+ useEffect(() => {
308
+ const previous = previousCeremony.current;
309
+ if (previous.status === "signing" && model.intent.status !== "signing" || previous.sign && !model.sign && (!model.awaitingPull || previous.sign.origin === "pull")) {
310
+ permit.setUnlimitedApproval(false);
311
+ }
312
+ previousCeremony.current = { sign: model.sign, status: model.intent.status };
313
+ }, [model.sign, model.awaitingPull, model.intent.status, permit.setUnlimitedApproval]);
273
314
  rt.bindings = {
274
315
  ctx,
275
316
  ctxKey,
@@ -308,14 +349,13 @@ function useIntent(params) {
308
349
  }, [raceEvents, model.clientFillMs]);
309
350
  const tier = useTierInfo(trustScore);
310
351
  const receipt = useMemo(() => view(model), [model]);
311
- const { paused: _paused, wallet: _wallet, ...trade } = ctx;
312
- const quoteKey = JSON.stringify([trade, address, chainId]);
313
352
  const previousQuoteKey = useRef(quoteKey);
314
353
  const requestQuote = useCallback(
315
354
  (amount) => {
316
355
  if (settlementAuthorized) dispatch({ type: "QuoteRequested", amount });
356
+ permit.setUnlimitedApproval(false);
317
357
  },
318
- [dispatch, quoteKey, ensureSession, settlementAuthorized]
358
+ [dispatch, quoteKey, ensureSession, settlementAuthorized, permit.setUnlimitedApproval]
319
359
  );
320
360
  const allocateDepositRoute = useCallback(
321
361
  () => settlementAuthorized ? rt.allocate() : Promise.resolve(false),
@@ -323,21 +363,27 @@ function useIntent(params) {
323
363
  );
324
364
  const sign = useCallback(() => {
325
365
  if (settlementAuthorized) dispatch({ type: "SignRequested" });
326
- }, [dispatch, settlementAuthorized]);
366
+ if (rt.model.intent.status !== "signing") permit.setUnlimitedApproval(false);
367
+ }, [dispatch, settlementAuthorized, rt, permit.setUnlimitedApproval]);
327
368
  const cancelSign = useCallback(() => {
328
369
  if (rt.model.intent.status !== "signing") return false;
370
+ permit.setUnlimitedApproval(false);
329
371
  dispatch({ type: "CancelSignRequested" });
330
372
  return rt.model.intent.status !== "signing";
331
- }, [rt, dispatch]);
373
+ }, [rt, dispatch, permit.setUnlimitedApproval]);
332
374
  const signPull = useCallback(() => {
333
375
  if (settlementAuthorized) dispatch({ type: "PullSignRequested" });
334
376
  }, [dispatch, settlementAuthorized]);
335
- const reset = useCallback(() => dispatch({ type: "ResetRequested" }), [dispatch]);
377
+ const reset = useCallback(() => {
378
+ permit.setUnlimitedApproval(false);
379
+ dispatch({ type: "ResetRequested" });
380
+ }, [dispatch, permit.setUnlimitedApproval]);
336
381
  const refreshQuote = useCallback(
337
382
  (forceRefresh = false) => {
383
+ permit.setUnlimitedApproval(false);
338
384
  if (settlementAuthorized) dispatch({ type: "RefreshRequested", forceRefresh });
339
385
  },
340
- [dispatch, settlementAuthorized]
386
+ [dispatch, settlementAuthorized, permit.setUnlimitedApproval]
341
387
  );
342
388
  useEffect(() => {
343
389
  if (previousQuoteKey.current === quoteKey) return;
@@ -385,7 +431,7 @@ function useIntent(params) {
385
431
  receivingTxHash: state.receivingTxHash,
386
432
  settlementTxHash: state.settlementTxHash,
387
433
  settlementChainId: state.settlementChainId,
388
- substatus: state.substatus,
434
+ substatus: state.status === "failed" && rt.failureSubstatus?.intentId === state.intentId ? rt.failureSubstatus.substatus : state.substatus,
389
435
  reconciling: state.reconciling,
390
436
  intentId: state.intentId,
391
437
  quoteId: state.quoteId,
@@ -396,6 +442,7 @@ function useIntent(params) {
396
442
  legsWithheld: state.legsWithheld,
397
443
  escrow: state.escrow,
398
444
  receipt,
445
+ notExecuted: state.status === "failed" && receipt.phase === "failed" && state.intentId !== null && rt.executionIntentId === state.intentId,
399
446
  // Derived state
400
447
  isLoading: LOADING_STATES.includes(state.status),
401
448
  canSign: canSignQuote(state.status, state.quote),
@@ -410,7 +457,10 @@ function useIntent(params) {
410
457
  // Approval state (origin pull, from usePermit)
411
458
  permitType: permit.permitType,
412
459
  approval: permit.approval,
460
+ approvalMayNeedReset: permit.approvalMayNeedReset,
413
461
  isApproving: permit.isApproving,
462
+ unlimitedApproval: permit.unlimitedApproval,
463
+ setUnlimitedApproval: permit.setUnlimitedApproval,
414
464
  // Actions
415
465
  requestQuote,
416
466
  allocateDepositRoute,
@@ -1,4 +1,4 @@
1
- import { useState, useMemo, useEffect, useCallback } from "react";
1
+ import { useState, useMemo, useEffect, useRef, useCallback } from "react";
2
2
  import { useAccount, usePublicClient, useWriteContract, useBytecode, useReadContract } from "wagmi";
3
3
  import { isAddress, erc20Abi, maxUint256 } from "viem";
4
4
  import { isUserRejection } from "../lib/eip712.js";
@@ -24,6 +24,7 @@ function usePermit({
24
24
  pullAuthorization,
25
25
  servedMethod,
26
26
  amount,
27
+ approvalContext = null,
27
28
  enabled = true
28
29
  }) {
29
30
  const { address } = useAccount();
@@ -42,6 +43,7 @@ function usePermit({
42
43
  );
43
44
  const servedSpender = permit2SpenderFromAuthorization(pullAuthorization);
44
45
  const foreignSpender = servedSpender !== null && servedSpender.toLowerCase() !== PERMIT2_ADDRESS.toLowerCase();
46
+ const zeroFirstApproval = chainId === 1 && token.toLowerCase() === "0xdac17f958d2ee523a2206206994597c13d831ec7";
45
47
  const readsAllowance = enabled && permitType === "permit2" && !foreignSpender && !!address && isAddress(token);
46
48
  const {
47
49
  data: allowance,
@@ -62,8 +64,49 @@ function usePermit({
62
64
  }, [allowanceError]);
63
65
  const required = amount && /^\d+$/.test(amount) ? BigInt(amount) : null;
64
66
  const approval = !enabled || permitType !== "permit2" ? "none" : foreignSpender || allowance === void 0 || allowanceError || required === null ? "unknown" : allowance >= required ? "covered" : "required";
67
+ const consentScope = JSON.stringify([
68
+ enabled,
69
+ address,
70
+ token,
71
+ chainId,
72
+ amount,
73
+ permitType,
74
+ approvalContext,
75
+ servedSpender
76
+ ]);
77
+ const scopeRef = useRef(consentScope);
78
+ const consentRef = useRef(null);
79
+ const consentRevision = useRef(0);
80
+ const lifetime = useRef({ mounted: false, generation: 0 });
81
+ const [selectedScope, setSelectedScope] = useState(null);
82
+ if (scopeRef.current !== consentScope) {
83
+ scopeRef.current = consentScope;
84
+ consentRevision.current += 1;
85
+ consentRef.current = null;
86
+ if (selectedScope !== null) setSelectedScope(null);
87
+ }
88
+ const unlimitedApproval = selectedScope === consentScope;
89
+ const setUnlimitedApproval = useCallback((enabled2) => {
90
+ consentRevision.current += 1;
91
+ const selected = enabled2 ? scopeRef.current : null;
92
+ consentRef.current = selected;
93
+ setSelectedScope(selected);
94
+ }, []);
95
+ useEffect(() => {
96
+ const active = lifetime.current;
97
+ active.mounted = true;
98
+ active.generation += 1;
99
+ return () => {
100
+ active.mounted = false;
101
+ active.generation += 1;
102
+ consentRef.current = null;
103
+ consentRevision.current += 1;
104
+ };
105
+ }, []);
65
106
  const ensureApproval = useCallback(
66
107
  async (amount2) => {
108
+ if (!lifetime.current.mounted) return false;
109
+ const generation = lifetime.current.generation;
67
110
  if (!enabled) return true;
68
111
  if (permitType !== "permit2") return true;
69
112
  if (foreignSpender) {
@@ -73,31 +116,52 @@ function usePermit({
73
116
  return false;
74
117
  }
75
118
  if (!address || !publicClient) return false;
119
+ const unlimited = consentRef.current === consentScope && required === amount2;
120
+ setUnlimitedApproval(false);
121
+ const revision = consentRevision.current;
122
+ const isCurrent = () => lifetime.current.mounted && lifetime.current.generation === generation && scopeRef.current === consentScope && consentRevision.current === revision;
76
123
  try {
77
124
  setIsApproving(true);
78
125
  const { data: current } = await refetchAllowance({ throwOnError: true });
79
126
  if (current === void 0) throw new Error("Permit2 allowance read returned nothing");
127
+ if (!isCurrent()) return false;
80
128
  if (current >= amount2) return true;
129
+ if (zeroFirstApproval && current > 0n) {
130
+ const resetHash = await writeContractAsync({
131
+ chainId,
132
+ address: token,
133
+ abi: erc20Abi,
134
+ functionName: "approve",
135
+ args: [PERMIT2_ADDRESS, 0n]
136
+ });
137
+ const resetReceipt = await publicClient.waitForTransactionReceipt({ hash: resetHash });
138
+ if (resetReceipt.status !== "success") {
139
+ throw new Error(`Permit2 allowance reset ${resetHash} reverted`);
140
+ }
141
+ if (!isCurrent()) return false;
142
+ }
81
143
  const hash = await writeContractAsync({
82
144
  chainId,
83
145
  address: token,
84
146
  abi: erc20Abi,
85
147
  functionName: "approve",
86
- args: [PERMIT2_ADDRESS, maxUint256]
148
+ args: [PERMIT2_ADDRESS, unlimited ? maxUint256 : amount2]
87
149
  });
88
150
  const receipt = await publicClient.waitForTransactionReceipt({ hash });
89
151
  await refetchAllowance();
90
152
  if (receipt.status !== "success") {
91
153
  throw new Error(`Permit2 approval ${hash} reverted`);
92
154
  }
93
- return true;
155
+ return isCurrent();
94
156
  } catch (err) {
95
157
  if (!isUserRejection(err)) {
96
158
  console.error("[usePermit] Permit2 approval failed:", err);
97
159
  }
98
160
  return false;
99
161
  } finally {
100
- setIsApproving(false);
162
+ if (lifetime.current.mounted && lifetime.current.generation === generation) {
163
+ setIsApproving(false);
164
+ }
101
165
  }
102
166
  },
103
167
  [
@@ -110,17 +174,25 @@ function usePermit({
110
174
  foreignSpender,
111
175
  servedSpender,
112
176
  refetchAllowance,
113
- writeContractAsync
177
+ writeContractAsync,
178
+ consentScope,
179
+ required,
180
+ setUnlimitedApproval,
181
+ zeroFirstApproval
114
182
  ]
115
183
  );
116
184
  const reset = useCallback(() => {
185
+ setUnlimitedApproval(false);
117
186
  setIsApproving(false);
118
187
  if (readsAllowance) void refetchAllowance();
119
- }, [readsAllowance, refetchAllowance]);
188
+ }, [readsAllowance, refetchAllowance, setUnlimitedApproval]);
120
189
  return {
121
190
  permitType,
122
191
  approval,
192
+ approvalMayNeedReset: zeroFirstApproval && approval === "required" && allowance !== void 0 && allowance > 0n,
123
193
  isApproving,
194
+ unlimitedApproval,
195
+ setUnlimitedApproval,
124
196
  ensureApproval,
125
197
  reset
126
198
  };
@@ -10,6 +10,7 @@ const MAY_HAVE_MOVED_NOTICE = {
10
10
  title: "Funds may have moved",
11
11
  detail: "This order did not complete. Check Activity before trading again."
12
12
  };
13
+ const NO_FUNDS_MOVED_NOTICE = "No funds moved. Get a new quote to try again.";
13
14
  const ERROR_ART = STATUS_GLYPH;
14
15
  const MAX_PASSTHROUGH = 100;
15
16
  const passthrough = (message) => message.length > MAX_PASSTHROUGH ? message.substring(0, MAX_PASSTHROUGH) + "..." : message;
@@ -194,6 +195,7 @@ export {
194
195
  AMOUNT_TOO_SMALL_TITLE,
195
196
  ERROR_ART,
196
197
  MAY_HAVE_MOVED_NOTICE,
198
+ NO_FUNDS_MOVED_NOTICE,
197
199
  getErrorInfo,
198
200
  isAmountTooSmall,
199
201
  supportedOriginCopy
@@ -7,7 +7,7 @@ function paymentSummary(method, hasPull, approval) {
7
7
  case "permit2":
8
8
  case "pimlico":
9
9
  case "mpp": {
10
- const gas = paysNoGas(method, approval) ? "No gas" : approval === "required" ? "Gas for a one-time approval" : "Gas only if an approval is needed";
10
+ const gas = paysNoGas(method, approval) ? "No gas" : approval === "required" ? "Gas for an approval" : "Gas only if an approval is needed";
11
11
  return hasPull ? `${gas}${sep}sign twice` : gas;
12
12
  }
13
13
  case "approval":
@@ -889,7 +889,8 @@ function SwapPanel({
889
889
  isRetrying: intent.status === "quoting",
890
890
  originTokens,
891
891
  errorCategory: quoteErrorCategory,
892
- mayHaveMoved: intent.receipt.phase === "may-have-moved"
892
+ mayHaveMoved: intent.receipt.phase === "may-have-moved",
893
+ notExecuted: intent.notExecuted
893
894
  }
894
895
  ),
895
896
  !sendRecipient && !routeBlocked && !orderOutOfBounds && !excessiveSlippage && !flowOpen && stealthRequestRejected && /* @__PURE__ */ jsxs("div", { className: "settlement-fallback", role: "status", children: [
@@ -252,10 +252,9 @@ function useSwapFlow({
252
252
  receivingTxHash: intent.receivingTxHash,
253
253
  settlementTxHash: intent.settlementTxHash,
254
254
  settlementChainId: intent.settlementChainId,
255
- // The machine keeps a failure's verdict, not its substatus. A `failed` it
256
- // does not end on `may-have-moved` is one the Worker marked `not_executed`
257
- // or one that was never sent: nothing moved, so the feed may retry it.
258
- substatus: intent.status === "failed" ? intent.receipt.phase === "may-have-moved" ? null : NOT_EXECUTED_SUBSTATUS : intent.substatus,
255
+ // Persist only the SDK's safe execution verdict. A quote refusal also
256
+ // has phase `failed`, but must not gain the feed's execution retry.
257
+ substatus: intent.status === "failed" ? intent.notExecuted ? NOT_EXECUTED_SUBSTATUS : null : intent.substatus,
259
258
  // The dispatched order's own mode (bound at confirm), never the live
260
259
  // toggle: this effect re-runs on later status/tx-hash transitions, and
261
260
  // the toggle can change in between (close the flow, tap Public, or
@@ -295,6 +294,7 @@ function useSwapFlow({
295
294
  isResumedIntent,
296
295
  intent.intentId,
297
296
  intent.status,
297
+ intent.notExecuted,
298
298
  intent.legsWithheld,
299
299
  intent.txHash,
300
300
  intent.receivingTxHash,
package/dist/styles.css CHANGED
@@ -8833,6 +8833,31 @@ html {
8833
8833
  .tx-preview-payment-value.gasless {
8834
8834
  color: var(--color-success);
8835
8835
  }
8836
+
8837
+ .tx-preview-approval {
8838
+ padding: 0.5rem 0.75rem;
8839
+ }
8840
+
8841
+ .tx-preview-approval-choice {
8842
+ display: flex;
8843
+ align-items: center;
8844
+ gap: 0.5rem;
8845
+ min-height: 44px;
8846
+ font-size: 0.8rem;
8847
+ color: var(--text-primary);
8848
+ cursor: pointer;
8849
+ }
8850
+
8851
+ .tx-preview-approval-choice input {
8852
+ accent-color: var(--color-success);
8853
+ }
8854
+
8855
+ .tx-preview-approval-note {
8856
+ margin: 0.25rem 0 0;
8857
+ font-size: 0.75rem;
8858
+ line-height: 1.5;
8859
+ color: var(--text-secondary);
8860
+ }
8836
8861
  /* Xochi - Intent Timeline Styles */
8837
8862
 
8838
8863
  .intent-timeline {
@@ -27,6 +27,8 @@ interface ErrorDisplayProps {
27
27
  * categorized copy, and never a Retry beside it.
28
28
  */
29
29
  mayHaveMoved?: boolean;
30
+ /** SDK safe failure verdict; after submission only the worker marker permits it. */
31
+ notExecuted?: boolean;
30
32
  }
31
33
  /**
32
34
  * Seconds remaining until an ABSOLUTE unix-seconds `retryAfter`, or null when the
@@ -40,5 +42,5 @@ export declare function computeRemaining(retryAfter?: number): number | null;
40
42
  * second. Shared by ErrorDisplay and the swap result view.
41
43
  */
42
44
  export declare function useCountdown(retryAfter?: number): number | null;
43
- export declare function ErrorDisplay({ error, onRetry, isRetrying, className, originTokens, errorCategory, mayHaveMoved, }: ErrorDisplayProps): import("react").JSX.Element | null;
45
+ export declare function ErrorDisplay({ error, onRetry, isRetrying, className, originTokens, errorCategory, mayHaveMoved, notExecuted, }: ErrorDisplayProps): import("react").JSX.Element | null;
44
46
  export {};
@@ -54,6 +54,9 @@ export interface IntentView {
54
54
  permitType: PermitType;
55
55
  /** Whether the pull needs an approval transaction first; the confirm copy states it. */
56
56
  approval: OriginApproval;
57
+ approvalMayNeedReset: boolean;
58
+ unlimitedApproval: boolean;
59
+ setUnlimitedApproval: (enabled: boolean) => void;
57
60
  /** Two-step signing (deep-link wallets): awaiting the user's tap for signature 2. */
58
61
  awaitingPull: boolean;
59
62
  /** The pull signature prompt (step 2) is in flight. */
@@ -84,6 +87,7 @@ export interface IntentView {
84
87
  * never off raw state.
85
88
  */
86
89
  receipt: Pick<Receipt, "phase" | "signing">;
90
+ notExecuted: boolean;
87
91
  }
88
92
  interface SwapFlowModalProps {
89
93
  open: boolean;
@@ -24,11 +24,14 @@ interface TransactionPreviewProps {
24
24
  permitType?: PermitType;
25
25
  /** Whether the pull needs an approval transaction first (usePermit, on-chain allowance). */
26
26
  approval: OriginApproval;
27
+ approvalMayNeedReset: boolean;
28
+ unlimitedApproval: boolean;
29
+ setUnlimitedApproval: (enabled: boolean) => void;
27
30
  /**
28
31
  * Seconds until the quote hard-expires. The modal pauses auto-refresh, so
29
32
  * this counts down to expiry; at 0 the modal's expired notice takes over.
30
33
  */
31
34
  quoteExpiresIn?: number | null;
32
35
  }
33
- export declare function TransactionPreview({ quote, fromAmount, fromSymbol, fromDecimals, toSymbol, toDecimals, toChainId, destination, sendRecipientDisplay, onConfirm, onCancel, isLoading, permitType, approval, quoteExpiresIn, }: TransactionPreviewProps): import("react").JSX.Element;
36
+ export declare function TransactionPreview({ quote, fromAmount, fromSymbol, fromDecimals, toSymbol, toDecimals, toChainId, destination, sendRecipientDisplay, onConfirm, onCancel, isLoading, permitType, approval, approvalMayNeedReset, unlimitedApproval, setUnlimitedApproval, quoteExpiresIn, }: TransactionPreviewProps): import("react").JSX.Element;
34
37
  export {};
@@ -3,6 +3,8 @@ import type { SelectableChainId } from "../../types/intent.js";
3
3
  import { type SwapFailureRef } from "../../lib/swapFlowPhase.js";
4
4
  interface SwapResultProps {
5
5
  variant: "success" | "refunded" | "failed" | "may-have-moved" | "pending";
6
+ /** SDK safe failure verdict; after submission only the worker marker permits it. */
7
+ notExecuted?: boolean;
6
8
  /** Stealth settlement: funds land at a one-time address the user must claim. */
7
9
  isStealth?: boolean;
8
10
  /**
@@ -62,5 +64,5 @@ interface SwapResultProps {
62
64
  /** Stealth completion handoff to the claims surface (pass-1 4.6). */
63
65
  onGoToClaims?: () => void;
64
66
  }
65
- export declare function SwapResult({ variant, isStealth, stealthPayee, sendRecipientDisplay, swapRecipientLabel, recipientTag, substatus, fromChainId, toChainId, isCrossChain, txHash, receivingTxHash, settlementTxHash, settlementChainId, receivedAmount, toSymbol, fillMs, failureRef, errorCode, errorCategory, retryAfter, refundReason, refundAddress, originTokens, onRetry, onClose, onGoToClaims, }: SwapResultProps): import("react").JSX.Element;
67
+ export declare function SwapResult({ variant, notExecuted, isStealth, stealthPayee, sendRecipientDisplay, swapRecipientLabel, recipientTag, substatus, fromChainId, toChainId, isCrossChain, txHash, receivingTxHash, settlementTxHash, settlementChainId, receivedAmount, toSymbol, fillMs, failureRef, errorCode, errorCategory, retryAfter, refundReason, refundAddress, originTokens, onRetry, onClose, onGoToClaims, }: SwapResultProps): import("react").JSX.Element;
66
68
  export {};
@@ -97,6 +97,8 @@ export interface UseIntentReturn {
97
97
  escrow: EscrowStatusData | null;
98
98
  /** What the user is told about this trade: `view(model)`. */
99
99
  receipt: Receipt;
100
+ /** Safe execution failure, never an ordinary quote refusal. */
101
+ notExecuted: boolean;
100
102
  isLoading: boolean;
101
103
  canSign: boolean;
102
104
  canAllocateDepositRoute: boolean;
@@ -105,7 +107,10 @@ export interface UseIntentReturn {
105
107
  permitType: PermitType;
106
108
  /** Whether the pull needs an approval transaction first, from the on-chain allowance. */
107
109
  approval: OriginApproval;
110
+ approvalMayNeedReset: boolean;
108
111
  isApproving: boolean;
112
+ unlimitedApproval: boolean;
113
+ setUnlimitedApproval: (enabled: boolean) => void;
109
114
  requestQuote: (amount: string) => void;
110
115
  /** Allocate the currently priced Tron route. Idempotent across transient retries. */
111
116
  allocateDepositRoute: () => Promise<boolean>;
@@ -9,7 +9,7 @@
9
9
  * is authoritative (the solver decides how it pulls); before a quote lands the
10
10
  * hook falls back to a per-token guess (erc3009 for USDC, permit2 otherwise)
11
11
  * for display only.
12
- * - For permit2, ensure the one-time on-chain ERC-20 allowance to the canonical
12
+ * - For permit2, ensure an on-chain ERC-20 allowance to the canonical
13
13
  * Permit2 contract that PermitWitnessTransferFrom requires. erc3009 (USDC)
14
14
  * pulls via ReceiveWithAuthorization and needs no approval transaction.
15
15
  * - Report whether that approval is still outstanding (`approval`), read off
@@ -42,6 +42,8 @@ export interface UsePermitParams {
42
42
  * Permit2 approval `unknown`.
43
43
  */
44
44
  amount: string | null;
45
+ /** Quote/trade identity. Changing it invalidates any unlimited consent. */
46
+ approvalContext?: string | null;
45
47
  /**
46
48
  * Whether the origin leg uses an EVM gasless pull. False for a non-EVM (Tron)
47
49
  * deposit-route origin, which has no permit/approval at all -- the hook goes
@@ -54,15 +56,19 @@ export interface UsePermitReturn {
54
56
  permitType: PermitType;
55
57
  /** Whether the pull needs an approval transaction first, from the on-chain allowance. */
56
58
  approval: OriginApproval;
59
+ /** A zero-first token may need a separate gasful allowance reset. */
60
+ approvalMayNeedReset: boolean;
57
61
  /** An approval transaction is in flight. */
58
62
  isApproving: boolean;
63
+ unlimitedApproval: boolean;
64
+ setUnlimitedApproval: (enabled: boolean) => void;
59
65
  /**
60
66
  * Ensure the origin token has a sufficient Permit2 allowance. No-op (returns
61
67
  * true) for erc3009 tokens. For permit2, refetches the allowance read that
62
- * `approval` comes from and sends a max approval if it is short, waiting for
63
- * the receipt and re-reading the allowance after it. Returns false on
64
- * rejection, revert, a non-canonical Permit2 domain or failure so the caller
65
- * can abort before signing.
68
+ * `approval` comes from and sends the exact amount if it is short (unlimited
69
+ * only with explicit, single-use consent), waiting for the receipt and
70
+ * re-reading allowance after it. Returns false on rejection, revert,
71
+ * a non-canonical Permit2 domain or failure so the caller aborts before signing.
66
72
  */
67
73
  ensureApproval: (amount: bigint) => Promise<boolean>;
68
74
  /** Clear the in-flight flag and re-read the allowance (a swap may have spent it). */
@@ -81,4 +87,4 @@ export interface UsePermitReturn {
81
87
  * `pull_authorization` remains authoritative once a quote lands.
82
88
  */
83
89
  export declare function detectPermitType(token: string, chainId: ChainId, isSmartAccount?: boolean): PermitType;
84
- export declare function usePermit({ token, chainId, pullAuthorization, servedMethod, amount, enabled, }: UsePermitParams): UsePermitReturn;
90
+ export declare function usePermit({ token, chainId, pullAuthorization, servedMethod, amount, approvalContext, enabled, }: UsePermitParams): UsePermitReturn;
@@ -30,6 +30,8 @@ export declare const MAY_HAVE_MOVED_NOTICE: {
30
30
  readonly title: "Funds may have moved";
31
31
  readonly detail: "This order did not complete. Check Activity before trading again.";
32
32
  };
33
+ /** The SDK's safe failure verdict; after submission it requires not_executed. */
34
+ export declare const NO_FUNDS_MOVED_NOTICE = "No funds moved. Get a new quote to try again.";
33
35
  /** Category -> status glyph, from the shared vocabulary (src/lib/glyphs.ts). */
34
36
  export declare const ERROR_ART: Record<string, string>;
35
37
  /**
@@ -124,7 +124,8 @@ export declare function hostWallet(bridge: HostConnection): Wallet;
124
124
  * Connect the embedding page's wallet on load when, and only when, the host
125
125
  * passed `autoConnect: true`: once per attachment of its wallet (widget-lib's
126
126
  * `onAutoConnect`). Otherwise it is an option in the connect modal like any
127
- * other wallet. Returns the unsubscribe.
127
+ * other wallet. Returns the unsubscribe. The connect adopts the host's
128
+ * connection without a prompt (the `connect` override in `hostWallet`).
128
129
  *
129
130
  * Waits until wagmi is not settling a connection. Its mount-time reconnect
130
131
  * starts from the previous page's connections, restored from storage under
package/dist/wagmi.js CHANGED
@@ -4,7 +4,7 @@ import { mainnet, arbitrum, optimism, base, polygon, gnosis } from "wagmi/chains
4
4
  import { createConnector, http } from "wagmi";
5
5
  import { getAccount, watchAccount, connect } from "wagmi/actions";
6
6
  import { injected } from "wagmi/connectors";
7
- import { defineChain, fallback } from "viem";
7
+ import { defineChain, UserRejectedRequestError, fallback } from "viem";
8
8
  import { SITE_URL as SITE_URL$1, WALLETCONNECT_PROJECT_ID, RPC_URLS, ARC_BROWSER_RPC_URL, ARC_BROWSER_ENABLED, GNOSIS_ENABLED } from "./config.js";
9
9
  import { isFirstPartyHost } from "./lib/hostBridge.js";
10
10
  const robinhood = defineChain({
@@ -84,6 +84,28 @@ function hostWallet(bridge) {
84
84
  firstPartyHost: () => isFirstPartyHost(bridge),
85
85
  isAuthorized() {
86
86
  return bridge.autoConnect() ? base2.isAuthorized.call(this) : Promise.resolve(false);
87
+ },
88
+ async connect(parameters) {
89
+ const connectBase = base2.connect;
90
+ const { chainId, ...options } = parameters ?? {};
91
+ const reconnecting = options.isReconnecting === true;
92
+ const adopt = !reconnecting && bridge.autoConnect() && (await base2.getAccounts.call(this)).length > 0;
93
+ let result = await connectBase.call(this, {
94
+ ...options,
95
+ isReconnecting: reconnecting || adopt
96
+ });
97
+ if (adopt && result.accounts.length === 0) {
98
+ result = await connectBase.call(this, options);
99
+ }
100
+ if (result.accounts.length === 0 || !chainId || result.chainId === chainId)
101
+ return result;
102
+ try {
103
+ const chain = await base2.switchChain.call(this, { chainId });
104
+ return { ...result, chainId: chain.id };
105
+ } catch (error) {
106
+ if (error.code === UserRejectedRequestError.code) throw error;
107
+ return result;
108
+ }
87
109
  }
88
110
  };
89
111
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xochi/widget",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "The complete Xochi React trading widget and lightweight iframe configurator.",
5
5
  "keywords": [
6
6
  "xochi",