@dynamic-labs/sdk-react-core 4.84.0 → 4.85.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 (51) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/package.cjs +3 -3
  3. package/package.js +3 -3
  4. package/package.json +14 -14
  5. package/src/index.cjs +2 -0
  6. package/src/index.d.ts +2 -2
  7. package/src/index.js +1 -0
  8. package/src/lib/components/SendBalanceForm/SendBalanceForm.cjs +26 -1
  9. package/src/lib/components/SendBalanceForm/SendBalanceForm.js +26 -1
  10. package/src/lib/components/SendBalancePageLayout/SendBalancePageLayout.cjs +6 -1
  11. package/src/lib/components/SendBalancePageLayout/SendBalancePageLayout.js +6 -1
  12. package/src/lib/components/SendBalancePageLayout/components/TokensBalanceDropdown/TokensBalanceDropdown.cjs +5 -1
  13. package/src/lib/components/SendBalancePageLayout/components/TokensBalanceDropdown/TokensBalanceDropdown.js +5 -1
  14. package/src/lib/context/OnrampContext/utils/getOnrampProviders.cjs +2 -6
  15. package/src/lib/context/OnrampContext/utils/getOnrampProviders.js +4 -8
  16. package/src/lib/data/api/onramp/onramp.cjs +26 -1
  17. package/src/lib/data/api/onramp/onramp.d.ts +11 -1
  18. package/src/lib/data/api/onramp/onramp.js +26 -1
  19. package/src/lib/utils/functions/onrampProviders/index.cjs +1 -0
  20. package/src/lib/utils/functions/onrampProviders/index.js +1 -0
  21. package/src/lib/utils/hooks/index.d.ts +2 -0
  22. package/src/lib/utils/hooks/useAleoAutoShieldSponsoredTokens/pollOnShielded.cjs +24 -4
  23. package/src/lib/utils/hooks/useAleoAutoShieldSponsoredTokens/pollOnShielded.d.ts +10 -2
  24. package/src/lib/utils/hooks/useAleoAutoShieldSponsoredTokens/pollOnShielded.js +24 -4
  25. package/src/lib/utils/hooks/useAleoAutoShieldSponsoredTokens/useAleoAutoShieldSponsoredTokens.cjs +14 -3
  26. package/src/lib/utils/hooks/useAleoAutoShieldSponsoredTokens/useAleoAutoShieldSponsoredTokens.d.ts +5 -1
  27. package/src/lib/utils/hooks/useAleoAutoShieldSponsoredTokens/useAleoAutoShieldSponsoredTokens.js +14 -3
  28. package/src/lib/utils/hooks/useAleoShieldedBalances/useAleoShieldedBalances.cjs +95 -10
  29. package/src/lib/utils/hooks/useAleoShieldedBalances/useAleoShieldedBalances.d.ts +18 -2
  30. package/src/lib/utils/hooks/useAleoShieldedBalances/useAleoShieldedBalances.js +96 -11
  31. package/src/lib/utils/hooks/useDynamicWaas/useDynamicWaas.cjs +4 -4
  32. package/src/lib/utils/hooks/useDynamicWaas/useDynamicWaas.js +4 -4
  33. package/src/lib/utils/hooks/usePrivateTokenBalances/index.d.ts +2 -0
  34. package/src/lib/utils/hooks/usePrivateTokenBalances/usePrivateTokenBalances.cjs +27 -0
  35. package/src/lib/utils/hooks/usePrivateTokenBalances/usePrivateTokenBalances.d.ts +24 -0
  36. package/src/lib/utils/hooks/usePrivateTokenBalances/usePrivateTokenBalances.js +23 -0
  37. package/src/lib/utils/hooks/useSyncDynamicWaas/instrumentWalletCreation.cjs +60 -0
  38. package/src/lib/utils/hooks/useSyncDynamicWaas/instrumentWalletCreation.d.ts +29 -0
  39. package/src/lib/utils/hooks/useSyncDynamicWaas/instrumentWalletCreation.js +55 -0
  40. package/src/lib/utils/hooks/useSyncDynamicWaas/useSyncDynamicWaas.cjs +14 -24
  41. package/src/lib/utils/hooks/useSyncDynamicWaas/useSyncDynamicWaas.js +14 -24
  42. package/src/lib/utils/hooks/useWalletDelegation/useWalletDelegation.cjs +19 -16
  43. package/src/lib/utils/hooks/useWalletDelegation/useWalletDelegation.d.ts +8 -0
  44. package/src/lib/utils/hooks/useWalletDelegation/useWalletDelegation.js +19 -17
  45. package/src/lib/views/TransactionConfirmationView/TransactionConfirmationView.cjs +17 -1
  46. package/src/lib/views/TransactionConfirmationView/TransactionConfirmationView.js +17 -1
  47. package/src/lib/widgets/DynamicWidget/components/ActiveWalletBalance/ActiveWalletBalance.cjs +138 -21
  48. package/src/lib/widgets/DynamicWidget/components/ActiveWalletBalance/ActiveWalletBalance.js +139 -22
  49. package/src/lib/widgets/DynamicWidget/components/ActiveWalletBalance/optimisticShield.cjs +150 -0
  50. package/src/lib/widgets/DynamicWidget/components/ActiveWalletBalance/optimisticShield.d.ts +74 -0
  51. package/src/lib/widgets/DynamicWidget/components/ActiveWalletBalance/optimisticShield.js +143 -0
@@ -127,6 +127,7 @@ require('../../views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
127
127
  require('../../../../store/state/multichainBalances.cjs');
128
128
  require('@dynamic-labs/store');
129
129
  require('../../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
130
+ var optimisticShield = require('./optimisticShield.cjs');
130
131
  var TokenBalanceList = require('./TokenBalanceList/TokenBalanceList.cjs');
131
132
 
132
133
  /** Component to display token balances for the primary wallet */
@@ -153,6 +154,57 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
153
154
  includeNativeBalance: true,
154
155
  });
155
156
  const { tokenBalances: shieldedTokenBalances, isLoading: isLoadingShielded, refetch: refetchShielded, supportsShielded, } = useAleoShieldedBalances.useAleoShieldedBalances();
157
+ // Optimistic shield ledger. A shield broadcast resolves before the
158
+ // public-balance mapping flips and well before the RecordScanner
159
+ // index reflects the new private record, so naively trusting the
160
+ // server feed shows a stale unshielded balance and an unchanged
161
+ // shielded balance for ~10–90s after the user clicks. Pushing an
162
+ // entry here deducts the burned amount from unshielded and prepends
163
+ // / bumps the matching shielded row, then `reconcileOptimisticShields`
164
+ // drops the entry as soon as either server feed catches up.
165
+ const [optimisticShields, setOptimisticShields] = React.useState([]);
166
+ const effectiveUnshieldedTokenBalances = React.useMemo(() => optimisticShield.applyOptimisticUnshieldedDeductions(unshieldedTokenBalances !== null && unshieldedTokenBalances !== void 0 ? unshieldedTokenBalances : [], optimisticShields), [unshieldedTokenBalances, optimisticShields]);
167
+ const effectiveShieldedTokenBalances = React.useMemo(() => optimisticShield.applyOptimisticShieldedAdditions(shieldedTokenBalances, optimisticShields), [shieldedTokenBalances, optimisticShields]);
168
+ // Reconcile + GC optimistic entries whenever either server feed
169
+ // updates. The reconciler is pure; we short-circuit the state write
170
+ // when nothing changed so downstream memos don't churn on every
171
+ // refresh tick.
172
+ React.useEffect(() => {
173
+ setOptimisticShields((current) => {
174
+ if (current.length === 0)
175
+ return current;
176
+ const next = optimisticShield.reconcileOptimisticShields(current, unshieldedTokenBalances !== null && unshieldedTokenBalances !== void 0 ? unshieldedTokenBalances : [], shieldedTokenBalances, Date.now());
177
+ return next.length === current.length ? current : next;
178
+ });
179
+ }, [unshieldedTokenBalances, shieldedTokenBalances]);
180
+ // Push helper used by both the manual Shield Manually CTA and the
181
+ // auto-shield hook so the optimistic UI semantics are identical
182
+ // whichever flow dispatches the broadcast.
183
+ const recordOptimisticShield = React.useCallback((info) => {
184
+ const { token, amount } = info;
185
+ const matchingShielded = shieldedTokenBalances.find((t) => token.isNative
186
+ ? Boolean(t.isNative)
187
+ : !t.isNative && t.address === token.address);
188
+ setOptimisticShields((current) => {
189
+ var _a, _b, _c, _d;
190
+ return [
191
+ ...current,
192
+ {
193
+ amount,
194
+ createdAtMs: Date.now(),
195
+ decimals: (_a = token.decimals) !== null && _a !== void 0 ? _a : 0,
196
+ isNative: Boolean(token.isNative),
197
+ logoURI: (_b = token.logoURI) !== null && _b !== void 0 ? _b : '',
198
+ name: token.name,
199
+ preShieldShieldedRaw: BigInt(Math.round((_c = matchingShielded === null || matchingShielded === void 0 ? void 0 : matchingShielded.rawBalance) !== null && _c !== void 0 ? _c : 0)),
200
+ preShieldUnshieldedRaw: BigInt(Math.round((_d = token.rawBalance) !== null && _d !== void 0 ? _d : 0)),
201
+ price: token.price,
202
+ symbol: token.symbol,
203
+ tokenAddress: token.address,
204
+ },
205
+ ];
206
+ });
207
+ }, [shieldedTokenBalances]);
156
208
  /**
157
209
  * Tab state for chains that have a shielded/unshielded split. Defaults to
158
210
  * shielded so Aleo wallets land on their primary balance type. Other
@@ -197,11 +249,22 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
197
249
  // Manually CTA, which prompts the user-paid confirmation modal.
198
250
  const { isShielding: isAutoShielding, currentlyShieldingTokenKeys: autoShieldingTokenKeys, } = useAleoAutoShieldSponsoredTokens.useAleoAutoShieldSponsoredTokens({
199
251
  accountAddress: primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address,
200
- onShielded: React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
201
- yield fetchAccountBalances(true);
202
- yield refetchShielded();
252
+ onShieldDispatched: recordOptimisticShield,
253
+ onShielded: React.useCallback(
254
+ // Parallel refresh — same reasoning as the manual shield path:
255
+ // shield ops move value across both tabs, and serializing the
256
+ // two refreshes doubled the visible latency for the Shielded
257
+ // tab in the common case.
258
+ () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
259
+ return Promise.all([fetchAccountBalances(true), refetchShielded()]).then(() => undefined);
203
260
  }), [fetchAccountBalances, refetchShielded]),
204
261
  shieldHandle: aleoShieldHandle,
262
+ // Auto-shield reads the raw server feed (not the optimistic one):
263
+ // once we deduct optimistically the to-be-shielded token drops to
264
+ // zero in the effective list, which would suppress the next
265
+ // auto-shield run before this one finishes. The auto-shield hook
266
+ // has its own per-session idempotency (`seenKeys`) so it won't
267
+ // re-fire for the same token anyway.
205
268
  unshieldedTokenBalances: unshieldedTokenBalances,
206
269
  });
207
270
  // Liveness handle for the manual post-shield poll — set to true when
@@ -214,12 +277,25 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
214
277
  isUnmountedRef.current = true;
215
278
  };
216
279
  }, []);
280
+ // Latest server-side unshielded list mirrored into a ref so the
281
+ // post-shield convergence check can read the freshest value after
282
+ // each polled refresh. `unshieldedTokenBalances` is closure-captured
283
+ // by `handleShieldToken` at callback construction time, so without
284
+ // this ref the predicate would read the pre-shield list forever and
285
+ // the poll would never exit early. Reads from the raw server feed,
286
+ // NOT the optimistic one — convergence means "on-chain effect
287
+ // observed", which is only meaningful against the actual server
288
+ // state.
289
+ const unshieldedTokenBalancesRef = React.useRef(unshieldedTokenBalances);
290
+ React.useEffect(() => {
291
+ unshieldedTokenBalancesRef.current = unshieldedTokenBalances;
292
+ }, [unshieldedTokenBalances]);
217
293
  // Token currently awaiting user-paid fee confirmation. Set when
218
294
  // Shield Manually is clicked on a token Feemaster doesn't sponsor;
219
295
  // cleared on Cancel or after the modal's Shield button dispatches.
220
296
  const [pendingShieldToken, setPendingShieldToken] = React.useState(null);
221
297
  const handleShieldToken = React.useCallback((token) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
222
- var _f;
298
+ var _f, _g;
223
299
  if (!aleoShieldHandle || shieldingAddress)
224
300
  return;
225
301
  // `rawBalance` is the atomic-units count redcoast surfaces (number).
@@ -229,6 +305,14 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
229
305
  const atomic = BigInt(Math.round((_f = token.rawBalance) !== null && _f !== void 0 ? _f : 0));
230
306
  if (atomic <= BigInt(0))
231
307
  return;
308
+ // Snapshot the pre-shield unshielded balance for the convergence
309
+ // predicate below. Aleo's `transfer_public_to_private` burns the
310
+ // public mapping value, so a successful shield must show up as a
311
+ // drop in this token's `rawBalance`. Polling exits early once
312
+ // that drop materializes — no need to keep refreshing on the
313
+ // long-tail schedule when we've already observed the on-chain
314
+ // effect.
315
+ const preShieldRawBalance = (_g = token.rawBalance) !== null && _g !== void 0 ? _g : 0;
232
316
  setShieldingAddress(token.address);
233
317
  let didBroadcast = false;
234
318
  try {
@@ -238,11 +322,22 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
238
322
  tokenAddress: token.address,
239
323
  });
240
324
  didBroadcast = true;
241
- // Refresh the unshielded list so the just-shielded balance drops to
242
- // 0 in the redcoast feed. The shielded side will pick the new
243
- // record up on its own polling once the RecordScanner indexes.
244
- yield fetchAccountBalances(true);
245
- yield refetchShielded();
325
+ // Optimistic balance update: deduct the burned amount from
326
+ // unshielded and bump (or synthesise) the matching shielded
327
+ // row before the server-side feeds catch up. Without this the
328
+ // Shield Manually CTA flickers back into view during the
329
+ // indexing tail and a fast user can issue a second shield
330
+ // that fails server-side (validator rejects the now-zero
331
+ // public balance) and looks to them like the first one
332
+ // failed.
333
+ recordOptimisticShield({ amount: atomic, token });
334
+ // Refresh both tabs in parallel. Shield moves value across the
335
+ // shielded/unshielded boundary, so both lists need to
336
+ // converge. Running them in parallel (vs. sequential) halves
337
+ // the visible refresh latency and shortens the window where
338
+ // `useTokenBalances`' `isLoading` guard could drop a
339
+ // concurrent fetch.
340
+ yield Promise.all([fetchAccountBalances(true), refetchShielded()]);
246
341
  }
247
342
  catch (err) {
248
343
  logger.logger.debug('[ActiveWalletBalance] shieldToken failed', err);
@@ -253,7 +348,7 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
253
348
  // The relay-accepted broadcast resolves *before* the
254
349
  // public→private transition finalizes on-chain, so the immediate
255
350
  // refresh above sees the pre-confirmation balance. Re-poll on the
256
- // shared backoff so the Unshielded row visibly drops to 0 and the
351
+ // shared backoff so the Unshielded row visibly drops and the
257
352
  // Shielded row picks the new record up without a manual reload.
258
353
  // Polling is best-effort — errors are swallowed inside
259
354
  // `pollOnShielded`. Skip when the broadcast itself failed; there's
@@ -261,10 +356,27 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
261
356
  if (!didBroadcast)
262
357
  return;
263
358
  yield pollOnShielded.pollOnShielded(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
264
- yield fetchAccountBalances(true);
265
- yield refetchShielded();
266
- }), () => isUnmountedRef.current);
267
- }), [aleoShieldHandle, fetchAccountBalances, refetchShielded, shieldingAddress]);
359
+ yield Promise.all([fetchAccountBalances(true), refetchShielded()]);
360
+ }), () => isUnmountedRef.current, () => {
361
+ var _a, _b;
362
+ // Convergence: the just-shielded token's unshielded raw
363
+ // balance has dropped below the pre-shield value. We read
364
+ // via the ref so we see whatever the store published after
365
+ // the most recent poll, not the closure-captured list from
366
+ // callback construction time. We don't require an exact 0
367
+ // — additional unshielded credits could land between scans;
368
+ // any decrease is sufficient evidence the burn took effect.
369
+ const current = (_a = unshieldedTokenBalancesRef.current) === null || _a === void 0 ? void 0 : _a.find((t) => t.address === token.address && t.isNative === token.isNative);
370
+ const currentRaw = (_b = current === null || current === void 0 ? void 0 : current.rawBalance) !== null && _b !== void 0 ? _b : 0;
371
+ return currentRaw < preShieldRawBalance;
372
+ });
373
+ }), [
374
+ aleoShieldHandle,
375
+ fetchAccountBalances,
376
+ recordOptimisticShield,
377
+ refetchShielded,
378
+ shieldingAddress,
379
+ ]);
268
380
  const getSecondaryAction = React.useCallback((token) => {
269
381
  // Only on the Unshielded tab, only when the connector exposes shield
270
382
  // helpers, only for tokens registered as shieldable, only for tokens
@@ -327,12 +439,12 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
327
439
  shieldingAddress,
328
440
  ]);
329
441
  const tokenBalances = React.useMemo(() => supportsShielded && activeShieldTab === 'shielded'
330
- ? shieldedTokenBalances
331
- : unshieldedTokenBalances, [
442
+ ? effectiveShieldedTokenBalances
443
+ : effectiveUnshieldedTokenBalances, [
332
444
  activeShieldTab,
333
- shieldedTokenBalances,
445
+ effectiveShieldedTokenBalances,
446
+ effectiveUnshieldedTokenBalances,
334
447
  supportsShielded,
335
- unshieldedTokenBalances,
336
448
  ]);
337
449
  const filteredTokenBalances = React.useMemo(() => (tokenBalances === null || tokenBalances === void 0 ? void 0 : tokenBalances.filter((token) => token.name)) || [], [tokenBalances]);
338
450
  const totalValue = React.useMemo(() => filteredTokenBalances.reduce((acc, token) => acc + ((token === null || token === void 0 ? void 0 : token.marketValue) || 0), 0), [filteredTokenBalances]);
@@ -375,8 +487,14 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
375
487
  setIsRefreshing(true);
376
488
  setIsSuccess(false);
377
489
  try {
378
- if (supportsShielded && activeShieldTab === 'shielded') {
379
- yield refetchShielded();
490
+ // Chains with a shielded/unshielded split (Aleo) refresh BOTH
491
+ // tabs on a single click. A shield op moves value across the
492
+ // boundary, so refreshing only the active tab leaves the other
493
+ // visibly stale — the original complaint that drove this fix.
494
+ // Other chains never had `refetchShielded` (no-op fallback) so
495
+ // they still just hit `fetchAccountBalances` here.
496
+ if (supportsShielded) {
497
+ yield Promise.all([refetchShielded(), fetchAccountBalances(true)]);
380
498
  }
381
499
  else {
382
500
  yield fetchAccountBalances(true);
@@ -400,7 +518,6 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
400
518
  fetchAccountBalances,
401
519
  refetchShielded,
402
520
  supportsShielded,
403
- activeShieldTab,
404
521
  ]);
405
522
  const primaryWalletNativeBalance = () => {
406
523
  if (!primaryWallet ||
@@ -1,7 +1,7 @@
1
1
  'use client'
2
2
  import { __awaiter } from '../../../../../../_virtual/_tslib.js';
3
3
  import { jsx, jsxs } from 'react/jsx-runtime';
4
- import { useState, useRef, useMemo, useCallback, useEffect } from 'react';
4
+ import { useState, useRef, useMemo, useEffect, useCallback } from 'react';
5
5
  import { useTranslation } from 'react-i18next';
6
6
  import '../../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
7
7
  import { useInternalDynamicContext } from '../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
@@ -123,6 +123,7 @@ import '../../views/ReceiveWalletFunds/ReceiveWalletFunds.js';
123
123
  import '../../../../store/state/multichainBalances.js';
124
124
  import '@dynamic-labs/store';
125
125
  import '../../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
126
+ import { applyOptimisticUnshieldedDeductions, applyOptimisticShieldedAdditions, reconcileOptimisticShields } from './optimisticShield.js';
126
127
  import { TokenBalanceList } from './TokenBalanceList/TokenBalanceList.js';
127
128
 
128
129
  /** Component to display token balances for the primary wallet */
@@ -149,6 +150,57 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
149
150
  includeNativeBalance: true,
150
151
  });
151
152
  const { tokenBalances: shieldedTokenBalances, isLoading: isLoadingShielded, refetch: refetchShielded, supportsShielded, } = useAleoShieldedBalances();
153
+ // Optimistic shield ledger. A shield broadcast resolves before the
154
+ // public-balance mapping flips and well before the RecordScanner
155
+ // index reflects the new private record, so naively trusting the
156
+ // server feed shows a stale unshielded balance and an unchanged
157
+ // shielded balance for ~10–90s after the user clicks. Pushing an
158
+ // entry here deducts the burned amount from unshielded and prepends
159
+ // / bumps the matching shielded row, then `reconcileOptimisticShields`
160
+ // drops the entry as soon as either server feed catches up.
161
+ const [optimisticShields, setOptimisticShields] = useState([]);
162
+ const effectiveUnshieldedTokenBalances = useMemo(() => applyOptimisticUnshieldedDeductions(unshieldedTokenBalances !== null && unshieldedTokenBalances !== void 0 ? unshieldedTokenBalances : [], optimisticShields), [unshieldedTokenBalances, optimisticShields]);
163
+ const effectiveShieldedTokenBalances = useMemo(() => applyOptimisticShieldedAdditions(shieldedTokenBalances, optimisticShields), [shieldedTokenBalances, optimisticShields]);
164
+ // Reconcile + GC optimistic entries whenever either server feed
165
+ // updates. The reconciler is pure; we short-circuit the state write
166
+ // when nothing changed so downstream memos don't churn on every
167
+ // refresh tick.
168
+ useEffect(() => {
169
+ setOptimisticShields((current) => {
170
+ if (current.length === 0)
171
+ return current;
172
+ const next = reconcileOptimisticShields(current, unshieldedTokenBalances !== null && unshieldedTokenBalances !== void 0 ? unshieldedTokenBalances : [], shieldedTokenBalances, Date.now());
173
+ return next.length === current.length ? current : next;
174
+ });
175
+ }, [unshieldedTokenBalances, shieldedTokenBalances]);
176
+ // Push helper used by both the manual Shield Manually CTA and the
177
+ // auto-shield hook so the optimistic UI semantics are identical
178
+ // whichever flow dispatches the broadcast.
179
+ const recordOptimisticShield = useCallback((info) => {
180
+ const { token, amount } = info;
181
+ const matchingShielded = shieldedTokenBalances.find((t) => token.isNative
182
+ ? Boolean(t.isNative)
183
+ : !t.isNative && t.address === token.address);
184
+ setOptimisticShields((current) => {
185
+ var _a, _b, _c, _d;
186
+ return [
187
+ ...current,
188
+ {
189
+ amount,
190
+ createdAtMs: Date.now(),
191
+ decimals: (_a = token.decimals) !== null && _a !== void 0 ? _a : 0,
192
+ isNative: Boolean(token.isNative),
193
+ logoURI: (_b = token.logoURI) !== null && _b !== void 0 ? _b : '',
194
+ name: token.name,
195
+ preShieldShieldedRaw: BigInt(Math.round((_c = matchingShielded === null || matchingShielded === void 0 ? void 0 : matchingShielded.rawBalance) !== null && _c !== void 0 ? _c : 0)),
196
+ preShieldUnshieldedRaw: BigInt(Math.round((_d = token.rawBalance) !== null && _d !== void 0 ? _d : 0)),
197
+ price: token.price,
198
+ symbol: token.symbol,
199
+ tokenAddress: token.address,
200
+ },
201
+ ];
202
+ });
203
+ }, [shieldedTokenBalances]);
152
204
  /**
153
205
  * Tab state for chains that have a shielded/unshielded split. Defaults to
154
206
  * shielded so Aleo wallets land on their primary balance type. Other
@@ -193,11 +245,22 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
193
245
  // Manually CTA, which prompts the user-paid confirmation modal.
194
246
  const { isShielding: isAutoShielding, currentlyShieldingTokenKeys: autoShieldingTokenKeys, } = useAleoAutoShieldSponsoredTokens({
195
247
  accountAddress: primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address,
196
- onShielded: useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
197
- yield fetchAccountBalances(true);
198
- yield refetchShielded();
248
+ onShieldDispatched: recordOptimisticShield,
249
+ onShielded: useCallback(
250
+ // Parallel refresh — same reasoning as the manual shield path:
251
+ // shield ops move value across both tabs, and serializing the
252
+ // two refreshes doubled the visible latency for the Shielded
253
+ // tab in the common case.
254
+ () => __awaiter(void 0, void 0, void 0, function* () {
255
+ return Promise.all([fetchAccountBalances(true), refetchShielded()]).then(() => undefined);
199
256
  }), [fetchAccountBalances, refetchShielded]),
200
257
  shieldHandle: aleoShieldHandle,
258
+ // Auto-shield reads the raw server feed (not the optimistic one):
259
+ // once we deduct optimistically the to-be-shielded token drops to
260
+ // zero in the effective list, which would suppress the next
261
+ // auto-shield run before this one finishes. The auto-shield hook
262
+ // has its own per-session idempotency (`seenKeys`) so it won't
263
+ // re-fire for the same token anyway.
201
264
  unshieldedTokenBalances: unshieldedTokenBalances,
202
265
  });
203
266
  // Liveness handle for the manual post-shield poll — set to true when
@@ -210,12 +273,25 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
210
273
  isUnmountedRef.current = true;
211
274
  };
212
275
  }, []);
276
+ // Latest server-side unshielded list mirrored into a ref so the
277
+ // post-shield convergence check can read the freshest value after
278
+ // each polled refresh. `unshieldedTokenBalances` is closure-captured
279
+ // by `handleShieldToken` at callback construction time, so without
280
+ // this ref the predicate would read the pre-shield list forever and
281
+ // the poll would never exit early. Reads from the raw server feed,
282
+ // NOT the optimistic one — convergence means "on-chain effect
283
+ // observed", which is only meaningful against the actual server
284
+ // state.
285
+ const unshieldedTokenBalancesRef = useRef(unshieldedTokenBalances);
286
+ useEffect(() => {
287
+ unshieldedTokenBalancesRef.current = unshieldedTokenBalances;
288
+ }, [unshieldedTokenBalances]);
213
289
  // Token currently awaiting user-paid fee confirmation. Set when
214
290
  // Shield Manually is clicked on a token Feemaster doesn't sponsor;
215
291
  // cleared on Cancel or after the modal's Shield button dispatches.
216
292
  const [pendingShieldToken, setPendingShieldToken] = useState(null);
217
293
  const handleShieldToken = useCallback((token) => __awaiter(void 0, void 0, void 0, function* () {
218
- var _f;
294
+ var _f, _g;
219
295
  if (!aleoShieldHandle || shieldingAddress)
220
296
  return;
221
297
  // `rawBalance` is the atomic-units count redcoast surfaces (number).
@@ -225,6 +301,14 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
225
301
  const atomic = BigInt(Math.round((_f = token.rawBalance) !== null && _f !== void 0 ? _f : 0));
226
302
  if (atomic <= BigInt(0))
227
303
  return;
304
+ // Snapshot the pre-shield unshielded balance for the convergence
305
+ // predicate below. Aleo's `transfer_public_to_private` burns the
306
+ // public mapping value, so a successful shield must show up as a
307
+ // drop in this token's `rawBalance`. Polling exits early once
308
+ // that drop materializes — no need to keep refreshing on the
309
+ // long-tail schedule when we've already observed the on-chain
310
+ // effect.
311
+ const preShieldRawBalance = (_g = token.rawBalance) !== null && _g !== void 0 ? _g : 0;
228
312
  setShieldingAddress(token.address);
229
313
  let didBroadcast = false;
230
314
  try {
@@ -234,11 +318,22 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
234
318
  tokenAddress: token.address,
235
319
  });
236
320
  didBroadcast = true;
237
- // Refresh the unshielded list so the just-shielded balance drops to
238
- // 0 in the redcoast feed. The shielded side will pick the new
239
- // record up on its own polling once the RecordScanner indexes.
240
- yield fetchAccountBalances(true);
241
- yield refetchShielded();
321
+ // Optimistic balance update: deduct the burned amount from
322
+ // unshielded and bump (or synthesise) the matching shielded
323
+ // row before the server-side feeds catch up. Without this the
324
+ // Shield Manually CTA flickers back into view during the
325
+ // indexing tail and a fast user can issue a second shield
326
+ // that fails server-side (validator rejects the now-zero
327
+ // public balance) and looks to them like the first one
328
+ // failed.
329
+ recordOptimisticShield({ amount: atomic, token });
330
+ // Refresh both tabs in parallel. Shield moves value across the
331
+ // shielded/unshielded boundary, so both lists need to
332
+ // converge. Running them in parallel (vs. sequential) halves
333
+ // the visible refresh latency and shortens the window where
334
+ // `useTokenBalances`' `isLoading` guard could drop a
335
+ // concurrent fetch.
336
+ yield Promise.all([fetchAccountBalances(true), refetchShielded()]);
242
337
  }
243
338
  catch (err) {
244
339
  logger.debug('[ActiveWalletBalance] shieldToken failed', err);
@@ -249,7 +344,7 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
249
344
  // The relay-accepted broadcast resolves *before* the
250
345
  // public→private transition finalizes on-chain, so the immediate
251
346
  // refresh above sees the pre-confirmation balance. Re-poll on the
252
- // shared backoff so the Unshielded row visibly drops to 0 and the
347
+ // shared backoff so the Unshielded row visibly drops and the
253
348
  // Shielded row picks the new record up without a manual reload.
254
349
  // Polling is best-effort — errors are swallowed inside
255
350
  // `pollOnShielded`. Skip when the broadcast itself failed; there's
@@ -257,10 +352,27 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
257
352
  if (!didBroadcast)
258
353
  return;
259
354
  yield pollOnShielded(() => __awaiter(void 0, void 0, void 0, function* () {
260
- yield fetchAccountBalances(true);
261
- yield refetchShielded();
262
- }), () => isUnmountedRef.current);
263
- }), [aleoShieldHandle, fetchAccountBalances, refetchShielded, shieldingAddress]);
355
+ yield Promise.all([fetchAccountBalances(true), refetchShielded()]);
356
+ }), () => isUnmountedRef.current, () => {
357
+ var _a, _b;
358
+ // Convergence: the just-shielded token's unshielded raw
359
+ // balance has dropped below the pre-shield value. We read
360
+ // via the ref so we see whatever the store published after
361
+ // the most recent poll, not the closure-captured list from
362
+ // callback construction time. We don't require an exact 0
363
+ // — additional unshielded credits could land between scans;
364
+ // any decrease is sufficient evidence the burn took effect.
365
+ const current = (_a = unshieldedTokenBalancesRef.current) === null || _a === void 0 ? void 0 : _a.find((t) => t.address === token.address && t.isNative === token.isNative);
366
+ const currentRaw = (_b = current === null || current === void 0 ? void 0 : current.rawBalance) !== null && _b !== void 0 ? _b : 0;
367
+ return currentRaw < preShieldRawBalance;
368
+ });
369
+ }), [
370
+ aleoShieldHandle,
371
+ fetchAccountBalances,
372
+ recordOptimisticShield,
373
+ refetchShielded,
374
+ shieldingAddress,
375
+ ]);
264
376
  const getSecondaryAction = useCallback((token) => {
265
377
  // Only on the Unshielded tab, only when the connector exposes shield
266
378
  // helpers, only for tokens registered as shieldable, only for tokens
@@ -323,12 +435,12 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
323
435
  shieldingAddress,
324
436
  ]);
325
437
  const tokenBalances = useMemo(() => supportsShielded && activeShieldTab === 'shielded'
326
- ? shieldedTokenBalances
327
- : unshieldedTokenBalances, [
438
+ ? effectiveShieldedTokenBalances
439
+ : effectiveUnshieldedTokenBalances, [
328
440
  activeShieldTab,
329
- shieldedTokenBalances,
441
+ effectiveShieldedTokenBalances,
442
+ effectiveUnshieldedTokenBalances,
330
443
  supportsShielded,
331
- unshieldedTokenBalances,
332
444
  ]);
333
445
  const filteredTokenBalances = useMemo(() => (tokenBalances === null || tokenBalances === void 0 ? void 0 : tokenBalances.filter((token) => token.name)) || [], [tokenBalances]);
334
446
  const totalValue = useMemo(() => filteredTokenBalances.reduce((acc, token) => acc + ((token === null || token === void 0 ? void 0 : token.marketValue) || 0), 0), [filteredTokenBalances]);
@@ -371,8 +483,14 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
371
483
  setIsRefreshing(true);
372
484
  setIsSuccess(false);
373
485
  try {
374
- if (supportsShielded && activeShieldTab === 'shielded') {
375
- yield refetchShielded();
486
+ // Chains with a shielded/unshielded split (Aleo) refresh BOTH
487
+ // tabs on a single click. A shield op moves value across the
488
+ // boundary, so refreshing only the active tab leaves the other
489
+ // visibly stale — the original complaint that drove this fix.
490
+ // Other chains never had `refetchShielded` (no-op fallback) so
491
+ // they still just hit `fetchAccountBalances` here.
492
+ if (supportsShielded) {
493
+ yield Promise.all([refetchShielded(), fetchAccountBalances(true)]);
376
494
  }
377
495
  else {
378
496
  yield fetchAccountBalances(true);
@@ -396,7 +514,6 @@ const ActiveWalletBalance = ({ isLoading = false, }) => {
396
514
  fetchAccountBalances,
397
515
  refetchShielded,
398
516
  supportsShielded,
399
- activeShieldTab,
400
517
  ]);
401
518
  const primaryWalletNativeBalance = () => {
402
519
  if (!primaryWallet ||
@@ -0,0 +1,150 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ // Default safety-net stale window for optimistic entries. Tuned to
7
+ // comfortably outlast the post-shield polling schedule (~106s) so
8
+ // reconciliation has a chance to fire on the real server-side state
9
+ // before the safety net trips.
10
+ const OPTIMISTIC_SHIELD_STALE_MS = 180000;
11
+ const matches = (entry, token) => {
12
+ if (entry.isNative)
13
+ return Boolean(token.isNative);
14
+ return !token.isNative && entry.tokenAddress === token.address;
15
+ };
16
+ /**
17
+ * Reduce each unshielded token's `rawBalance` by the sum of pending
18
+ * optimistic shields for the same `(address, isNative)`, clamped to 0.
19
+ * `balance` and `marketValue` scale by the same ratio so the fiat
20
+ * column doesn't disagree with the optimistic raw balance.
21
+ *
22
+ * Rows that are zeroed by the deduction are dropped from the returned
23
+ * array so they disappear immediately from the unshielded list instead
24
+ * of lingering as a `<$0.01` ghost (the per-row fiat formatter renders
25
+ * any non-positive-but-non-undefined `marketValue` as `<$0.01`, which
26
+ * looks broken when the optimistic deduction has already taken the row
27
+ * to exactly 0). Rows untouched by the optimistic shield pass through
28
+ * by reference (no copy) so downstream memos / identity comparisons
29
+ * don't churn on every render.
30
+ */
31
+ const applyOptimisticUnshieldedDeductions = (balances, optimisticShields) => {
32
+ var _a, _b;
33
+ if (optimisticShields.length === 0)
34
+ return balances;
35
+ const result = [];
36
+ for (const token of balances) {
37
+ const adjustments = optimisticShields.filter((o) => matches(o, token));
38
+ if (adjustments.length === 0) {
39
+ result.push(token);
40
+ continue;
41
+ }
42
+ const currentRaw = BigInt(Math.round((_a = token.rawBalance) !== null && _a !== void 0 ? _a : 0));
43
+ const totalAdjustment = adjustments.reduce((sum, o) => sum + o.amount, BigInt(0));
44
+ const newRaw = currentRaw > totalAdjustment ? currentRaw - totalAdjustment : BigInt(0);
45
+ // Zero-out drop: the optimistic deduction took this row to (or
46
+ // below) zero, so there is nothing useful to display. Filter it
47
+ // out rather than emit a synthetic 0-balance row — otherwise the
48
+ // `<$0.01` formatter renders it as a misleading dust value until
49
+ // the server catches up and reconciliation drops the entry.
50
+ if (newRaw <= BigInt(0))
51
+ continue;
52
+ // Ratio-scale display-units balance + fiat so they stay consistent
53
+ // with the optimistic raw value. `currentRaw === 0n` is
54
+ // unreachable here (already handled by the zero-out drop above
55
+ // via `newRaw <= 0`), but the guard remains as defence-in-depth.
56
+ const ratio = currentRaw > BigInt(0) ? Number(newRaw) / Number(currentRaw) : 0;
57
+ result.push(Object.assign(Object.assign({}, token), { balance: ((_b = token.balance) !== null && _b !== void 0 ? _b : 0) * ratio, marketValue: token.marketValue !== undefined ? token.marketValue * ratio : undefined, rawBalance: Number(newRaw), rawBalanceString: newRaw.toString() }));
58
+ }
59
+ return result;
60
+ };
61
+ /**
62
+ * Apply optimistic shield additions to the shielded balance list. For
63
+ * each optimistic shield with a matching `(address, isNative)` entry
64
+ * already in `shielded`, bump that entry; otherwise prepend a fresh
65
+ * synthesized row built from the entry's captured metadata.
66
+ *
67
+ * Returns a fresh array only when at least one optimistic shield
68
+ * applies. When `optimisticShields` is empty we pass through the
69
+ * input array by reference so consumers that compare by identity
70
+ * don't churn.
71
+ */
72
+ const applyOptimisticShieldedAdditions = (shielded, optimisticShields) => {
73
+ if (optimisticShields.length === 0)
74
+ return shielded;
75
+ const consumedIndices = new Set();
76
+ const merged = shielded.map((token) => {
77
+ var _a, _b;
78
+ const adjustments = optimisticShields.filter((o, idx) => {
79
+ if (!matches(o, token))
80
+ return false;
81
+ consumedIndices.add(idx);
82
+ return true;
83
+ });
84
+ if (adjustments.length === 0)
85
+ return token;
86
+ const totalAtomic = adjustments.reduce((sum, o) => sum + o.amount, BigInt(0));
87
+ const newRaw = BigInt(Math.round((_a = token.rawBalance) !== null && _a !== void 0 ? _a : 0)) + totalAtomic;
88
+ const decimals = (_b = token.decimals) !== null && _b !== void 0 ? _b : 0;
89
+ const denominator = Math.pow(10, decimals);
90
+ const newDisplay = Number(newRaw) / denominator;
91
+ return Object.assign(Object.assign({}, token), { balance: newDisplay, marketValue: token.price !== undefined
92
+ ? newDisplay * token.price
93
+ : token.marketValue, rawBalance: Number(newRaw), rawBalanceString: newRaw.toString() });
94
+ });
95
+ // Prepend synthesized rows for any optimistic shield that didn't
96
+ // fold into an existing shielded row above. New rows go to the top
97
+ // of the list so the just-shielded token is immediately visible.
98
+ const synthesized = [];
99
+ optimisticShields.forEach((entry, idx) => {
100
+ if (consumedIndices.has(idx))
101
+ return;
102
+ const denominator = Math.pow(10, entry.decimals);
103
+ const display = Number(entry.amount) / denominator;
104
+ const marketValue = entry.price !== undefined ? display * entry.price : undefined;
105
+ synthesized.push(Object.assign(Object.assign({ address: entry.tokenAddress, balance: display, decimals: entry.decimals, isNative: entry.isNative, logoURI: entry.logoURI, name: entry.name, rawBalance: Number(entry.amount), rawBalanceString: entry.amount.toString(), symbol: entry.symbol }, (entry.price !== undefined ? { price: entry.price } : {})), (marketValue !== undefined ? { marketValue } : {})));
106
+ });
107
+ return [...synthesized, ...merged];
108
+ };
109
+ /**
110
+ * Filter the optimistic shield list down to entries that are still
111
+ * relevant. An entry is dropped when any of:
112
+ *
113
+ * - the unshielded server feed reports a `rawBalance` strictly less
114
+ * than `preShieldUnshieldedRaw` for that token (the burn was
115
+ * observed on-chain),
116
+ * - the shielded server feed reports a `rawBalance` strictly greater
117
+ * than `preShieldShieldedRaw` for that token (the new record was
118
+ * indexed),
119
+ * - the unshielded server no longer lists the token at all (rare,
120
+ * but means the public balance is effectively zero — our
121
+ * optimistic deduct is moot),
122
+ * - the entry is older than `staleMs` (safety net for shields whose
123
+ * on-chain effect is masked by parallel inbound credits).
124
+ *
125
+ * Pure / module-scope so it's trivially unit-testable; the widget
126
+ * just calls it on every server-side balance update.
127
+ */
128
+ const reconcileOptimisticShields = (optimisticShields, unshieldedTokenBalances, shieldedTokenBalances, nowMs, staleMs = OPTIMISTIC_SHIELD_STALE_MS) => optimisticShields.filter((entry) => {
129
+ var _a, _b;
130
+ if (nowMs - entry.createdAtMs > staleMs)
131
+ return false;
132
+ const unshielded = unshieldedTokenBalances.find((t) => matches(entry, t));
133
+ if (!unshielded)
134
+ return false;
135
+ const serverUnshielded = BigInt(Math.round((_a = unshielded.rawBalance) !== null && _a !== void 0 ? _a : 0));
136
+ if (serverUnshielded < entry.preShieldUnshieldedRaw)
137
+ return false;
138
+ const shielded = shieldedTokenBalances.find((t) => matches(entry, t));
139
+ const serverShielded = shielded
140
+ ? BigInt(Math.round((_b = shielded.rawBalance) !== null && _b !== void 0 ? _b : 0))
141
+ : BigInt(0);
142
+ if (serverShielded > entry.preShieldShieldedRaw)
143
+ return false;
144
+ return true;
145
+ });
146
+
147
+ exports.OPTIMISTIC_SHIELD_STALE_MS = OPTIMISTIC_SHIELD_STALE_MS;
148
+ exports.applyOptimisticShieldedAdditions = applyOptimisticShieldedAdditions;
149
+ exports.applyOptimisticUnshieldedDeductions = applyOptimisticUnshieldedDeductions;
150
+ exports.reconcileOptimisticShields = reconcileOptimisticShields;