@funkit/connect-rn 8.0.0 → 8.1.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 (65) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/{chunk-KZOSYNGV.js → chunk-4YNYOJJK.js} +161 -1
  3. package/dist/chunk-4YNYOJJK.js.map +7 -0
  4. package/dist/{chunk-SRVRWQO6.js → chunk-75U7A2Q5.js} +26 -10
  5. package/dist/chunk-75U7A2Q5.js.map +7 -0
  6. package/dist/clients/lighter.js +1 -1
  7. package/dist/clients/nado.js +3 -3
  8. package/dist/clients/nado.js.map +2 -2
  9. package/dist/index.js +11679 -10494
  10. package/dist/index.js.map +4 -4
  11. package/dist/src/components/AssetGrid.d.ts.map +1 -1
  12. package/dist/src/components/InfoTooltip.d.ts +28 -0
  13. package/dist/src/components/InfoTooltip.d.ts.map +1 -0
  14. package/dist/src/fiat/SurfaceSlot.d.ts +8 -2
  15. package/dist/src/fiat/SurfaceSlot.d.ts.map +1 -1
  16. package/dist/src/fiat/providers/moonpay.d.ts.map +1 -1
  17. package/dist/src/flow/AddressCopiedToast.d.ts +3 -1
  18. package/dist/src/flow/AddressCopiedToast.d.ts.map +1 -1
  19. package/dist/src/flow/DepositAssetPicker.d.ts +11 -0
  20. package/dist/src/flow/DepositAssetPicker.d.ts.map +1 -0
  21. package/dist/src/flow/DepositFlowContent.d.ts +1 -1
  22. package/dist/src/flow/DepositFlowContent.d.ts.map +1 -1
  23. package/dist/src/flow/FunkitFlowProvider.d.ts.map +1 -1
  24. package/dist/src/flow/depositFlowConfig.d.ts +3 -0
  25. package/dist/src/flow/depositFlowConfig.d.ts.map +1 -1
  26. package/dist/src/flow/isLockedDeposit.d.ts +6 -0
  27. package/dist/src/flow/isLockedDeposit.d.ts.map +1 -0
  28. package/dist/src/flow/useCopiedToast.d.ts +1 -1
  29. package/dist/src/flow/useCopiedToast.d.ts.map +1 -1
  30. package/dist/src/screens/LockedTransferCryptoScreen.d.ts +19 -0
  31. package/dist/src/screens/LockedTransferCryptoScreen.d.ts.map +1 -0
  32. package/dist/src/screens/SelectChainScreen.d.ts +1 -0
  33. package/dist/src/screens/SelectChainScreen.d.ts.map +1 -1
  34. package/dist/src/screens/SelectReceiveTokenAndChainScreen.d.ts +0 -8
  35. package/dist/src/screens/SelectReceiveTokenAndChainScreen.d.ts.map +1 -1
  36. package/dist/src/screens/TokenAndChainPickerScreen.d.ts +16 -0
  37. package/dist/src/screens/TokenAndChainPickerScreen.d.ts.map +1 -0
  38. package/dist/src/swapped/SwappedScreenShell.d.ts.map +1 -1
  39. package/dist/src/transfer/clipboard.d.ts +2 -0
  40. package/dist/src/transfer/clipboard.d.ts.map +1 -1
  41. package/dist/src/transfer/depositAssets.d.ts +35 -0
  42. package/dist/src/transfer/depositAssets.d.ts.map +1 -0
  43. package/dist/src/transfer/hooks/useCopyDepositAddress.d.ts +7 -6
  44. package/dist/src/transfer/hooks/useCopyDepositAddress.d.ts.map +1 -1
  45. package/dist/src/transfer/hooks/useDepositAssets.d.ts +14 -0
  46. package/dist/src/transfer/hooks/useDepositAssets.d.ts.map +1 -0
  47. package/dist/src/transfer/hooks/useFiatExchangeRates.d.ts +1 -5
  48. package/dist/src/transfer/hooks/useFiatExchangeRates.d.ts.map +1 -1
  49. package/dist/src/transfer/hooks/useLockedTokenAmount.d.ts +10 -0
  50. package/dist/src/transfer/hooks/useLockedTokenAmount.d.ts.map +1 -0
  51. package/dist/src/transfer/lockedTokenAmount.d.ts +9 -0
  52. package/dist/src/transfer/lockedTokenAmount.d.ts.map +1 -0
  53. package/dist/src/transfer/supportedTokens.d.ts +5 -0
  54. package/dist/src/transfer/supportedTokens.d.ts.map +1 -1
  55. package/dist/src/utils/assetGrid.d.ts +5 -0
  56. package/dist/src/utils/assetGrid.d.ts.map +1 -1
  57. package/dist/src/utils/tokenAndChainPicker.d.ts +15 -0
  58. package/dist/src/utils/tokenAndChainPicker.d.ts.map +1 -0
  59. package/dist/src/withdrawal/receiveDestination.d.ts +0 -7
  60. package/dist/src/withdrawal/receiveDestination.d.ts.map +1 -1
  61. package/dist/src/withdrawal/useSourceTokenUsdPrice.d.ts +15 -2
  62. package/dist/src/withdrawal/useSourceTokenUsdPrice.d.ts.map +1 -1
  63. package/package.json +6 -5
  64. package/dist/chunk-KZOSYNGV.js.map +0 -7
  65. package/dist/chunk-SRVRWQO6.js.map +0 -7
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useFunkitIdentity
3
- } from "./chunk-KZOSYNGV.js";
3
+ } from "./chunk-4YNYOJJK.js";
4
4
  import {
5
5
  logger
6
6
  } from "./chunk-D64EJ57D.js";
@@ -52,20 +52,28 @@ function useIsStablecoin() {
52
52
  var SOURCE_TOKEN_PRICE_QUERY_KEY = "sourceTokenUsdPrice";
53
53
  var PRICE_STALE_TIME_MS = 6e4;
54
54
  var STABLECOIN_USD_PRICE = 1;
55
- function useSourceTokenUsdPrice(sourceToken) {
55
+ function useSourceTokenUsdPrice(sourceToken, {
56
+ enabled = true,
57
+ refetchInterval = false
58
+ } = {}) {
56
59
  const { apiKey } = useFunkitIdentity();
57
60
  const isStablecoin = useIsStablecoin();
58
- const isStable = isStablecoin(sourceToken.symbol);
59
- const { data } = useQuery({
61
+ const chainId = sourceToken ? String(sourceToken.chainId) : void 0;
62
+ const isStable = !!sourceToken && isStablecoin(sourceToken.symbol);
63
+ const unavailable = enabled && !!sourceToken && !isStable && !apiKey;
64
+ const query = useQuery({
60
65
  queryKey: [
61
66
  SOURCE_TOKEN_PRICE_QUERY_KEY,
62
67
  apiKey,
63
- sourceToken.chainId,
64
- sourceToken.address
68
+ chainId,
69
+ sourceToken?.address
65
70
  ],
66
71
  queryFn: async () => {
72
+ if (!sourceToken || !chainId) {
73
+ throw new Error("Missing price inputs");
74
+ }
67
75
  const info = await getAssetPriceInfoWithFallback({
68
- chainId: sourceToken.chainId,
76
+ chainId,
69
77
  assetTokenAddress: sourceToken.address,
70
78
  apiKey,
71
79
  logger
@@ -81,11 +89,19 @@ function useSourceTokenUsdPrice(sourceToken) {
81
89
  }
82
90
  return unitPrice;
83
91
  },
84
- enabled: !!apiKey && !isStable,
92
+ enabled: enabled && !!sourceToken && !isStable && !unavailable,
85
93
  staleTime: PRICE_STALE_TIME_MS,
94
+ refetchInterval: isStable ? false : refetchInterval,
86
95
  retry: false
87
96
  });
88
- return isStable ? STABLECOIN_USD_PRICE : data ?? 0;
97
+ return {
98
+ refetch: query.refetch,
99
+ data: isStable ? STABLECOIN_USD_PRICE : query.data ?? 0,
100
+ isUnavailable: unavailable,
101
+ isPending: !isStable && !unavailable && query.isPending,
102
+ isError: !isStable && (unavailable || query.isError),
103
+ isFetching: !isStable && query.isFetching
104
+ };
89
105
  }
90
106
 
91
107
  export {
@@ -94,4 +110,4 @@ export {
94
110
  useIsStablecoin,
95
111
  useSourceTokenUsdPrice
96
112
  };
97
- //# sourceMappingURL=chunk-SRVRWQO6.js.map
113
+ //# sourceMappingURL=chunk-75U7A2Q5.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/statsig/useDynamicConfig.ts", "../src/geo/useUserIpInfo.ts", "../src/withdrawal/useSourceTokenUsdPrice.ts", "../src/hooks/useIsStablecoin.ts"],
4
+ "sourcesContent": ["import {\n type DynamicConfigName,\n type DynamicConfigValue,\n useDynamicConfig as useCoreDynamicConfig,\n} from '@funkit/connect-core'\n\nimport { useUserIpInfo } from '../geo/useUserIpInfo'\n\n// RN counterpart of `@funkit/connect`'s `hooks/statsig/useDynamicConfig`. The\n// core hook takes `countryCode` as a parameter so it stays platform-agnostic;\n// this wrapper threads the user's IP-derived `alpha2` (Moonpay/ipapi) so\n// country-conditional variant configs (e.g. `enableswappeddeposit`) resolve\n// against the real region instead of falling to their default branch.\nexport type { DynamicConfigName, DynamicConfigValue }\n\nexport const useDynamicConfig = <Name extends DynamicConfigName>(\n name: Name,\n options?: {\n bypassCountryCode?: boolean\n },\n): DynamicConfigValue<Name> => {\n const { userIpInfo } = useUserIpInfo()\n return useCoreDynamicConfig(name, {\n bypassCountryCode: options?.bypassCountryCode,\n countryCode: userIpInfo?.alpha2,\n })\n}\n", "import { useUserIpInfo as useCoreUserIpInfo } from '@funkit/connect-core'\n\nimport { useFunkitIdentity } from '../identity/IdentityContext'\nimport { logger } from '../logging/logger'\n\n// Re-exported so existing RN importers (isCountryBlocked, the flow hooks, tests)\n// keep their type source unchanged after the fetch logic moved to core.\nexport type {\n FunkitUserIpInfo,\n UseUserIpInfoResult,\n} from '@funkit/connect-core'\n\n// Thin RN wrapper over the shared core `useUserIpInfo` (V1 PR13 moved the\n// Moonpay\u2192ipapi fetch logic there so web and RN don't duplicate it). RN is\n// login-agnostic, so the lookup always runs (`enabled: true`); web's wrapper\n// gates on `isUserLoggedIn` instead. `apiKey` lets the core hook reach the\n// first-party geo endpoint; the chain it picks is Statsig-driven.\nexport function useUserIpInfo() {\n const { apiKey } = useFunkitIdentity()\n\n // Login-agnostic + session-stable: always run, never go stale. The fiat\n // rail prices a US buyer by state, so a stateless answer is worth a second\n // provider here; web reads only the country and leaves this off.\n return useCoreUserIpInfo({\n logger,\n apiKey,\n enabled: true,\n staleTime: Number.POSITIVE_INFINITY,\n requireState: true,\n })\n}\n", "import { getAssetPriceInfoWithFallback } from '@funkit/connect-core'\nimport { useQuery } from '@tanstack/react-query'\n\nimport { useIsStablecoin } from '../hooks/useIsStablecoin'\nimport { useFunkitIdentity } from '../identity/IdentityContext'\nimport { logger } from '../logging/logger'\n\nconst SOURCE_TOKEN_PRICE_QUERY_KEY = 'sourceTokenUsdPrice'\n\n/** Long enough that typing doesn't refetch, short enough to stay honest. */\nconst PRICE_STALE_TIME_MS = 60_000\n\n/** What a dollar stablecoin is worth, without asking anyone. */\nconst STABLECOIN_USD_PRICE = 1\n\n/**\n * Spot USD price of the source token, for the USD floor and ceiling the host\n * configures (`getMinWithdrawalUSD` / `getMaxWithdrawalUSD`).\n *\n * A dollar stablecoin is priced from its symbol and never fetched, as web's\n * `useAssetAddressPrice` does \u2014 it is the common withdrawal source, and the\n * amount screen was waiting on a round trip to be told a dollar is a dollar.\n *\n * `0` means \"unknown\", which is what the core validator reads as \"no price\" \u2014\n * so a failed or in-flight lookup leaves the USD limits inert rather than\n * judging an amount against a made-up rate. Per-token limits and the balance\n * check are unaffected either way.\n *\n * Not every source has a price: Lighter's L2 assets are addressed by index, not\n * by an ERC-20 funkit's price API knows, so that lookup 404s and core's Relay\n * fallback is what prices them.\n */\nexport function useSourceTokenUsdPrice(\n sourceToken:\n | { chainId: string | number; address: string; symbol: string }\n | undefined,\n {\n enabled = true,\n refetchInterval = false,\n }: {\n enabled?: boolean\n refetchInterval?: number | false\n } = {},\n) {\n const { apiKey } = useFunkitIdentity()\n const isStablecoin = useIsStablecoin()\n const chainId = sourceToken ? String(sourceToken.chainId) : undefined\n const isStable = !!sourceToken && isStablecoin(sourceToken.symbol)\n const unavailable = enabled && !!sourceToken && !isStable && !apiKey\n\n const query = useQuery({\n queryKey: [\n SOURCE_TOKEN_PRICE_QUERY_KEY,\n apiKey,\n chainId,\n sourceToken?.address,\n ],\n queryFn: async () => {\n if (!sourceToken || !chainId) {\n throw new Error('Missing price inputs')\n }\n const info = await getAssetPriceInfoWithFallback({\n chainId,\n assetTokenAddress: sourceToken.address as `0x${string}`,\n apiKey,\n logger,\n })\n const unitPrice = info.unitPrice\n if (!Number.isFinite(unitPrice) || unitPrice <= 0) {\n // Reported here, not on read: a cached bad price would otherwise warn\n // on every render. A non-positive price would silently scale every USD\n // limit to nothing.\n logger.warn('connect-rn:withdrawal:unusable_source_price', {\n chainId: sourceToken.chainId,\n address: sourceToken.address,\n unitPrice,\n })\n return 0\n }\n return unitPrice\n },\n enabled: enabled && !!sourceToken && !isStable && !unavailable,\n staleTime: PRICE_STALE_TIME_MS,\n refetchInterval: isStable ? false : refetchInterval,\n retry: false,\n })\n\n return {\n refetch: query.refetch,\n data: isStable ? STABLECOIN_USD_PRICE : (query.data ?? 0),\n isUnavailable: unavailable,\n isPending: !isStable && !unavailable && query.isPending,\n isError: !isStable && (unavailable || query.isError),\n isFetching: !isStable && query.isFetching,\n }\n}\n", "import { useCallback } from 'react'\nimport { useDynamicConfig } from '../statsig/useDynamicConfig'\n\nexport type IsStablecoinFn = (symbol: string) => boolean\n\nexport function useIsStablecoin(): IsStablecoinFn {\n const stablecoinSymbols = useDynamicConfig('stablecoinsymbols')\n return useCallback(\n (symbol: string) =>\n stablecoinSymbols.some((stable) =>\n symbol.toLowerCase().includes(stable.toLowerCase()),\n ),\n [stablecoinSymbols],\n )\n}\n"],
5
+ "mappings": ";;;;;;;;AAAA;AAAA,EAGE,oBAAoB;AAAA,OACf;;;ACJP,SAAS,iBAAiB,yBAAyB;AAiB5C,SAAS,gBAAgB;AAC9B,QAAM,EAAE,OAAO,IAAI,kBAAkB;AAKrC,SAAO,kBAAkB;AAAA,IACvB;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT,WAAW,OAAO;AAAA,IAClB,cAAc;AAAA,EAChB,CAAC;AACH;;;ADfO,IAAM,mBAAmB,CAC9B,MACA,YAG6B;AAC7B,QAAM,EAAE,WAAW,IAAI,cAAc;AACrC,SAAO,qBAAqB,MAAM;AAAA,IAChC,mBAAmB,SAAS;AAAA,IAC5B,aAAa,YAAY;AAAA,EAC3B,CAAC;AACH;;;AE1BA,SAAS,qCAAqC;AAC9C,SAAS,gBAAgB;;;ACDzB,SAAS,mBAAmB;AAKrB,SAAS,kBAAkC;AAChD,QAAM,oBAAoB,iBAAiB,mBAAmB;AAC9D,SAAO;AAAA,IACL,CAAC,WACC,kBAAkB;AAAA,MAAK,CAAC,WACtB,OAAO,YAAY,EAAE,SAAS,OAAO,YAAY,CAAC;AAAA,IACpD;AAAA,IACF,CAAC,iBAAiB;AAAA,EACpB;AACF;;;ADPA,IAAM,+BAA+B;AAGrC,IAAM,sBAAsB;AAG5B,IAAM,uBAAuB;AAmBtB,SAAS,uBACd,aAGA;AAAA,EACE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1,7 +1,7 @@
1
1
  import {
2
2
  useFunkitIdentity,
3
3
  useFunkitTranslation
4
- } from "../chunk-KZOSYNGV.js";
4
+ } from "../chunk-4YNYOJJK.js";
5
5
  import {
6
6
  logger
7
7
  } from "../chunk-D64EJ57D.js";
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  useSourceTokenUsdPrice
3
- } from "../chunk-SRVRWQO6.js";
3
+ } from "../chunk-75U7A2Q5.js";
4
4
  import {
5
5
  i18n,
6
6
  useFunkitTranslation
7
- } from "../chunk-KZOSYNGV.js";
7
+ } from "../chunk-4YNYOJJK.js";
8
8
  import {
9
9
  logger
10
10
  } from "../chunk-D64EJ57D.js";
@@ -368,7 +368,7 @@ function useNadoWithdrawal({
368
368
  symbol: sourceOption.symbol,
369
369
  decimals: sourceOption.decimals
370
370
  };
371
- const sourceTokenUsdPrice = useSourceTokenUsdPrice(sourceToken);
371
+ const { data: sourceTokenUsdPrice } = useSourceTokenUsdPrice(sourceToken);
372
372
  const invalidateMaxWithdrawable = useInvalidateNadoMaxWithdrawable();
373
373
  const hasMaximum = maxWithdrawableX18 !== void 0;
374
374
  if (!nado || !config?.withdrawalWallet || !subaccount || !isFeeSettled || !isMaxSettled) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../clients/nado/useNadoWithdrawal.ts", "../../clients/nado/nadoWithdrawalConfig.ts", "../../clients/nado/withdrawalSubmit.ts", "../../clients/nado/withdrawalErrors.ts"],
4
- "sourcesContent": ["import {\n getMaxEnterableAmount,\n getSequencerFee,\n resolveNadoSubaccount,\n useInvalidateNadoMaxWithdrawable,\n useNadoFeeRates,\n useNadoMaxWithdrawable,\n} from '@funkit/connect-core/clients/nado'\nimport { useMemo, useRef } from 'react'\nimport type { Hex } from 'viem'\n\nimport type {\n WithdrawalFlowConfig,\n WithdrawalMethodOption,\n} from '../../src/flow/withdrawalFlowConfig'\nimport { logger } from '../../src/logging/logger'\nimport { useFunkitTranslation } from '../../src/providers/FunkitI18nProvider'\nimport { useSourceTokenUsdPrice } from '../../src/withdrawal/useSourceTokenUsdPrice'\nimport {\n NADO_METHOD_ID,\n NADO_MIN_WITHDRAWAL_TOKENS,\n NADO_MOBILE_SPOT_LEVERAGE,\n NADO_USDT0_SOURCE_TOKEN,\n type NadoWithdrawalFlowConfig,\n} from './nadoWithdrawalConfig'\nimport { createNadoWithdrawalSubmit } from './withdrawalSubmit'\n\n/**\n * The Nado method to hand `beginWithdrawal`, carrying the config it runs, so the\n * SDK never holds Nado config itself.\n *\n * Empty until the subaccount id can be built \u2014 every Nado query is keyed on it.\n */\nexport function useNadoWithdrawal({\n nado,\n config,\n}: {\n nado: NadoWithdrawalFlowConfig | undefined\n /** Title, callbacks and wallet carry over. Absent until the host has one. */\n config: WithdrawalFlowConfig | undefined\n}): WithdrawalMethodOption[] {\n const { t } = useFunkitTranslation()\n const sourceOption = NADO_USDT0_SOURCE_TOKEN\n const subaccount = useNadoSubaccount(nado)\n\n const { data: feeRates, isFetched: isFeeSettled } = useNadoFeeRates({\n sender: subaccount,\n logger,\n })\n // Asked rather than derived from a spot balance: only Nado's own accounting\n // sees margin, locked collateral and account health.\n const { data: maxWithdrawableX18, isFetched: isMaxSettled } =\n useNadoMaxWithdrawable({\n productId: subaccount ? sourceOption.productId : undefined,\n sender: subaccount,\n spotLeverage: NADO_MOBILE_SPOT_LEVERAGE,\n logger,\n })\n // `beginWithdrawal` snapshots the config, so the getter reads a ref rather\n // than the value of the render it was built in.\n const maxWithdrawableRef = useRef(maxWithdrawableX18)\n maxWithdrawableRef.current = maxWithdrawableX18\n\n const sequencerFee = getSequencerFee(feeRates, sourceOption)\n const sourceToken = {\n chainId: sourceOption.tokenChainId,\n address: sourceOption.tokenAddress,\n symbol: sourceOption.symbol,\n decimals: sourceOption.decimals,\n }\n const sourceTokenUsdPrice = useSourceTokenUsdPrice(sourceToken)\n const invalidateMaxWithdrawable = useInvalidateNadoMaxWithdrawable()\n // `isFetched` is true after a failure too, so settled is not known.\n const hasMaximum = maxWithdrawableX18 !== undefined\n\n // Withheld while the first answer is still in flight, and permanently without\n // a wallet \u2014 Nado withdrawals are signed by the user, so there is no method\n // to offer rather than one that fails at submit.\n if (\n !nado ||\n !config?.withdrawalWallet ||\n !subaccount ||\n !isFeeSettled ||\n !isMaxSettled\n ) {\n return []\n }\n\n return [\n {\n id: NADO_METHOD_ID,\n title: t('withdrawCrypto.methodTitle'),\n subtitle: t('withdrawCrypto.methodSubtitle'),\n config: {\n ...config,\n sourceToken,\n sourceTokens: [{ token: sourceToken, iconSrc: sourceOption.iconSrc }],\n // Unknown is not zero \u2014 omitted, validation skips the check rather\n // than rejecting every amount. Submit re-reads the real maximum.\n withdrawalSourceTokenBalance: hasMaximum\n ? () =>\n getMaxEnterableAmount({\n maxWithdrawableX18: maxWithdrawableRef.current,\n sequencerFee: sequencerFee.x18,\n decimals: sourceOption.decimals,\n })\n : undefined,\n defaultReceiveToken: config.defaultReceiveToken ?? sourceOption.symbol,\n getMinWithdrawalAmount:\n config.getMinWithdrawalAmount ?? (() => NADO_MIN_WITHDRAWAL_TOKENS),\n // Taken off the amount before quoting, and billed as source-chain cost.\n quoteInputFeeTokens: sequencerFee.tokenAmount,\n extraSourceGasUsd: sequencerFee.tokenAmount * sourceTokenUsdPrice,\n submitWithdrawal: createNadoWithdrawalSubmit({\n nado,\n subaccount,\n sourceToken: sourceOption,\n wallet: config.withdrawalWallet,\n onWithdrawn: invalidateMaxWithdrawable,\n }),\n },\n },\n ]\n}\n\nfunction useNadoSubaccount(\n nado: NadoWithdrawalFlowConfig | undefined,\n): Hex | undefined {\n const { walletAddress, subaccountName } = nado ?? {}\n return useMemo(\n () => resolveNadoSubaccount({ walletAddress, subaccountName, logger }),\n [walletAddress, subaccountName],\n )\n}\n", "import {\n INK_CHAIN_ID,\n type NadoWithdrawalSourceOption,\n} from '@funkit/connect-core/clients/nado'\nimport type { Address } from 'viem'\n\n/** Row identity, routing and logs. */\nexport const NADO_METHOD_ID = 'nado'\n\n/**\n * Sent explicitly on every call: Nado treats an absent `spot_leverage` as\n * `true`, so omitting it would open a margin position for a user with no\n * affordance to see or close one.\n */\nexport const NADO_MOBILE_SPOT_LEVERAGE = false\n\n/**\n * Below this the sequencer fee and routing costs eat most of the withdrawal.\n * Token units, calibrated for USDT0 \u2014 the only source mobile ships.\n */\nexport const NADO_MIN_WITHDRAWAL_TOKENS = 4\n\n/**\n * The only source mobile withdraws. Web has the integrator declare the whole\n * product table because it offers every listing; mobile ships the one it\n * supports rather than making every host restate Nado's ids.\n */\nexport const NADO_USDT0_SOURCE_TOKEN: NadoWithdrawalSourceOption = {\n productId: 0,\n symbol: 'USDT0',\n decimals: 6,\n tokenAddress: '0x0200C29006150606B650577BBE7B6248F58470c1',\n tokenChainId: `${INK_CHAIN_ID}`,\n iconSrc: undefined,\n}\n\n/**\n * Nado withdrawal, as the host configures it. Mirrors web's\n * `NadoWithdrawalConfig` where the concepts overlap, minus the borrow toggle and\n * the multi-product picker.\n */\nexport interface NadoWithdrawalFlowConfig {\n /** Must also be the signer \u2014 Nado rejects linked signers on withdrawals. */\n walletAddress: Address\n /** Omit for the default subaccount. Packed with the wallet; capped at 12 bytes. */\n subaccountName?: string\n /**\n * Awaited after the user taps Withdraw, before anything is minted or signed.\n * Throw to abort.\n */\n onBeforeSign?: () => Promise<void> | void\n}\n", "/**\n * The Nado withdrawal money path: generate a Fun deposit address, sign Nado's\n * gasless `withdraw_collateral_v2` with `sendTo` pointing at it, and submit.\n *\n * Port of web's `createNadoWithdrawalCallback` over {@link WithdrawalClient}.\n * Two differences from web:\n * - The amount arrives **already net** of the sequencer fee, where web's\n * callback deducts it itself. Deducting again would short the user a fee.\n * - Borrowing is never offered, so `spot_leverage` is always `false`.\n *\n * Re-submitting belongs to the gateway, which reuses the signed nonce; a retry\n * from here would mint a fresh one and withdraw twice.\n */\n\nimport {\n type FunAddress,\n NADO_API_KEY,\n initializeCheckoutTokenTransferAddress,\n} from '@funkit/api-base'\nimport {\n type WithdrawalClient,\n isAddressEquivalent,\n isUserRejectedError,\n normalizeRecipientAddress,\n safeBigInt,\n toWithdrawalAmountBaseUnit,\n} from '@funkit/connect-core'\nimport {\n INK_CHAIN_ID,\n NADO_WITHDRAWAL_ACTION_TYPE,\n NadoGatewayError,\n type NadoWithdrawalSourceOption,\n NadoWithdrawalUnconfirmedError,\n buildWithdrawCollateralV2TypedData,\n executeNadoWithdrawCollateralV2,\n getNadoMaxWithdrawable,\n getNadoTxNonce,\n isExpectedNadoWithdrawalFailure,\n x18ToRawBaseUnit,\n} from '@funkit/connect-core/clients/nado'\nimport type { Address, Hex } from 'viem'\n\nimport type { CustomWithdrawalSubmission } from '../../src/flow/withdrawalFlowConfig'\nimport { i18n } from '../../src/locales/i18n'\nimport { logger } from '../../src/logging/logger'\nimport type { NadoWithdrawalFlowConfig } from './nadoWithdrawalConfig'\nimport { NADO_MOBILE_SPOT_LEVERAGE } from './nadoWithdrawalConfig'\nimport { toNadoWithdrawalErrorMessage } from './withdrawalErrors'\n\n/** Steps are logged on failure so a support ticket names the stage it died at. */\ntype NadoWithdrawalStep =\n | 'validate'\n | 'beforeSign'\n | 'switchChain'\n | 'uda'\n | 'sign'\n | 'execute'\n\n/** A wiring bug, not a user-correctable condition; the user gets the generic line. */\nclass NadoWithdrawalInputError extends Error {}\n\n/** Already logged where it was raised, so the catch neither re-logs nor escalates. */\nclass NadoWithdrawalUserError extends Error {}\n\nexport interface NadoWithdrawalSubmitContext {\n nado: NadoWithdrawalFlowConfig\n /** Packed id of the subaccount being debited (`buildNadoSubaccountId`). */\n subaccount: Hex\n sourceToken: NadoWithdrawalSourceOption\n /** The host's signer. Nado needs `signTypedData`; a client without it fails. */\n wallet: WithdrawalClient\n /** Drops the cached max, or a follow-up withdrawal opens on a stale balance. */\n onWithdrawn: () => void\n}\n\n/**\n * The `submitWithdrawal` the crypto rail runs in place of a relay execution.\n * Resolves with the deposit address Nado was told to send to \u2014 nothing of ours\n * goes on-chain, so there is no transaction to return.\n */\nexport function createNadoWithdrawalSubmit({\n nado,\n subaccount,\n sourceToken,\n wallet,\n onWithdrawn,\n}: NadoWithdrawalSubmitContext) {\n return async ({\n recipientAddress,\n destinationToken,\n amountTokenUnits,\n }: CustomWithdrawalSubmission): Promise<{ depositAddress: Address }> => {\n const { walletAddress, onBeforeSign } = nado\n const { productId, decimals } = sourceToken\n const recipientAddr = normalizeRecipientAddress(recipientAddress)\n\n let step: NadoWithdrawalStep = 'validate'\n\n try {\n // Already net of the fee \u2014 see the note at the top of the file.\n const netRawAmount = toWithdrawalAmountBaseUnit(\n amountTokenUnits,\n decimals,\n )\n if (netRawAmount <= 0n) {\n logger.warn('nado:withdrawal:amountTooLow', {\n productId,\n amountTokenUnits,\n })\n throw new NadoWithdrawalUserError(\n i18n.t('withdrawNado.errorAmountTooLow'),\n )\n }\n\n logger.info('nado:withdrawal:start', {\n productId,\n spotLeverage: NADO_MOBILE_SPOT_LEVERAGE,\n decimals,\n amountTokenUnits,\n toChainId: destinationToken.chainId,\n toToken: destinationToken.address,\n recipientAddress: recipientAddr,\n })\n\n await assertWithinMaxWithdrawable({\n subaccount,\n productId,\n decimals,\n netRawAmount,\n })\n\n // Before the deposit address: a declined switch or swapped account would\n // otherwise orphan one.\n step = 'beforeSign'\n try {\n await onBeforeSign?.()\n } catch (error) {\n // The documented way for a host to abort \u2014 a user choice, not a failure.\n const message = error instanceof Error ? error.message : String(error)\n logger.warn('nado:withdrawal:abortedByHost', {\n walletAddress,\n errorMessage: message,\n })\n throw new NadoWithdrawalUserError(message)\n }\n\n step = 'switchChain'\n await ensureWalletOnInk(wallet)\n await assertOwnerIsSigner({ walletAddress, wallet })\n\n step = 'uda'\n const { depositAddr } = await initializeCheckoutTokenTransferAddress({\n apiKey: NADO_API_KEY,\n // The owner wallet is the stable per-user id, and is what the completion\n // tracker later looks the arrival up by.\n userId: walletAddress,\n recipientAddr,\n toChainId: destinationToken.chainId,\n toTokenAddress: destinationToken.address,\n sourceOfFund: `balance|nado|${walletAddress}`,\n // Attribution only \u2014 forces a separate address from Nado deposits.\n actionType: NADO_WITHDRAWAL_ACTION_TYPE,\n logger,\n clientMetadata: { isWithdrawal: true },\n })\n logger.info('nado:withdrawal:udaGenerated', {\n depositAddr,\n productId,\n recipientAddress: recipientAddr,\n })\n\n step = 'sign'\n // Immediately before signing: a stale nonce is rejected outright.\n const nonce = await getNadoTxNonce(walletAddress, { logger })\n const signature = await signWithdrawal({\n wallet,\n subaccount,\n productId,\n netRawAmount,\n nonce,\n sendTo: depositAddr as Address,\n })\n logger.info('nado:withdrawal:signed', {\n nonce: nonce.toString(),\n depositAddr,\n productId,\n })\n\n step = 'execute'\n try {\n await executeNadoWithdrawCollateralV2(\n {\n sender: subaccount,\n productId,\n amount: netRawAmount,\n nonce,\n sendTo: depositAddr,\n signature,\n spotLeverage: NADO_MOBILE_SPOT_LEVERAGE,\n },\n { logger },\n )\n } catch (error) {\n // An unconfirmed execute may still have debited. Re-reading Nado is\n // right either way; keeping the cached maximum is only right if it did\n // not land.\n if (error instanceof NadoWithdrawalUnconfirmedError) {\n onWithdrawn()\n }\n throw error\n }\n logger.info('nado:withdrawal:executeSubmitted', {\n nonce: nonce.toString(),\n depositAddr,\n productId,\n netRawAmount: netRawAmount.toString(),\n })\n onWithdrawn()\n\n return { depositAddress: depositAddr as Address }\n } catch (error) {\n throw toThrownWithdrawalError(error, {\n step,\n walletAddress,\n subaccount,\n recipientAddress: recipientAddr,\n toChainId: destinationToken.chainId,\n })\n }\n }\n}\n\n/**\n * The signature is off-chain and gasless, but wallets reject an\n * `eth_signTypedData_v4` whose domain chainId isn't the active chain \u2014 so the\n * wallet still has to sit on Ink to sign it.\n */\nasync function ensureWalletOnInk(wallet: WithdrawalClient): Promise<void> {\n const connectedChainId = await wallet.getChainId()\n if (connectedChainId === INK_CHAIN_ID) {\n return\n }\n logger.info('nado:withdrawal:switchingChain', {\n fromChainId: connectedChainId,\n })\n try {\n await wallet.switchChain(INK_CHAIN_ID)\n } catch (error) {\n if (isUserRejectedError(error)) {\n throw error\n }\n logger.warn('nado:withdrawal:switchChainFailed', {\n fromChainId: connectedChainId,\n errorMessage: error instanceof Error ? error.message : String(error),\n })\n throw new NadoWithdrawalUserError(i18n.t('withdrawCrypto.errorSwitchChain'))\n }\n}\n\n/** Nado only honors owner-wallet signatures, so a switched account must fail loudly. */\nasync function assertOwnerIsSigner({\n walletAddress,\n wallet,\n}: {\n walletAddress: Address\n wallet: WithdrawalClient\n}): Promise<void> {\n const connectedAddress = wallet.address()\n if (\n connectedAddress &&\n isAddressEquivalent({\n firstAddress: connectedAddress,\n secondAddress: walletAddress,\n })\n ) {\n return\n }\n logger.warn('nado:withdrawal:signerMismatch', {\n walletAddress,\n connectedAddress: connectedAddress ?? null,\n })\n throw new NadoWithdrawalUserError(i18n.t('withdrawNado.errorSignerMismatch'))\n}\n\n/** `signTypedData` is optional on the client, but Nado cannot withdraw without it. */\nasync function signWithdrawal({\n wallet,\n subaccount,\n productId,\n netRawAmount,\n nonce,\n sendTo,\n}: {\n wallet: WithdrawalClient\n subaccount: Hex\n productId: number\n netRawAmount: bigint\n nonce: bigint\n sendTo: Address\n}): Promise<Hex> {\n if (!wallet.signTypedData) {\n throw new NadoWithdrawalInputError(\n 'withdrawalWallet cannot signTypedData, which Nado withdrawals require',\n )\n }\n const signature = await wallet.signTypedData(\n buildWithdrawCollateralV2TypedData({\n sender: subaccount,\n productId,\n amount: netRawAmount,\n nonce,\n sendTo,\n }),\n )\n return signature as Hex\n}\n\n/**\n * Race backstop, not the primary gate: the amount screen already blocks this,\n * but account health can move between render and submit \u2014 and catching it here\n * saves a wallet prompt and a burnt nonce. `max_withdrawable` is already net of\n * the fee, so it compares against the signed amount.\n */\nasync function assertWithinMaxWithdrawable({\n subaccount,\n productId,\n decimals,\n netRawAmount,\n}: {\n subaccount: Hex\n productId: number\n decimals: number\n netRawAmount: bigint\n}): Promise<void> {\n const maxWithdrawableX18 = await getNadoMaxWithdrawable(\n { productId, sender: subaccount, spotLeverage: NADO_MOBILE_SPOT_LEVERAGE },\n { logger },\n )\n const maxRawAmount = x18ToRawBaseUnit(\n safeBigInt(maxWithdrawableX18, 0n),\n decimals,\n )\n if (netRawAmount <= maxRawAmount) {\n return\n }\n logger.warn('nado:withdrawal:exceedsMaxWithdrawable', {\n productId,\n netRawAmount: netRawAmount.toString(),\n maxRawAmount: maxRawAmount.toString(),\n })\n // No figure in the copy: on a race it is stale by the time it is read.\n throw new NadoWithdrawalUserError(i18n.t('withdrawNado.errorBalanceChanged'))\n}\n\n/**\n * Failure \u2192 what the user sees, and at what severity.\n *\n * - Recovered states (declined signature, precondition rejections, expected\n * gateway codes) log at WARN; ERROR is reserved for what is worth alerting on.\n * - Gateway failures map to Nado copy; everything else already carries a usable\n * message and passes through.\n */\nfunction toThrownWithdrawalError(\n error: unknown,\n context: {\n step: NadoWithdrawalStep\n walletAddress: Address\n subaccount: Hex\n recipientAddress: FunAddress\n toChainId: string\n },\n): unknown {\n const logContext = {\n ...context,\n nadoErrorCode:\n error instanceof NadoGatewayError ? (error.errorCode ?? null) : null,\n nadoErrorKind: error instanceof NadoGatewayError ? error.kind : null,\n errorMessage: error instanceof Error ? error.message : String(error),\n }\n // A user choice, not a failure to alert on.\n if (isUserRejectedError(error)) {\n logger.warn('nado:withdrawal:rejected', logContext)\n return error\n }\n // Already warned where it was raised, with the context only that site had.\n if (error instanceof NadoWithdrawalUserError) {\n return error\n }\n if (error instanceof NadoWithdrawalInputError) {\n logger.error('nado:withdrawal:invalidInput', error, logContext)\n return new Error(i18n.t('withdrawCrypto.errorGeneric'))\n }\n // Already logged at the gateway; the copy steers away from a retry.\n if (error instanceof NadoWithdrawalUnconfirmedError) {\n return new Error(toNadoWithdrawalErrorMessage(error))\n }\n if (!(error instanceof NadoGatewayError)) {\n logger.error(\n 'nado:withdrawal:failed',\n error instanceof Error ? error : new Error(String(error)),\n logContext,\n )\n return error\n }\n if (isExpectedNadoWithdrawalFailure(error)) {\n logger.warn('nado:withdrawal:gatewayRejected', logContext)\n } else {\n logger.error('nado:withdrawal:gatewayFailed', error, logContext)\n }\n return new Error(toNadoWithdrawalErrorMessage(error))\n}\n", "/**\n * Nado failure code \u2192 the copy the user sees. Core classifies; each platform\n * owns its map, and an exhaustive `Record` fails the build on a new code.\n *\n * Thunks rather than a key lookup: `t(KEYS[code])` passes a non-literal to `t`,\n * which `.ast-grep/rules/i18n-t-string-literal.yml` rejects.\n */\n\nimport {\n type NadoWithdrawalFailure,\n toNadoWithdrawalFailure,\n} from '@funkit/connect-core/clients/nado'\n\nimport { i18n } from '../../src/locales/i18n'\n\nconst MESSAGE_FOR: Record<NadoWithdrawalFailure, () => string> = {\n generic: () => i18n.t('withdrawCrypto.errorGeneric'),\n network: () => i18n.t('withdrawNado.errorNetwork'),\n rateLimited: () => i18n.t('withdrawNado.errorRateLimited'),\n // Borrowing is off on mobile, so this only ever means the balance moved.\n exceedsBorrowLimit: () => i18n.t('withdrawNado.errorBalanceChanged'),\n invalidNonce: () => i18n.t('withdrawNado.errorInvalidNonce'),\n noPriorDeposit: () => i18n.t('withdrawNado.errorNoPriorDeposit'),\n withdrawRisk: () => i18n.t('withdrawNado.errorWithdrawRisk'),\n unconfirmed: () => i18n.t('withdrawNado.errorUnconfirmed'),\n}\n\nexport function toNadoWithdrawalErrorMessage(error: unknown): string {\n return MESSAGE_FOR[toNadoWithdrawalFailure(error)]()\n}\n"],
5
- "mappings": ";;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS,cAAc;;;ACRhC;AAAA,EACE;AAAA,OAEK;AAIA,IAAM,iBAAiB;AAOvB,IAAM,4BAA4B;AAMlC,IAAM,6BAA6B;AAOnC,IAAM,0BAAsD;AAAA,EACjE,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,cAAc;AAAA,EACd,cAAc,GAAG,YAAY;AAAA,EA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e,IAAI,QAAQ,CAAC;AACnD,SAAO;AAAA,IACL,MAAM,sBAAsB,EAAE,eAAe,gBAAgB,OAAO,CAAC;AAAA,IACrE,CAAC,eAAe,cAAc;AAAA,EAChC;AACF;",
4
+ "sourcesContent": ["import {\n getMaxEnterableAmount,\n getSequencerFee,\n resolveNadoSubaccount,\n useInvalidateNadoMaxWithdrawable,\n useNadoFeeRates,\n useNadoMaxWithdrawable,\n} from '@funkit/connect-core/clients/nado'\nimport { useMemo, useRef } from 'react'\nimport type { Hex } from 'viem'\n\nimport type {\n WithdrawalFlowConfig,\n WithdrawalMethodOption,\n} from '../../src/flow/withdrawalFlowConfig'\nimport { logger } from '../../src/logging/logger'\nimport { useFunkitTranslation } from '../../src/providers/FunkitI18nProvider'\nimport { useSourceTokenUsdPrice } from '../../src/withdrawal/useSourceTokenUsdPrice'\nimport {\n NADO_METHOD_ID,\n NADO_MIN_WITHDRAWAL_TOKENS,\n NADO_MOBILE_SPOT_LEVERAGE,\n NADO_USDT0_SOURCE_TOKEN,\n type NadoWithdrawalFlowConfig,\n} from './nadoWithdrawalConfig'\nimport { createNadoWithdrawalSubmit } from './withdrawalSubmit'\n\n/**\n * The Nado method to hand `beginWithdrawal`, carrying the config it runs, so the\n * SDK never holds Nado config itself.\n *\n * Empty until the subaccount id can be built \u2014 every Nado query is keyed on it.\n */\nexport function useNadoWithdrawal({\n nado,\n config,\n}: {\n nado: NadoWithdrawalFlowConfig | undefined\n /** Title, callbacks and wallet carry over. Absent until the host has one. */\n config: WithdrawalFlowConfig | undefined\n}): WithdrawalMethodOption[] {\n const { t } = useFunkitTranslation()\n const sourceOption = NADO_USDT0_SOURCE_TOKEN\n const subaccount = useNadoSubaccount(nado)\n\n const { data: feeRates, isFetched: isFeeSettled } = useNadoFeeRates({\n sender: subaccount,\n logger,\n })\n // Asked rather than derived from a spot balance: only Nado's own accounting\n // sees margin, locked collateral and account health.\n const { data: maxWithdrawableX18, isFetched: isMaxSettled } =\n useNadoMaxWithdrawable({\n productId: subaccount ? sourceOption.productId : undefined,\n sender: subaccount,\n spotLeverage: NADO_MOBILE_SPOT_LEVERAGE,\n logger,\n })\n // `beginWithdrawal` snapshots the config, so the getter reads a ref rather\n // than the value of the render it was built in.\n const maxWithdrawableRef = useRef(maxWithdrawableX18)\n maxWithdrawableRef.current = maxWithdrawableX18\n\n const sequencerFee = getSequencerFee(feeRates, sourceOption)\n const sourceToken = {\n chainId: sourceOption.tokenChainId,\n address: sourceOption.tokenAddress,\n symbol: sourceOption.symbol,\n decimals: sourceOption.decimals,\n }\n const { data: sourceTokenUsdPrice } = useSourceTokenUsdPrice(sourceToken)\n const invalidateMaxWithdrawable = useInvalidateNadoMaxWithdrawable()\n // `isFetched` is true after a failure too, so settled is not known.\n const hasMaximum = maxWithdrawableX18 !== undefined\n\n // Withheld while the first answer is still in flight, and permanently without\n // a wallet \u2014 Nado withdrawals are signed by the user, so there is no method\n // to offer rather than one that fails at submit.\n if (\n !nado ||\n !config?.withdrawalWallet ||\n !subaccount ||\n !isFeeSettled ||\n !isMaxSettled\n ) {\n return []\n }\n\n return [\n {\n id: NADO_METHOD_ID,\n title: t('withdrawCrypto.methodTitle'),\n subtitle: t('withdrawCrypto.methodSubtitle'),\n config: {\n ...config,\n sourceToken,\n sourceTokens: [{ token: sourceToken, iconSrc: sourceOption.iconSrc }],\n // Unknown is not zero \u2014 omitted, validation skips the check rather\n // than rejecting every amount. Submit re-reads the real maximum.\n withdrawalSourceTokenBalance: hasMaximum\n ? () =>\n getMaxEnterableAmount({\n maxWithdrawableX18: maxWithdrawableRef.current,\n sequencerFee: sequencerFee.x18,\n decimals: sourceOption.decimals,\n })\n : undefined,\n defaultReceiveToken: config.defaultReceiveToken ?? sourceOption.symbol,\n getMinWithdrawalAmount:\n config.getMinWithdrawalAmount ?? (() => NADO_MIN_WITHDRAWAL_TOKENS),\n // Taken off the amount before quoting, and billed as source-chain cost.\n quoteInputFeeTokens: sequencerFee.tokenAmount,\n extraSourceGasUsd: sequencerFee.tokenAmount * sourceTokenUsdPrice,\n submitWithdrawal: createNadoWithdrawalSubmit({\n nado,\n subaccount,\n sourceToken: sourceOption,\n wallet: config.withdrawalWallet,\n onWithdrawn: invalidateMaxWithdrawable,\n }),\n },\n },\n ]\n}\n\nfunction useNadoSubaccount(\n nado: NadoWithdrawalFlowConfig | undefined,\n): Hex | undefined {\n const { walletAddress, subaccountName } = nado ?? {}\n return useMemo(\n () => resolveNadoSubaccount({ walletAddress, subaccountName, logger }),\n [walletAddress, subaccountName],\n )\n}\n", "import {\n INK_CHAIN_ID,\n type NadoWithdrawalSourceOption,\n} from '@funkit/connect-core/clients/nado'\nimport type { Address } from 'viem'\n\n/** Row identity, routing and logs. */\nexport const NADO_METHOD_ID = 'nado'\n\n/**\n * Sent explicitly on every call: Nado treats an absent `spot_leverage` as\n * `true`, so omitting it would open a margin position for a user with no\n * affordance to see or close one.\n */\nexport const NADO_MOBILE_SPOT_LEVERAGE = false\n\n/**\n * Below this the sequencer fee and routing costs eat most of the withdrawal.\n * Token units, calibrated for USDT0 \u2014 the only source mobile ships.\n */\nexport const NADO_MIN_WITHDRAWAL_TOKENS = 4\n\n/**\n * The only source mobile withdraws. Web has the integrator declare the whole\n * product table because it offers every listing; mobile ships the one it\n * supports rather than making every host restate Nado's ids.\n */\nexport const NADO_USDT0_SOURCE_TOKEN: NadoWithdrawalSourceOption = {\n productId: 0,\n symbol: 'USDT0',\n decimals: 6,\n tokenAddress: '0x0200C29006150606B650577BBE7B6248F58470c1',\n tokenChainId: `${INK_CHAIN_ID}`,\n iconSrc: undefined,\n}\n\n/**\n * Nado withdrawal, as the host configures it. Mirrors web's\n * `NadoWithdrawalConfig` where the concepts overlap, minus the borrow toggle and\n * the multi-product picker.\n */\nexport interface NadoWithdrawalFlowConfig {\n /** Must also be the signer \u2014 Nado rejects linked signers on withdrawals. */\n walletAddress: Address\n /** Omit for the default subaccount. Packed with the wallet; capped at 12 bytes. */\n subaccountName?: string\n /**\n * Awaited after the user taps Withdraw, before anything is minted or signed.\n * Throw to abort.\n */\n onBeforeSign?: () => Promise<void> | void\n}\n", "/**\n * The Nado withdrawal money path: generate a Fun deposit address, sign Nado's\n * gasless `withdraw_collateral_v2` with `sendTo` pointing at it, and submit.\n *\n * Port of web's `createNadoWithdrawalCallback` over {@link WithdrawalClient}.\n * Two differences from web:\n * - The amount arrives **already net** of the sequencer fee, where web's\n * callback deducts it itself. Deducting again would short the user a fee.\n * - Borrowing is never offered, so `spot_leverage` is always `false`.\n *\n * Re-submitting belongs to the gateway, which reuses the signed nonce; a retry\n * from here would mint a fresh one and withdraw twice.\n */\n\nimport {\n type FunAddress,\n NADO_API_KEY,\n initializeCheckoutTokenTransferAddress,\n} from '@funkit/api-base'\nimport {\n type WithdrawalClient,\n isAddressEquivalent,\n isUserRejectedError,\n normalizeRecipientAddress,\n safeBigInt,\n toWithdrawalAmountBaseUnit,\n} from '@funkit/connect-core'\nimport {\n INK_CHAIN_ID,\n NADO_WITHDRAWAL_ACTION_TYPE,\n NadoGatewayError,\n type NadoWithdrawalSourceOption,\n NadoWithdrawalUnconfirmedError,\n buildWithdrawCollateralV2TypedData,\n executeNadoWithdrawCollateralV2,\n getNadoMaxWithdrawable,\n getNadoTxNonce,\n isExpectedNadoWithdrawalFailure,\n x18ToRawBaseUnit,\n} from '@funkit/connect-core/clients/nado'\nimport type { Address, Hex } from 'viem'\n\nimport type { CustomWithdrawalSubmission } from '../../src/flow/withdrawalFlowConfig'\nimport { i18n } from '../../src/locales/i18n'\nimport { logger } from '../../src/logging/logger'\nimport type { NadoWithdrawalFlowConfig } from './nadoWithdrawalConfig'\nimport { NADO_MOBILE_SPOT_LEVERAGE } from './nadoWithdrawalConfig'\nimport { toNadoWithdrawalErrorMessage } from './withdrawalErrors'\n\n/** Steps are logged on failure so a support ticket names the stage it died at. */\ntype NadoWithdrawalStep =\n | 'validate'\n | 'beforeSign'\n | 'switchChain'\n | 'uda'\n | 'sign'\n | 'execute'\n\n/** A wiring bug, not a user-correctable condition; the user gets the generic line. */\nclass NadoWithdrawalInputError extends Error {}\n\n/** Already logged where it was raised, so the catch neither re-logs nor escalates. */\nclass NadoWithdrawalUserError extends Error {}\n\nexport interface NadoWithdrawalSubmitContext {\n nado: NadoWithdrawalFlowConfig\n /** Packed id of the subaccount being debited (`buildNadoSubaccountId`). */\n subaccount: Hex\n sourceToken: NadoWithdrawalSourceOption\n /** The host's signer. Nado needs `signTypedData`; a client without it fails. */\n wallet: WithdrawalClient\n /** Drops the cached max, or a follow-up withdrawal opens on a stale balance. */\n onWithdrawn: () => void\n}\n\n/**\n * The `submitWithdrawal` the crypto rail runs in place of a relay execution.\n * Resolves with the deposit address Nado was told to send to \u2014 nothing of ours\n * goes on-chain, so there is no transaction to return.\n */\nexport function createNadoWithdrawalSubmit({\n nado,\n subaccount,\n sourceToken,\n wallet,\n onWithdrawn,\n}: NadoWithdrawalSubmitContext) {\n return async ({\n recipientAddress,\n destinationToken,\n amountTokenUnits,\n }: CustomWithdrawalSubmission): Promise<{ depositAddress: Address }> => {\n const { walletAddress, onBeforeSign } = nado\n const { productId, decimals } = sourceToken\n const recipientAddr = normalizeRecipientAddress(recipientAddress)\n\n let step: NadoWithdrawalStep = 'validate'\n\n try {\n // Already net of the fee \u2014 see the note at the top of the file.\n const netRawAmount = toWithdrawalAmountBaseUnit(\n amountTokenUnits,\n decimals,\n )\n if (netRawAmount <= 0n) {\n logger.warn('nado:withdrawal:amountTooLow', {\n productId,\n amountTokenUnits,\n })\n throw new NadoWithdrawalUserError(\n i18n.t('withdrawNado.errorAmountTooLow'),\n )\n }\n\n logger.info('nado:withdrawal:start', {\n productId,\n spotLeverage: NADO_MOBILE_SPOT_LEVERAGE,\n decimals,\n amountTokenUnits,\n toChainId: destinationToken.chainId,\n toToken: destinationToken.address,\n recipientAddress: recipientAddr,\n })\n\n await assertWithinMaxWithdrawable({\n subaccount,\n productId,\n decimals,\n netRawAmount,\n })\n\n // Before the deposit address: a declined switch or swapped account would\n // otherwise orphan one.\n step = 'beforeSign'\n try {\n await onBeforeSign?.()\n } catch (error) {\n // The documented way for a host to abort \u2014 a user choice, not a failure.\n const message = error instanceof Error ? error.message : String(error)\n logger.warn('nado:withdrawal:abortedByHost', {\n walletAddress,\n errorMessage: message,\n })\n throw new NadoWithdrawalUserError(message)\n }\n\n step = 'switchChain'\n await ensureWalletOnInk(wallet)\n await assertOwnerIsSigner({ walletAddress, wallet })\n\n step = 'uda'\n const { depositAddr } = await initializeCheckoutTokenTransferAddress({\n apiKey: NADO_API_KEY,\n // The owner wallet is the stable per-user id, and is what the completion\n // tracker later looks the arrival up by.\n userId: walletAddress,\n recipientAddr,\n toChainId: destinationToken.chainId,\n toTokenAddress: destinationToken.address,\n sourceOfFund: `balance|nado|${walletAddress}`,\n // Attribution only \u2014 forces a separate address from Nado deposits.\n actionType: NADO_WITHDRAWAL_ACTION_TYPE,\n logger,\n clientMetadata: { isWithdrawal: true },\n })\n logger.info('nado:withdrawal:udaGenerated', {\n depositAddr,\n productId,\n recipientAddress: recipientAddr,\n })\n\n step = 'sign'\n // Immediately before signing: a stale nonce is rejected outright.\n const nonce = await getNadoTxNonce(walletAddress, { logger })\n const signature = await signWithdrawal({\n wallet,\n subaccount,\n productId,\n netRawAmount,\n nonce,\n sendTo: depositAddr as Address,\n })\n logger.info('nado:withdrawal:signed', {\n nonce: nonce.toString(),\n depositAddr,\n productId,\n })\n\n step = 'execute'\n try {\n await executeNadoWithdrawCollateralV2(\n {\n sender: subaccount,\n productId,\n amount: netRawAmount,\n nonce,\n sendTo: depositAddr,\n signature,\n spotLeverage: NADO_MOBILE_SPOT_LEVERAGE,\n },\n { logger },\n )\n } catch (error) {\n // An unconfirmed execute may still have debited. Re-reading Nado is\n // right either way; keeping the cached maximum is only right if it did\n // not land.\n if (error instanceof NadoWithdrawalUnconfirmedError) {\n onWithdrawn()\n }\n throw error\n }\n logger.info('nado:withdrawal:executeSubmitted', {\n nonce: nonce.toString(),\n depositAddr,\n productId,\n netRawAmount: netRawAmount.toString(),\n })\n onWithdrawn()\n\n return { depositAddress: depositAddr as Address }\n } catch (error) {\n throw toThrownWithdrawalError(error, {\n step,\n walletAddress,\n subaccount,\n recipientAddress: recipientAddr,\n toChainId: destinationToken.chainId,\n })\n }\n }\n}\n\n/**\n * The signature is off-chain and gasless, but wallets reject an\n * `eth_signTypedData_v4` whose domain chainId isn't the active chain \u2014 so the\n * wallet still has to sit on Ink to sign it.\n */\nasync function ensureWalletOnInk(wallet: WithdrawalClient): Promise<void> {\n const connectedChainId = await wallet.getChainId()\n if (connectedChainId === INK_CHAIN_ID) {\n return\n }\n logger.info('nado:withdrawal:switchingChain', {\n fromChainId: connectedChainId,\n })\n try {\n await wallet.switchChain(INK_CHAIN_ID)\n } catch (error) {\n if (isUserRejectedError(error)) {\n throw error\n }\n logger.warn('nado:withdrawal:switchChainFailed', {\n fromChainId: connectedChainId,\n errorMessage: error instanceof Error ? error.message : String(error),\n })\n throw new NadoWithdrawalUserError(i18n.t('withdrawCrypto.errorSwitchChain'))\n }\n}\n\n/** Nado only honors owner-wallet signatures, so a switched account must fail loudly. */\nasync function assertOwnerIsSigner({\n walletAddress,\n wallet,\n}: {\n walletAddress: Address\n wallet: WithdrawalClient\n}): Promise<void> {\n const connectedAddress = wallet.address()\n if (\n connectedAddress &&\n isAddressEquivalent({\n firstAddress: connectedAddress,\n secondAddress: walletAddress,\n })\n ) {\n return\n }\n logger.warn('nado:withdrawal:signerMismatch', {\n walletAddress,\n connectedAddress: connectedAddress ?? null,\n })\n throw new NadoWithdrawalUserError(i18n.t('withdrawNado.errorSignerMismatch'))\n}\n\n/** `signTypedData` is optional on the client, but Nado cannot withdraw without it. */\nasync function signWithdrawal({\n wallet,\n subaccount,\n productId,\n netRawAmount,\n nonce,\n sendTo,\n}: {\n wallet: WithdrawalClient\n subaccount: Hex\n productId: number\n netRawAmount: bigint\n nonce: bigint\n sendTo: Address\n}): Promise<Hex> {\n if (!wallet.signTypedData) {\n throw new NadoWithdrawalInputError(\n 'withdrawalWallet cannot signTypedData, which Nado withdrawals require',\n )\n }\n const signature = await wallet.signTypedData(\n buildWithdrawCollateralV2TypedData({\n sender: subaccount,\n productId,\n amount: netRawAmount,\n nonce,\n sendTo,\n }),\n )\n return signature as Hex\n}\n\n/**\n * Race backstop, not the primary gate: the amount screen already blocks this,\n * but account health can move between render and submit \u2014 and catching it here\n * saves a wallet prompt and a burnt nonce. `max_withdrawable` is already net of\n * the fee, so it compares against the signed amount.\n */\nasync function assertWithinMaxWithdrawable({\n subaccount,\n productId,\n decimals,\n netRawAmount,\n}: {\n subaccount: Hex\n productId: number\n decimals: number\n netRawAmount: bigint\n}): Promise<void> {\n const maxWithdrawableX18 = await getNadoMaxWithdrawable(\n { productId, sender: subaccount, spotLeverage: NADO_MOBILE_SPOT_LEVERAGE },\n { logger },\n )\n const maxRawAmount = x18ToRawBaseUnit(\n safeBigInt(maxWithdrawableX18, 0n),\n decimals,\n )\n if (netRawAmount <= maxRawAmount) {\n return\n }\n logger.warn('nado:withdrawal:exceedsMaxWithdrawable', {\n productId,\n netRawAmount: netRawAmount.toString(),\n maxRawAmount: maxRawAmount.toString(),\n })\n // No figure in the copy: on a race it is stale by the time it is read.\n throw new NadoWithdrawalUserError(i18n.t('withdrawNado.errorBalanceChanged'))\n}\n\n/**\n * Failure \u2192 what the user sees, and at what severity.\n *\n * - Recovered states (declined signature, precondition rejections, expected\n * gateway codes) log at WARN; ERROR is reserved for what is worth alerting on.\n * - Gateway failures map to Nado copy; everything else already carries a usable\n * message and passes through.\n */\nfunction toThrownWithdrawalError(\n error: unknown,\n context: {\n step: NadoWithdrawalStep\n walletAddress: Address\n subaccount: Hex\n recipientAddress: FunAddress\n toChainId: string\n },\n): unknown {\n const logContext = {\n ...context,\n nadoErrorCode:\n error instanceof NadoGatewayError ? (error.errorCode ?? null) : null,\n nadoErrorKind: error instanceof NadoGatewayError ? error.kind : null,\n errorMessage: error instanceof Error ? error.message : String(error),\n }\n // A user choice, not a failure to alert on.\n if (isUserRejectedError(error)) {\n logger.warn('nado:withdrawal:rejected', logContext)\n return error\n }\n // Already warned where it was raised, with the context only that site had.\n if (error instanceof NadoWithdrawalUserError) {\n return error\n }\n if (error instanceof NadoWithdrawalInputError) {\n logger.error('nado:withdrawal:invalidInput', error, logContext)\n return new Error(i18n.t('withdrawCrypto.errorGeneric'))\n }\n // Already logged at the gateway; the copy steers away from a retry.\n if (error instanceof NadoWithdrawalUnconfirmedError) {\n return new Error(toNadoWithdrawalErrorMessage(error))\n }\n if (!(error instanceof NadoGatewayError)) {\n logger.error(\n 'nado:withdrawal:failed',\n error instanceof Error ? error : new Error(String(error)),\n logContext,\n )\n return error\n }\n if (isExpectedNadoWithdrawalFailure(error)) {\n logger.warn('nado:withdrawal:gatewayRejected', logContext)\n } else {\n logger.error('nado:withdrawal:gatewayFailed', error, logContext)\n }\n return new Error(toNadoWithdrawalErrorMessage(error))\n}\n", "/**\n * Nado failure code \u2192 the copy the user sees. Core classifies; each platform\n * owns its map, and an exhaustive `Record` fails the build on a new code.\n *\n * Thunks rather than a key lookup: `t(KEYS[code])` passes a non-literal to `t`,\n * which `.ast-grep/rules/i18n-t-string-literal.yml` rejects.\n */\n\nimport {\n type NadoWithdrawalFailure,\n toNadoWithdrawalFailure,\n} from '@funkit/connect-core/clients/nado'\n\nimport { i18n } from '../../src/locales/i18n'\n\nconst MESSAGE_FOR: Record<NadoWithdrawalFailure, () => string> = {\n generic: () => i18n.t('withdrawCrypto.errorGeneric'),\n network: () => i18n.t('withdrawNado.errorNetwork'),\n rateLimited: () => i18n.t('withdrawNado.errorRateLimited'),\n // Borrowing is off on mobile, so this only ever means the balance moved.\n exceedsBorrowLimit: () => i18n.t('withdrawNado.errorBalanceChanged'),\n invalidNonce: () => i18n.t('withdrawNado.errorInvalidNonce'),\n noPriorDeposit: () => i18n.t('withdrawNado.errorNoPriorDeposit'),\n withdrawRisk: () => i18n.t('withdrawNado.errorWithdrawRisk'),\n unconfirmed: () => i18n.t('withdrawNado.errorUnconfirmed'),\n}\n\nexport function toNadoWithdrawalErrorMessage(error: unknown): string {\n return MESSAGE_FOR[toNadoWithdrawalFailure(error)]()\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS,cAAc;;;ACRhC;AAAA,EACE;AAAA,OAEK;AAIA,IAAM,iBAAiB;AAOvB,IAAM,4BAA4B;AAMlC,IAAM,6BAA6B;AAOnC,IAAM,0BAAsD;AAAA,EACjE,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,cAAc;AAAA,EACd,cAAc,GAAG,YAAY;AAAA,EAC7B,SAAS;AACX;;;ACpBA;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE,gBAAAA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AC/BP;AAAA,EAEE;AAAA,OACK;AAIP,IAAM,cAA2D;AAAA,EAC/D,SAAS,MAAM,KAAK,EAAE,6BAA6B;AAAA,EACnD,SAAS,MAAM,KAAK,EAAE,2BAA2B;AAAA,EACjD,aAAa,MAAM,KAAK,EAAE,+BAA+B;AAAA;AAAA,EAEzD,oBAAoB,MAAM,KAAK,EAAE,kCAAkC;AAAA,EACnE,cAAc,MAAM,KAAK,EAAE,gCAAgC;AAAA,EAC3D,gBAAgB,MAAM,KAAK,EAAE,kCAAkC;AAAA,EAC/D,cAAc,MAAM,KAAK,EAAE,gCAAgC;AAAA,EAC3D,aAAa,MAAM,KAAK,EAAE,+BAA+B;AAC3D;AAEO,SAAS,6BAA6B,OAAwB;AACnE,SAAO,YAAY,wBAAwB,KAAK,CAAC,EAAE;AAC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