@funkit/connect-rn 7.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.
- package/CHANGELOG.md +71 -0
- package/README.md +76 -56
- package/dist/{chunk-P3OLDPDC.js → chunk-4YNYOJJK.js} +217 -192
- package/dist/chunk-4YNYOJJK.js.map +7 -0
- package/dist/{chunk-HRJNTNCV.js → chunk-75U7A2Q5.js} +29 -11
- package/dist/chunk-75U7A2Q5.js.map +7 -0
- package/dist/chunk-D64EJ57D.js +161 -0
- package/dist/chunk-D64EJ57D.js.map +7 -0
- package/dist/clients/lighter.js +4 -2
- package/dist/clients/lighter.js.map +1 -1
- package/dist/clients/nado.js +6 -4
- package/dist/clients/nado.js.map +2 -2
- package/dist/clients/solana/index.d.ts +5 -0
- package/dist/clients/solana/index.d.ts.map +1 -0
- package/dist/clients/solana/solanaWithdrawal.d.ts +20 -0
- package/dist/clients/solana/solanaWithdrawal.d.ts.map +1 -0
- package/dist/clients/solana/useSolanaWithdrawal.d.ts +13 -0
- package/dist/clients/solana/useSolanaWithdrawal.d.ts.map +1 -0
- package/dist/clients/solana.d.ts +1 -0
- package/dist/clients/solana.js +87 -0
- package/dist/clients/solana.js.map +7 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20258 -18583
- package/dist/index.js.map +4 -4
- package/dist/src/components/AssetGrid.d.ts.map +1 -1
- package/dist/src/components/Grabber.d.ts +3 -1
- package/dist/src/components/Grabber.d.ts.map +1 -1
- package/dist/src/components/InfoTooltip.d.ts +28 -0
- package/dist/src/components/InfoTooltip.d.ts.map +1 -0
- package/dist/src/fiat/KycGlassBackdrop.d.ts.map +1 -1
- package/dist/src/fiat/SurfaceSlot.d.ts +8 -2
- package/dist/src/fiat/SurfaceSlot.d.ts.map +1 -1
- package/dist/src/fiat/providers/moonpay.d.ts.map +1 -1
- package/dist/src/fiat/quoteRefusal.d.ts +29 -6
- package/dist/src/fiat/quoteRefusal.d.ts.map +1 -1
- package/dist/src/fiat/useFiatDirectDelivery.d.ts +5 -4
- package/dist/src/fiat/useFiatDirectDelivery.d.ts.map +1 -1
- package/dist/src/fiat/useIdentityAssertion.d.ts +35 -0
- package/dist/src/fiat/useIdentityAssertion.d.ts.map +1 -0
- package/dist/src/fiat/useQuoteableCeiling.d.ts +28 -0
- package/dist/src/fiat/useQuoteableCeiling.d.ts.map +1 -0
- package/dist/src/flow/AddressCopiedToast.d.ts +3 -1
- package/dist/src/flow/AddressCopiedToast.d.ts.map +1 -1
- package/dist/src/flow/DepositAssetPicker.d.ts +11 -0
- package/dist/src/flow/DepositAssetPicker.d.ts.map +1 -0
- package/dist/src/flow/DepositFlowContent.d.ts +1 -1
- package/dist/src/flow/DepositFlowContent.d.ts.map +1 -1
- package/dist/src/flow/DepositReceivedToast.d.ts +2 -2
- package/dist/src/flow/DepositReceivedToast.d.ts.map +1 -1
- package/dist/src/flow/FeeDetailsSheet.d.ts.map +1 -1
- package/dist/src/flow/FiatDepositAmountStep.d.ts.map +1 -1
- package/dist/src/flow/FlowSheet.d.ts +14 -20
- package/dist/src/flow/FlowSheet.d.ts.map +1 -1
- package/dist/src/flow/FunkitFlowProvider.d.ts +9 -4
- package/dist/src/flow/FunkitFlowProvider.d.ts.map +1 -1
- package/dist/src/flow/SheetMaterial.d.ts +11 -0
- package/dist/src/flow/SheetMaterial.d.ts.map +1 -0
- package/dist/src/flow/WithdrawalFlowContent.d.ts.map +1 -1
- package/dist/src/flow/depositFlowConfig.d.ts +24 -5
- package/dist/src/flow/depositFlowConfig.d.ts.map +1 -1
- package/dist/src/flow/flowError.d.ts +11 -1
- package/dist/src/flow/flowError.d.ts.map +1 -1
- package/dist/src/flow/flowStepHeight.d.ts +19 -0
- package/dist/src/flow/flowStepHeight.d.ts.map +1 -0
- package/dist/src/flow/isLockedDeposit.d.ts +6 -0
- package/dist/src/flow/isLockedDeposit.d.ts.map +1 -0
- package/dist/src/flow/useCopiedToast.d.ts +1 -1
- package/dist/src/flow/useCopiedToast.d.ts.map +1 -1
- package/dist/src/flow/validateClientMetadata.d.ts +2 -3
- package/dist/src/flow/validateClientMetadata.d.ts.map +1 -1
- package/dist/src/hooks/useSheetFade.d.ts +11 -0
- package/dist/src/hooks/useSheetFade.d.ts.map +1 -0
- package/dist/src/identity/IdentityContext.d.ts +28 -4
- package/dist/src/identity/IdentityContext.d.ts.map +1 -1
- package/dist/src/logging/debugBridge.d.ts +2 -0
- package/dist/src/logging/debugBridge.d.ts.map +1 -1
- package/dist/src/native/glassEffect.d.ts +18 -0
- package/dist/src/native/glassEffect.d.ts.map +1 -0
- package/dist/src/providers/FunkitProvider.d.ts +6 -8
- package/dist/src/providers/FunkitProvider.d.ts.map +1 -1
- package/dist/src/providers/NativeCapabilitiesContext.d.ts +12 -11
- package/dist/src/providers/NativeCapabilitiesContext.d.ts.map +1 -1
- package/dist/src/providers/useFunkitCheckout.d.ts +7 -3
- package/dist/src/providers/useFunkitCheckout.d.ts.map +1 -1
- package/dist/src/screens/DepositAmountScreen.d.ts.map +1 -1
- package/dist/src/screens/FeeDetailsScreen.d.ts +2 -5
- package/dist/src/screens/FeeDetailsScreen.d.ts.map +1 -1
- package/dist/src/screens/LockedTransferCryptoScreen.d.ts +19 -0
- package/dist/src/screens/LockedTransferCryptoScreen.d.ts.map +1 -0
- package/dist/src/screens/SelectChainScreen.d.ts +1 -0
- package/dist/src/screens/SelectChainScreen.d.ts.map +1 -1
- package/dist/src/screens/SelectReceiveTokenAndChainScreen.d.ts +0 -8
- package/dist/src/screens/SelectReceiveTokenAndChainScreen.d.ts.map +1 -1
- package/dist/src/screens/TokenAndChainPickerScreen.d.ts +16 -0
- package/dist/src/screens/TokenAndChainPickerScreen.d.ts.map +1 -0
- package/dist/src/screens/WithdrawAddressScreen.d.ts.map +1 -1
- package/dist/src/screens/WithdrawAmountScreen.d.ts.map +1 -1
- package/dist/src/screens/WithdrawCompleteScreen.d.ts.map +1 -1
- package/dist/src/swapped/SwappedScreenShell.d.ts.map +1 -1
- package/dist/src/swapped/SwappedWebView.d.ts.map +1 -1
- package/dist/src/swapped/SwappedWithdrawScreen.d.ts +3 -1
- package/dist/src/swapped/SwappedWithdrawScreen.d.ts.map +1 -1
- package/dist/src/swapped/paymentNavigation.d.ts +21 -0
- package/dist/src/swapped/paymentNavigation.d.ts.map +1 -0
- package/dist/src/transfer/clipboard.d.ts +2 -0
- package/dist/src/transfer/clipboard.d.ts.map +1 -1
- package/dist/src/transfer/depositAssets.d.ts +35 -0
- package/dist/src/transfer/depositAssets.d.ts.map +1 -0
- package/dist/src/transfer/hooks/useCopyDepositAddress.d.ts +7 -6
- package/dist/src/transfer/hooks/useCopyDepositAddress.d.ts.map +1 -1
- package/dist/src/transfer/hooks/useDepositAssets.d.ts +14 -0
- package/dist/src/transfer/hooks/useDepositAssets.d.ts.map +1 -0
- package/dist/src/transfer/hooks/useDepositRecipient.d.ts +2 -2
- package/dist/src/transfer/hooks/useDepositRecipient.d.ts.map +1 -1
- package/dist/src/transfer/hooks/useFiatExchangeRates.d.ts +1 -5
- package/dist/src/transfer/hooks/useFiatExchangeRates.d.ts.map +1 -1
- package/dist/src/transfer/hooks/useLockedTokenAmount.d.ts +10 -0
- package/dist/src/transfer/hooks/useLockedTokenAmount.d.ts.map +1 -0
- package/dist/src/transfer/hooks/useTokenTransfer.d.ts +3 -2
- package/dist/src/transfer/hooks/useTokenTransfer.d.ts.map +1 -1
- package/dist/src/transfer/hooks/useTransferInit.d.ts +2 -3
- package/dist/src/transfer/hooks/useTransferInit.d.ts.map +1 -1
- package/dist/src/transfer/lockedTokenAmount.d.ts +9 -0
- package/dist/src/transfer/lockedTokenAmount.d.ts.map +1 -0
- package/dist/src/transfer/supportedTokens.d.ts +5 -0
- package/dist/src/transfer/supportedTokens.d.ts.map +1 -1
- package/dist/src/utils/assetGrid.d.ts +5 -0
- package/dist/src/utils/assetGrid.d.ts.map +1 -1
- package/dist/src/utils/motion.d.ts +10 -0
- package/dist/src/utils/motion.d.ts.map +1 -1
- package/dist/src/utils/tokenAndChainPicker.d.ts +15 -0
- package/dist/src/utils/tokenAndChainPicker.d.ts.map +1 -0
- package/dist/src/withdrawal/fiatTargetDecimals.d.ts +13 -0
- package/dist/src/withdrawal/fiatTargetDecimals.d.ts.map +1 -0
- package/dist/src/withdrawal/receiveDestination.d.ts +0 -7
- package/dist/src/withdrawal/receiveDestination.d.ts.map +1 -1
- package/dist/src/withdrawal/useSourceTokenDecimals.d.ts.map +1 -1
- package/dist/src/withdrawal/useSourceTokenUsdPrice.d.ts +15 -2
- package/dist/src/withdrawal/useSourceTokenUsdPrice.d.ts.map +1 -1
- package/dist/src/withdrawal/useWithdrawalExecution.d.ts.map +1 -1
- package/expo-module.config.json +6 -0
- package/ios/FunkitGlassEffect.podspec +23 -0
- package/ios/FunkitGlassEffectModule.swift +126 -0
- package/ios/GlassStyle.swift +52 -0
- package/ios/GlassView.swift +305 -0
- package/package.json +17 -5
- package/dist/chunk-HRJNTNCV.js.map +0 -7
- package/dist/chunk-P3OLDPDC.js.map +0 -7
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
|
-
logger,
|
|
3
2
|
useFunkitIdentity
|
|
4
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-4YNYOJJK.js";
|
|
4
|
+
import {
|
|
5
|
+
logger
|
|
6
|
+
} from "./chunk-D64EJ57D.js";
|
|
5
7
|
|
|
6
8
|
// src/statsig/useDynamicConfig.ts
|
|
7
9
|
import {
|
|
@@ -50,20 +52,28 @@ function useIsStablecoin() {
|
|
|
50
52
|
var SOURCE_TOKEN_PRICE_QUERY_KEY = "sourceTokenUsdPrice";
|
|
51
53
|
var PRICE_STALE_TIME_MS = 6e4;
|
|
52
54
|
var STABLECOIN_USD_PRICE = 1;
|
|
53
|
-
function useSourceTokenUsdPrice(sourceToken
|
|
55
|
+
function useSourceTokenUsdPrice(sourceToken, {
|
|
56
|
+
enabled = true,
|
|
57
|
+
refetchInterval = false
|
|
58
|
+
} = {}) {
|
|
54
59
|
const { apiKey } = useFunkitIdentity();
|
|
55
60
|
const isStablecoin = useIsStablecoin();
|
|
56
|
-
const
|
|
57
|
-
const
|
|
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({
|
|
58
65
|
queryKey: [
|
|
59
66
|
SOURCE_TOKEN_PRICE_QUERY_KEY,
|
|
60
67
|
apiKey,
|
|
61
|
-
|
|
62
|
-
sourceToken
|
|
68
|
+
chainId,
|
|
69
|
+
sourceToken?.address
|
|
63
70
|
],
|
|
64
71
|
queryFn: async () => {
|
|
72
|
+
if (!sourceToken || !chainId) {
|
|
73
|
+
throw new Error("Missing price inputs");
|
|
74
|
+
}
|
|
65
75
|
const info = await getAssetPriceInfoWithFallback({
|
|
66
|
-
chainId
|
|
76
|
+
chainId,
|
|
67
77
|
assetTokenAddress: sourceToken.address,
|
|
68
78
|
apiKey,
|
|
69
79
|
logger
|
|
@@ -79,11 +89,19 @@ function useSourceTokenUsdPrice(sourceToken) {
|
|
|
79
89
|
}
|
|
80
90
|
return unitPrice;
|
|
81
91
|
},
|
|
82
|
-
enabled: !!
|
|
92
|
+
enabled: enabled && !!sourceToken && !isStable && !unavailable,
|
|
83
93
|
staleTime: PRICE_STALE_TIME_MS,
|
|
94
|
+
refetchInterval: isStable ? false : refetchInterval,
|
|
84
95
|
retry: false
|
|
85
96
|
});
|
|
86
|
-
return
|
|
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
|
+
};
|
|
87
105
|
}
|
|
88
106
|
|
|
89
107
|
export {
|
|
@@ -92,4 +110,4 @@ export {
|
|
|
92
110
|
useIsStablecoin,
|
|
93
111
|
useSourceTokenUsdPrice
|
|
94
112
|
};
|
|
95
|
-
//# sourceMappingURL=chunk-
|
|
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],\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,MACA,aAAa;AAAA,IACf;AAAA,IACA,SAAS,YAAY;AACnB,UAAI,CAAC,eAAe,CAAC,SAAS;AAC5B,cAAM,IAAI,MAAM,sBAAsB;AAAA,MACxC;AACA,YAAM,OAAO,MAAM,8BAA8B;AAAA,QAC/C;AAAA,QACA,mBAAmB,YAAY;AAAA,QAC/B;AAAA,QACA;AAAA,MACF,CAAC;AACD,YAAM,YAAY,KAAK;AACvB,UAAI,CAAC,OAAO,SAAS,SAAS,KAAK,aAAa,GAAG;AAIjD,eAAO,KAAK,+CAA+C;AAAA,UACzD,SAAS,YAAY;AAAA,UACrB,SAAS,YAAY;AAAA,UACrB;AAAA,QACF,CAAC;AACD,eAAO;AAAA,MACT;AACA,aAAO;AAAA,IACT;AAAA,IACA,SAAS,WAAW,CAAC,CAAC,eAAe,CAAC,YAAY,CAAC;AAAA,IACnD,WAAW;AAAA,IACX,iBAAiB,WAAW,QAAQ;AAAA,IACpC,OAAO;AAAA,EACT,CAAC;AAED,SAAO;AAAA,IACL,SAAS,MAAM;AAAA,IACf,MAAM,WAAW,uBAAwB,MAAM,QAAQ;AAAA,IACvD,eAAe;AAAA,IACf,WAAW,CAAC,YAAY,CAAC,eAAe,MAAM;AAAA,IAC9C,SAAS,CAAC,aAAa,eAAe,MAAM;AAAA,IAC5C,YAAY,CAAC,YAAY,MAAM;AAAA,EACjC;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// src/logging/logger.ts
|
|
2
|
+
import { FunLogger } from "@funkit/connect-core";
|
|
3
|
+
|
|
4
|
+
// src/logging/serializeLogBatch.ts
|
|
5
|
+
var UNSERIALIZABLE_DATA = "[Unserializable]";
|
|
6
|
+
function serializeLogBatch(batch) {
|
|
7
|
+
try {
|
|
8
|
+
return JSON.stringify(batch, createSafeJsonReplacer());
|
|
9
|
+
} catch {
|
|
10
|
+
return `[${batch.map(serializeRecord).join(",")}]`;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function serializeRecord(record) {
|
|
14
|
+
const attributes = Object.entries(record).flatMap(([key, value]) => {
|
|
15
|
+
const serialized = serializeValue(value);
|
|
16
|
+
return serialized === void 0 ? [] : [`${JSON.stringify(key)}:${serialized}`];
|
|
17
|
+
});
|
|
18
|
+
return `{${attributes.join(",")}}`;
|
|
19
|
+
}
|
|
20
|
+
function serializeValue(value) {
|
|
21
|
+
try {
|
|
22
|
+
return JSON.stringify(value, createSafeJsonReplacer());
|
|
23
|
+
} catch {
|
|
24
|
+
return JSON.stringify(UNSERIALIZABLE_DATA);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function createSafeJsonReplacer() {
|
|
28
|
+
const ancestors = [];
|
|
29
|
+
return function(_key, value) {
|
|
30
|
+
if (typeof value === "bigint") {
|
|
31
|
+
return value.toString();
|
|
32
|
+
}
|
|
33
|
+
if (typeof value === "function") {
|
|
34
|
+
return `[Function] ${value.name || "anonymous"}`;
|
|
35
|
+
}
|
|
36
|
+
if (typeof value === "symbol") {
|
|
37
|
+
return `[Symbol] ${value.description ?? ""}`;
|
|
38
|
+
}
|
|
39
|
+
if (value === null || typeof value !== "object") {
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
if ("$$typeof" in value) {
|
|
43
|
+
return "[React]";
|
|
44
|
+
}
|
|
45
|
+
while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {
|
|
46
|
+
ancestors.pop();
|
|
47
|
+
}
|
|
48
|
+
if (ancestors.includes(value)) {
|
|
49
|
+
return "[Circular]";
|
|
50
|
+
}
|
|
51
|
+
ancestors.push(value);
|
|
52
|
+
return value;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// src/logging/datadogHttpLogTransport.ts
|
|
57
|
+
var DEFAULT_SERVICE = "connect-rn";
|
|
58
|
+
var DEFAULT_SITE = "datadoghq.com";
|
|
59
|
+
var DEFAULT_FLUSH_INTERVAL_MS = 5e3;
|
|
60
|
+
var DEFAULT_MAX_BATCH_SIZE = 50;
|
|
61
|
+
var DatadogHttpLogTransport = class {
|
|
62
|
+
constructor(options) {
|
|
63
|
+
this.consent = "granted";
|
|
64
|
+
this.queue = [];
|
|
65
|
+
this.flushTimer = null;
|
|
66
|
+
const site = options.site ?? DEFAULT_SITE;
|
|
67
|
+
this.service = options.service ?? DEFAULT_SERVICE;
|
|
68
|
+
this.env = options.env;
|
|
69
|
+
this.flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
|
|
70
|
+
this.maxBatchSize = options.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;
|
|
71
|
+
this.intakeUrl = `https://browser-intake-${site}/api/v2/logs?dd-api-key=${encodeURIComponent(options.clientToken)}&ddsource=react-native&dd-evp-origin=react-native`;
|
|
72
|
+
}
|
|
73
|
+
setEnv(environment) {
|
|
74
|
+
this.env = environment;
|
|
75
|
+
}
|
|
76
|
+
setTrackingConsent(consent) {
|
|
77
|
+
this.consent = consent;
|
|
78
|
+
if (consent !== "granted") {
|
|
79
|
+
this.queue = [];
|
|
80
|
+
this.clearTimer();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
log({ level, title, context, error }) {
|
|
84
|
+
if (this.consent !== "granted") {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const entry = {
|
|
88
|
+
// Caller context first so the mandatory Datadog fields below always win —
|
|
89
|
+
// a future LogContext attribute named e.g. `message`/`status` can't
|
|
90
|
+
// silently corrupt the record.
|
|
91
|
+
...context,
|
|
92
|
+
ddsource: "react-native",
|
|
93
|
+
service: this.service,
|
|
94
|
+
status: level,
|
|
95
|
+
message: title,
|
|
96
|
+
...this.env ? { ddtags: `env:${this.env}` } : {},
|
|
97
|
+
...error ? {
|
|
98
|
+
error: {
|
|
99
|
+
message: error.message,
|
|
100
|
+
stack: error.stack,
|
|
101
|
+
kind: error.name
|
|
102
|
+
}
|
|
103
|
+
} : {}
|
|
104
|
+
};
|
|
105
|
+
this.queue.push(entry);
|
|
106
|
+
if (this.queue.length >= this.maxBatchSize) {
|
|
107
|
+
this.flush();
|
|
108
|
+
} else {
|
|
109
|
+
this.scheduleFlush();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** Send the buffered batch. Fire-and-forget; network errors are swallowed. */
|
|
113
|
+
flush() {
|
|
114
|
+
this.clearTimer();
|
|
115
|
+
if (this.queue.length === 0) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (typeof fetch !== "function") {
|
|
119
|
+
this.queue = [];
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const batch = this.queue;
|
|
123
|
+
this.queue = [];
|
|
124
|
+
fetch(this.intakeUrl, {
|
|
125
|
+
method: "POST",
|
|
126
|
+
headers: { "Content-Type": "application/json" },
|
|
127
|
+
body: serializeLogBatch(batch)
|
|
128
|
+
}).catch(() => {
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
scheduleFlush() {
|
|
132
|
+
if (this.flushTimer != null) {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
this.flushTimer = setTimeout(() => {
|
|
136
|
+
this.flushTimer = null;
|
|
137
|
+
this.flush();
|
|
138
|
+
}, this.flushIntervalMs);
|
|
139
|
+
}
|
|
140
|
+
clearTimer() {
|
|
141
|
+
if (this.flushTimer != null) {
|
|
142
|
+
clearTimeout(this.flushTimer);
|
|
143
|
+
this.flushTimer = null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
// src/logging/logger.ts
|
|
149
|
+
var DDOG_CLIENT_TOKEN = "pub4f86c6be8c792cb48dc156a8c17d9a47";
|
|
150
|
+
var logger = new FunLogger(
|
|
151
|
+
new DatadogHttpLogTransport({
|
|
152
|
+
clientToken: DDOG_CLIENT_TOKEN
|
|
153
|
+
// service defaults to 'connect-rn' (see DatadogHttpLogTransport).
|
|
154
|
+
})
|
|
155
|
+
);
|
|
156
|
+
logger.setDebugTag(process.env.EXPO_PUBLIC_DEV_TAG ?? null);
|
|
157
|
+
|
|
158
|
+
export {
|
|
159
|
+
logger
|
|
160
|
+
};
|
|
161
|
+
//# sourceMappingURL=chunk-D64EJ57D.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/logging/logger.ts", "../src/logging/serializeLogBatch.ts", "../src/logging/datadogHttpLogTransport.ts"],
|
|
4
|
+
"sourcesContent": ["import { FunLogger } from '@funkit/connect-core'\n\nimport { DatadogHttpLogTransport } from './datadogHttpLogTransport'\n\n// Public Datadog client token (same one `@funkit/connect` uses for web). A\n// client token is safe to embed in client apps.\nconst DDOG_CLIENT_TOKEN = 'pub4f86c6be8c792cb48dc156a8c17d9a47'\n\n/**\n * The React Native `FunLogger` singleton. Mirrors `@funkit/connect`'s web\n * `logger`, but injects the raw-HTTP {@link DatadogHttpLogTransport} (no Datadog\n * SDK, no native modules) instead of `@datadog/browser-logs`. The host wires\n * `logger.configure(...)` / `setUserInfo(...)` once identity is available.\n */\nexport const logger = new FunLogger(\n new DatadogHttpLogTransport({\n clientToken: DDOG_CLIENT_TOKEN,\n // service defaults to 'connect-rn' (see DatadogHttpLogTransport).\n }),\n)\n\n// Names a developer's build in Datadog and switches on the MoonPay frame taps.\n// Metro inlines `EXPO_PUBLIC_*` only outside `node_modules` (expo/expo#46982),\n// so this resolves in this monorepo's playground and is `undefined` \u2014 taps off \u2014\n// for anyone consuming the published package. That is the intent: it is dev\n// tooling, and a host needs no API to opt out of it.\nlogger.setDebugTag(process.env.EXPO_PUBLIC_DEV_TAG ?? null)\n", "const UNSERIALIZABLE_DATA = '[Unserializable]'\n\n/**\n * Serialize log records to a JSON body. Always succeeds.\n *\n * Web gets this from `@datadog/browser-logs`; the raw-`fetch` RN transport has\n * no such layer and serializes inside the caller's `log()`, so a throw would\n * land in a user flow.\n */\nexport function serializeLogBatch(batch: readonly object[]): string {\n try {\n return JSON.stringify(batch, createSafeJsonReplacer())\n } catch {\n return `[${batch.map(serializeRecord).join(',')}]`\n }\n}\n\n/** Attribute by attribute, so one bad value can't drop unrelated records. */\nfunction serializeRecord(record: object): string {\n const attributes = Object.entries(record).flatMap(([key, value]) => {\n const serialized = serializeValue(value)\n // Omit undefined, as JSON.stringify does for object properties.\n return serialized === undefined\n ? []\n : [`${JSON.stringify(key)}:${serialized}`]\n })\n return `{${attributes.join(',')}}`\n}\n\nfunction serializeValue(value: unknown): string | undefined {\n try {\n return JSON.stringify(value, createSafeJsonReplacer())\n } catch {\n return JSON.stringify(UNSERIALIZABLE_DATA)\n }\n}\n\n/**\n * Resolves what `JSON.stringify` can't, inside the traversal it already makes.\n * `toJSON` runs before the replacer, so a throwing one escapes to the callers\n * above. Create one per `stringify`.\n */\nfunction createSafeJsonReplacer() {\n const ancestors: object[] = []\n\n return function (this: unknown, _key: string, value: unknown): unknown {\n if (typeof value === 'bigint') {\n return value.toString()\n }\n if (typeof value === 'function') {\n return `[Function] ${value.name || 'anonymous'}`\n }\n if (typeof value === 'symbol') {\n return `[Symbol] ${value.description ?? ''}`\n }\n if (value === null || typeof value !== 'object') {\n return value\n }\n\n // React values reference the fiber that rendered them, or themselves \u2014\n // internals either way, so mark the family instead of walking it.\n if ('$$typeof' in value) {\n return '[React]'\n }\n\n // `this` is the object `value` came from; unwinding to it leaves only true\n // ancestors, so a repeated sibling reference isn't read as a cycle.\n while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {\n ancestors.pop()\n }\n if (ancestors.includes(value)) {\n return '[Circular]'\n }\n ancestors.push(value)\n return value\n }\n}\n", "import type {\n LogRecord,\n LogTransport,\n TrackingConsent,\n} from '@funkit/connect-core'\n\nimport { serializeLogBatch } from './serializeLogBatch'\n\n/**\n * React Native `LogTransport` that ships records to Datadog over **raw HTTP**\n * (`fetch`) \u2014 deliberately NOT the Datadog SDK. `@datadog/mobile-react-native`\n * pulls in native modules (autolinking, pods, no Expo Go); a plain `fetch` to\n * the logs intake needs none, so this works in Expo Go and any RN runtime.\n *\n * Records are batched and flushed fire-and-forget on a timer (or when the batch\n * fills); network errors are swallowed so logging never breaks a user flow.\n * Authenticates with the public Datadog **client token** via `dd-api-key`\n * (the same credential the browser SDK uses \u2014 safe to embed), so no server-side\n * API key is needed.\n */\nexport interface DatadogHttpLogTransportOptions {\n /** Datadog client token (`pub\u2026`). Safe to ship in client apps. */\n clientToken: string\n /** Service name attached to every log. */\n service?: string\n /** Datadog site, e.g. `datadoghq.com` (default), `datadoghq.eu`. */\n site?: string\n /** Initial environment tag; also settable later via {@link setEnv}. */\n env?: string\n /** Flush the batch at most this often (ms). Default 5000. */\n flushIntervalMs?: number\n /** Flush immediately once the batch reaches this size. Default 50. */\n maxBatchSize?: number\n}\n\ninterface DatadogLogEntry {\n ddsource: string\n service: string\n status: LogRecord['level']\n message: string\n ddtags?: string\n error?: { message: string; stack?: string; kind: string }\n [attribute: string]: unknown\n}\n\nconst DEFAULT_SERVICE = 'connect-rn'\nconst DEFAULT_SITE = 'datadoghq.com'\nconst DEFAULT_FLUSH_INTERVAL_MS = 5_000\nconst DEFAULT_MAX_BATCH_SIZE = 50\n\nexport class DatadogHttpLogTransport implements LogTransport {\n private readonly intakeUrl: string\n private readonly service: string\n private readonly flushIntervalMs: number\n private readonly maxBatchSize: number\n\n private env: string | undefined\n private consent: TrackingConsent = 'granted'\n private queue: DatadogLogEntry[] = []\n private flushTimer: ReturnType<typeof setTimeout> | null = null\n\n constructor(options: DatadogHttpLogTransportOptions) {\n const site = options.site ?? DEFAULT_SITE\n this.service = options.service ?? DEFAULT_SERVICE\n this.env = options.env\n this.flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS\n this.maxBatchSize = options.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE\n // Browser/mobile logs intake; the client token authenticates via dd-api-key.\n this.intakeUrl =\n `https://browser-intake-${site}/api/v2/logs` +\n `?dd-api-key=${encodeURIComponent(options.clientToken)}` +\n `&ddsource=react-native&dd-evp-origin=react-native`\n }\n\n setEnv(environment: string): void {\n this.env = environment\n }\n\n setTrackingConsent(consent: TrackingConsent): void {\n this.consent = consent\n if (consent !== 'granted') {\n // Drop anything buffered when consent is withdrawn.\n this.queue = []\n this.clearTimer()\n }\n }\n\n log({ level, title, context, error }: LogRecord): void {\n if (this.consent !== 'granted') {\n return\n }\n\n const entry: DatadogLogEntry = {\n // Caller context first so the mandatory Datadog fields below always win \u2014\n // a future LogContext attribute named e.g. `message`/`status` can't\n // silently corrupt the record.\n ...context,\n ddsource: 'react-native',\n service: this.service,\n status: level,\n message: title,\n ...(this.env ? { ddtags: `env:${this.env}` } : {}),\n ...(error\n ? {\n error: {\n message: error.message,\n stack: error.stack,\n kind: error.name,\n },\n }\n : {}),\n }\n\n this.queue.push(entry)\n\n if (this.queue.length >= this.maxBatchSize) {\n this.flush()\n } else {\n this.scheduleFlush()\n }\n }\n\n /** Send the buffered batch. Fire-and-forget; network errors are swallowed. */\n flush(): void {\n this.clearTimer()\n if (this.queue.length === 0) {\n return\n }\n if (typeof fetch !== 'function') {\n // No fetch (e.g. SSR import) \u2014 drop rather than throw.\n this.queue = []\n return\n }\n\n const batch = this.queue\n this.queue = []\n\n fetch(this.intakeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: serializeLogBatch(batch),\n }).catch(() => {\n // Swallow: logging must never break a user flow.\n })\n }\n\n private scheduleFlush(): void {\n if (this.flushTimer != null) {\n return\n }\n this.flushTimer = setTimeout(() => {\n this.flushTimer = null\n this.flush()\n }, this.flushIntervalMs)\n }\n\n private clearTimer(): void {\n if (this.flushTimer != null) {\n clearTimeout(this.flushTimer)\n this.flushTimer = null\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,iBAAiB;;;ACA1B,IAAM,sBAAsB;AASrB,SAAS,kBAAkB,OAAkC;AAClE,MAAI;AACF,WAAO,KAAK,UAAU,OAA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K,WAAW;AAChB,QAAI,KAAK,MAAM,WAAW,GAAG;AAC3B;AAAA,IACF;AACA,QAAI,OAAO,UAAU,YAAY;AAE/B,WAAK,QAAQ,CAAC;AACd;AAAA,IACF;AAEA,UAAM,QAAQ,KAAK;AACnB,SAAK,QAAQ,CAAC;AAEd,UAAM,KAAK,WAAW;AAAA,MACpB,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,kBAAkB,KAAK;AAAA,IAC/B,CAAC,EAAE,MAAM,MAAM;AAAA,IAEf,CAAC;AAAA,EACH;AAAA,EAEQ,gBAAsB;AAC5B,QAAI,KAAK,cAAc,MAAM;AAC3B;AAAA,IACF;AACA,SAAK,aAAa,WAAW,MAAM;AACjC,WAAK,aAAa;AAClB,WAAK,MAAM;AAAA,IACb,GAAG,KAAK,eAAe;AAAA,EACzB;AAAA,EAEQ,aAAmB;AACzB,QAAI,KAAK,cAAc,MAAM;AAC3B,mBAAa,KAAK,UAAU;AAC5B,WAAK,aAAa;AAAA,IACpB;AAAA,EACF;AACF;;;AF5JA,IAAM,oBAAoB;AAQnB,IAAM,SAAS,IAAI;AAAA,EACxB,IAAI,wBAAwB;AAAA,IAC1B,aAAa;AAAA;AAAA,EAEf,CAAC;AACH;AAOA,OAAO,YAAY,QAAQ,IAAI,uBAAuB,IAAI;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/clients/lighter.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
|
-
logger,
|
|
3
2
|
useFunkitIdentity,
|
|
4
3
|
useFunkitTranslation
|
|
5
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-4YNYOJJK.js";
|
|
5
|
+
import {
|
|
6
|
+
logger
|
|
7
|
+
} from "../chunk-D64EJ57D.js";
|
|
6
8
|
|
|
7
9
|
// clients/lighter/useLighterWithdrawalMethods.ts
|
|
8
10
|
import { useLighterAccountsQuery } from "@funkit/connect-core";
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../clients/lighter/useLighterWithdrawalMethods.ts", "../../clients/lighter/lighterWithdrawalConfig.ts", "../../clients/lighter/lighterFastWithdrawal.ts", "../../clients/lighter/useLighterUnstakedFee.ts", "../../clients/lighter/useLighterWithdrawal.ts", "../../clients/lighter/useLighterSecureWithdrawal.ts"],
|
|
4
4
|
"sourcesContent": ["import { useLighterAccountsQuery } from '@funkit/connect-core'\nimport { getLighterWithdrawalDelay } from '@funkit/connect-core/clients/lighter'\nimport { useQuery } from '@tanstack/react-query'\nimport type { TFunction } from 'i18next'\nimport { useEffect, useRef } from 'react'\n\nimport { logger } from '../../src/logging/logger'\nimport { useFunkitTranslation } from '../../src/providers/FunkitI18nProvider'\nimport {\n LIGHTER_FAST_METHOD_ID,\n LIGHTER_SECURE_METHOD_ID,\n type LighterWithdrawalFlowConfig,\n} from './lighterWithdrawalConfig'\n\n/** One row on the withdrawal method screen, before icons are attached. */\nexport interface LighterWithdrawalMethod {\n id: typeof LIGHTER_FAST_METHOD_ID | typeof LIGHTER_SECURE_METHOD_ID\n title: string\n subtitle: string\n}\n\nexport interface UseLighterWithdrawalMethodsResult {\n /** Fast then Secure, in web's order. Empty until the account resolves. */\n methods: LighterWithdrawalMethod[]\n /**\n * The user's Lighter L2 main-account index. Both rails address the account\n * by index, so neither can run before this resolves.\n */\n accountIndex: string | undefined\n /** Unified accounts hold one USDC balance \u2014 no spot/perps split. */\n isUnifiedTradingMode: boolean\n /** The account lookup is in flight; rows are expected to be empty. */\n isLoading: boolean\n}\n\nconst SECONDS_PER_MINUTE = 60\nconst MINUTES_PER_HOUR = 60\nconst SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR\n\n/**\n * Formats Lighter's live L2\u2192L1 delay for the Secure row (e.g. \"1 h 50 min\").\n * - Reproduces web's `formatSecondsToReadableForm(seconds, false, true)` output\n * for every input, including its two oddities: a sub-minute delay reads in\n * seconds, and exactly one hour reads \"60 min\". The two SDKs quote the same\n * bridge, so they must not disagree on the wait.\n * - Rounds up otherwise: an estimate must not promise finality early.\n * - One literal `t` key per shape \u2014 never a computed key.\n */\nfunction formatDelay(t: TFunction, seconds: number): string {\n const normalized = Math.ceil(seconds)\n if (normalized === 1) {\n return t('withdrawLighter.delaySecond')\n }\n if (normalized <= SECONDS_PER_MINUTE) {\n return t('withdrawLighter.delaySeconds', { seconds: normalized })\n }\n // Round to minutes first: rounding the remainder alone can yield \"1 h 60 min\".\n const minutes = Math.ceil(normalized / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR\n const hours = Math.ceil(\n (normalized - minutes * SECONDS_PER_MINUTE) / SECONDS_PER_HOUR,\n )\n if (hours === 1 && minutes === 0) {\n return t('withdrawLighter.delayMinutes', { minutes: MINUTES_PER_HOUR })\n }\n if (hours > 0 && minutes > 0) {\n return t('withdrawLighter.delayHoursMinutes', { hours, minutes })\n }\n if (hours > 0) {\n return t('withdrawLighter.delayHours', { hours })\n }\n return t('withdrawLighter.delayMinutes', { minutes })\n}\n\n/**\n * Secure-withdrawal delay as display copy. Shown live because it tracks L2\u2192L1\n * batch cadence; `undefined` until it loads.\n */\nfunction useLighterSecureDelayText(enabled: boolean): string | undefined {\n const { t } = useFunkitTranslation()\n const { data } = useQuery({\n queryKey: ['lighterWithdrawalDelay'],\n queryFn: getLighterWithdrawalDelay,\n // This hook runs for every withdrawal flow, Lighter or not \u2014 a host with no\n // Lighter config must never reach Lighter's API.\n enabled,\n staleTime: 60_000,\n retry: 2,\n })\n const seconds = data?.seconds\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return undefined\n }\n return formatDelay(t, seconds)\n}\n\ntype RailOutcome = 'not_configured' | 'loading' | 'offered' | 'no_account_index'\n\n/**\n * Whether Lighter's rails replace the generic crypto row, and why not when they\n * don't.\n * - `isFetched`, not `isLoading`: the latter is false on the first render,\n * before the query starts, which would record a premature \"no account\".\n */\nfunction resolveRailOutcome({\n isConfigured,\n isFetched,\n hasAccountIndex,\n}: {\n isConfigured: boolean\n isFetched: boolean\n hasAccountIndex: boolean\n}): RailOutcome {\n if (!isConfigured) {\n return 'not_configured'\n }\n if (!isFetched) {\n return 'loading'\n }\n if (!hasAccountIndex) {\n return 'no_account_index'\n }\n return 'offered'\n}\n\n/**\n * The Fast / Secure rows plus the account state both rails need. Port of the\n * row-building half of web's `useLighterWithdrawalConfig`.\n *\n * Pass `undefined` when the host configured no Lighter: the inner hooks still\n * run (Rules of Hooks) but every query stays disabled.\n */\nexport function useLighterWithdrawalMethods(\n config: LighterWithdrawalFlowConfig | undefined,\n): UseLighterWithdrawalMethodsResult {\n const { t } = useFunkitTranslation()\n const { mainAccountIndex, isUnifiedTradingMode, isLoading, isFetched } =\n useLighterAccountsQuery({ address: config?.l1Address })\n const secureDelayText = useLighterSecureDelayText(!!config)\n\n // Lighter addresses accounts by a numeric index; anything else means the\n // lookup returned something unusable and neither rail can address the user.\n const accountIndex =\n mainAccountIndex && /^\\d+$/.test(mainAccountIndex)\n ? mainAccountIndex\n : undefined\n\n const outcome = resolveRailOutcome({\n isConfigured: !!config,\n isFetched,\n hasAccountIndex: !!accountIndex,\n })\n // Rail-availability decision point, recorded once per outcome so a re-render\n // or a background refetch doesn't re-emit the same one.\n const loggedOutcome = useRef<RailOutcome | undefined>(undefined)\n useEffect(() => {\n if (outcome === 'loading' || loggedOutcome.current === outcome) {\n return\n }\n loggedOutcome.current = outcome\n if (outcome === 'not_configured') {\n return\n }\n const payload = {\n outcome,\n isUnifiedTradingMode,\n hasAccountIndex: !!accountIndex,\n }\n if (outcome === 'no_account_index') {\n // Recovered, but the user loses Lighter's rails for this session \u2014 that\n // is a visible capability change, so it belongs above INFO.\n logger.warn('lighter:withdrawal:rails', payload)\n return\n }\n logger.info('lighter:withdrawal:rails', payload)\n }, [outcome, isUnifiedTradingMode, accountIndex])\n\n const methods: LighterWithdrawalMethod[] =\n config && accountIndex\n ? [\n {\n id: LIGHTER_FAST_METHOD_ID,\n title: t('withdrawLighter.methodFast'),\n subtitle: isUnifiedTradingMode\n ? t('withdrawLighter.fastDisclaimerUnified')\n : t('withdrawLighter.fastDisclaimer'),\n },\n {\n id: LIGHTER_SECURE_METHOD_ID,\n title: t('withdrawLighter.methodSecure'),\n subtitle: t('withdrawLighter.secureDisclaimer', {\n // Until the live value loads, show the localized \"60+ minutes\"\n // historical estimate. The \"+\" lives in the per-locale fallback\n // string so it doesn't bleed into live values, which are exact.\n delay:\n secureDelayText ?? t('withdrawLighter.secureFallbackDelay'),\n }),\n },\n ]\n : []\n\n return {\n methods,\n accountIndex,\n isUnifiedTradingMode,\n isLoading: !!config && isLoading,\n }\n}\n", "import type { LighterRouteType } from '@funkit/connect-core/clients/lighter'\nimport type { LighterSigner } from '@funkit/connect-core/clients/lighter'\nimport type { Address } from 'viem'\n\nimport type { WithdrawalSourceTokenParams } from '../../src/flow/withdrawalFlowConfig'\n\n/** Stable ids for the two rails \u2014 used for row identity, routing and logs. */\nexport const LIGHTER_FAST_METHOD_ID = 'lighter-fast'\nexport const LIGHTER_SECURE_METHOD_ID = 'lighter-secure'\n\n/** What the host must implement to submit a Secure withdrawal on Lighter's L2. */\nexport interface LighterSecureWithdrawalParams {\n /** Withdrawal amount in token units (e.g. \"1.5\" for 1.5 ETH). */\n amountTokenUnits: string\n /** The Lighter asset index (e.g. 1 for ETH, 3 for USDC). */\n assetIndex: number\n /**\n * 0 = perps / USDC collateral, 1 = spot. USDC shares asset index 3 across\n * both routes, so the route type is what selects Perps vs Spot.\n */\n routeType: LighterRouteType\n}\n\n/**\n * Lighter withdrawal, as the host configures it. Mirrors web's\n * `LighterWithdrawalConfig` (`@funkit/connect/clients/lighter`) so an\n * integrator's web and mobile wiring read the same.\n *\n * Passed on `WithdrawalFlowConfig.lighter`; its presence is what turns the\n * withdrawal flow's single crypto row into the Fast / Secure pair.\n */\nexport interface LighterWithdrawalFlowConfig {\n /**\n * The connected user's L1 address. The SDK resolves the L2 main-account\n * index from it \u2014 Lighter addresses accounts by index, not by address.\n */\n l1Address: Address\n /**\n * Host-built Lighter L2 signer, used by the Fast rail's relay adapter. The\n * SDK never holds L2 key material.\n */\n signerClient: LighterSigner\n /**\n * Submits the Secure withdrawal on Lighter's L2 and resolves with the L2 tx\n * hash. Funds bridge directly to Ethereum mainnet \u2014 no relay, no swap.\n */\n sendLighterSecureWithdrawal: (\n params: LighterSecureWithdrawalParams,\n ) => Promise<string>\n /**\n * Withdrawable balance for the selected source token, applied to both rails.\n * Lighter's own accounting \u2014 it must account for what the SDK cannot see\n * (margin requirements, locked collateral), so the integrator owns it.\n */\n withdrawalSourceTokenBalance?: (\n params: WithdrawalSourceTokenParams,\n ) => string | number\n /**\n * Minimum Secure withdrawal in token units. Takes the same\n * {@link WithdrawalSourceTokenParams} as every other source-token callback,\n * so the shape carries over to any venue rather than being symbol-only.\n * Perps and spot USDC stay distinguishable \u2014 they are separate source tokens\n * with their own addresses. Return `undefined` for the default.\n */\n getSecureMinWithdrawalAmount?: (\n params: WithdrawalSourceTokenParams,\n ) => number | undefined\n /**\n * Awaited after the user taps Withdraw but before either rail fetches a\n * nonce, prompts, or submits.\n *\n * Lighter strategies and withdrawals share one L2 signing account, so a\n * strategy still placing or cancelling orders bumps the nonce out from under\n * the withdrawal and the signed tx is rejected. Cancel in-flight strategies\n * here so the withdrawal signs against a stable nonce. Throw to abort \u2014 no\n * nonce is consumed.\n */\n onBeforeSign?: () => Promise<void> | void\n}\n", "import { type WithdrawalClient } from '@funkit/connect-core'\nimport { LIGHTER_FAST_MAX_WITHDRAWAL_USD } from '@funkit/connect-core/clients/lighter'\nimport { createLighterAdaptedWallet } from '@funkit/connect-core/clients/lighter'\nimport { LIGHTER_CHAIN_ID } from '@funkit/chains'\nimport type { Address } from 'viem'\n\nimport type { WithdrawalFlowConfig } from '../../src/flow/withdrawalFlowConfig'\nimport { logger } from '../../src/logging/logger'\nimport type { LighterWithdrawalFlowConfig } from './lighterWithdrawalConfig'\n\n/**\n * Lighter USDC Perps, addressed as relay does: the zero address maps to relay\n * asset '0' via `RELAY_LIGHTER_FUN_ADDRESS_MAP` in fun-relay.\n */\nconst LIGHTER_USDC_PERPS_ADDRESS =\n '0x0000000000000000000000000000000000000000' as Address\n\n/** Same id relay calls `RELAY_LIGHTER_CHAIN_ID`; the config carries it as a string. */\nconst LIGHTER_SOURCE_CHAIN_ID = `${LIGHTER_CHAIN_ID}`\n\n/** Fast is USDC-only, so web's USD floor is also its token-unit floor. */\nconst LIGHTER_FAST_MIN_WITHDRAWAL_USD = 4\n\n/**\n * Wraps the host's signer so `onBeforeSign` is awaited before the first\n * transfer. Lighter strategies and withdrawals share one L2 signing account, so\n * an in-flight strategy would bump the nonce out from under a Fast withdrawal\n * exactly as it would a Secure one. Throwing aborts before any nonce is used.\n */\nfunction withPreSignHook(\n signerClient: LighterWithdrawalFlowConfig['signerClient'],\n onBeforeSign: LighterWithdrawalFlowConfig['onBeforeSign'],\n): LighterWithdrawalFlowConfig['signerClient'] {\n if (!onBeforeSign) {\n return signerClient\n }\n return {\n ...signerClient,\n transfer: async (params) => {\n await onBeforeSign()\n return signerClient.transfer(params)\n },\n }\n}\n\n/**\n * A {@link WithdrawalClient} for Lighter Fast. Relay drives `adaptedWallet`\n * directly \u2014 the EVM members exist to satisfy the interface and to throw\n * loudly if something ever routes an EVM leg through this client, which for\n * Fast would mean signing on the wrong rail.\n *\n * `address()` is the L2 account index, not an EVM address: Lighter addresses\n * accounts by index, and that is what relay and the tracking row record.\n */\nexport function createLighterFastWithdrawalClient({\n signerClient,\n accountIndex,\n onBeforeSign,\n}: {\n signerClient: LighterWithdrawalFlowConfig['signerClient']\n accountIndex: string\n /**\n * Host hook awaited before the first L2 signature. Relay drives the adapter,\n * so the only point Fast controls is the signer itself.\n */\n onBeforeSign?: LighterWithdrawalFlowConfig['onBeforeSign']\n // The adapter is narrowed to Lighter's own wallet: the interface field is\n // relay's per-VM union, and callers of this client know which vm they got.\n}): WithdrawalClient & {\n adaptedWallet: ReturnType<typeof createLighterAdaptedWallet>\n} {\n // Fail here rather than let a NaN account index reach relay, where it\n // surfaces much later as an unattributable signing failure.\n if (!/^\\d+$/.test(accountIndex)) {\n throw new Error(\n `Lighter Fast needs a numeric account index, got: ${accountIndex}`,\n )\n }\n return {\n adaptedWallet: createLighterAdaptedWallet({\n signerClient: withPreSignHook(signerClient, onBeforeSign),\n accountIndex: Number(accountIndex),\n logger,\n }),\n address: () => accountIndex,\n getChainId: async () => LIGHTER_CHAIN_ID,\n // Lighter is single-chain \u2014 nothing to switch to.\n switchChain: async () => undefined,\n sendTransaction: async () => {\n throw new Error('Lighter Fast executes through its relay adapter')\n },\n confirmTransaction: async () => {\n throw new Error('Lighter Fast executes through its relay adapter')\n },\n }\n}\n\n/**\n * The withdrawal the crypto rail runs for Lighter Fast: USDC Perps out of the\n * user's L2 account, quoted and executed through Fun + Relay to any supported\n * destination. Port of web's `buildLighterFastWalletWithdrawalConfig`.\n *\n * Limits are web's USD numbers expressed in token units. Fast is USDC-only, so\n * the two are the same number; RN has no price feed yet, and a USD limit\n * without one is inert (see `withdrawal/validation.ts`).\n */\nexport function buildLighterFastWithdrawalConfig({\n config,\n lighter,\n accountIndex,\n isUnifiedTradingMode,\n}: {\n /** The host's withdrawal config \u2014 title and callbacks carry over. */\n config: WithdrawalFlowConfig\n lighter: LighterWithdrawalFlowConfig\n accountIndex: string\n /** Unified accounts hold one USDC balance, so the label drops \"(Perps)\". */\n isUnifiedTradingMode: boolean\n}): WithdrawalFlowConfig {\n const sourceToken = {\n chainId: LIGHTER_SOURCE_CHAIN_ID,\n address: LIGHTER_USDC_PERPS_ADDRESS,\n symbol: 'USDC',\n decimals: 6,\n }\n return {\n ...config,\n sourceToken,\n sourceTokens: [\n {\n token: sourceToken,\n label: isUnifiedTradingMode ? 'USDC' : 'USDC (Perps)',\n },\n ],\n withdrawalSourceTokenBalance: lighter.withdrawalSourceTokenBalance,\n defaultReceiveToken: 'USDC',\n withdrawalWallet: createLighterFastWithdrawalClient({\n signerClient: lighter.signerClient,\n accountIndex,\n onBeforeSign: lighter.onBeforeSign,\n }),\n // Both in token units, not USD: the price API can't resolve Lighter's\n // source (an L2 balance behind a pseudo-address), and a USD bound with no\n // price silently goes unenforced. Fast is USDC-only, so the numbers match.\n getMinWithdrawalAmount: () => LIGHTER_FAST_MIN_WITHDRAWAL_USD,\n getMaxWithdrawalAmount: () => LIGHTER_FAST_MAX_WITHDRAWAL_USD,\n }\n}\n", "import type { LighterAccountIndex } from '@funkit/api-base'\nimport { useLogOnce } from '@funkit/connect-core'\nimport { useLighterFastUnstakedFeeTokens } from '@funkit/connect-core/clients/lighter'\n\nimport { logger } from '../../src/logging/logger'\n\n/**\n * The Lighter Fast \"unstaked fee\": a flat deduction taken off the withdrawal\n * before quoting, waived for users staked at or above Lighter's own threshold.\n *\n * Reads Lighter's `transferFeeInfo` endpoint (via `useLighterFastUnstakedFeeTokens`)\n * rather than deriving the fee from share price locally \u2014 Lighter's backend\n * already knows the account's stake. `feeTokens` is 0 while the lookup is in\n * flight and for every non-Fast caller; a failed lookup fails closed to the\n * flat historical fee rather than 0. Callers must wait for `isFetched` before\n * quoting off `feeTokens` \u2014 see `quoteInputFeeSettled`.\n */\nexport function useLighterUnstakedFee({\n accountIndex,\n enabled,\n}: {\n accountIndex: string | undefined\n /** Fast only \u2014 Secure charges no such fee. */\n enabled: boolean\n}): {\n feeTokens: number\n /** `true` for a non-Fast caller: nothing to wait on. */\n isFetched: boolean\n} {\n const isEnabled = enabled && !!accountIndex\n const { feeTokens, isFetched, isError } = useLighterFastUnstakedFeeTokens({\n accountIndex: isEnabled ? (accountIndex as LighterAccountIndex) : undefined,\n enabled: isEnabled,\n })\n\n useLogOnce(\n isEnabled && isFetched\n ? `${accountIndex}|${isError}|${feeTokens}`\n : undefined,\n () => {\n if (isError) {\n // The fee is charged from Lighter's own view of the stake, which we\n // could not read \u2014 so it is applied blind and worth surfacing.\n logger.warn('lighter:fast:unstaked-fee:account-unavailable', {\n accountIndex,\n unstakedFeeTokens: feeTokens,\n })\n return\n }\n logger.info('lighter:fast:unstaked-fee:resolved', {\n accountIndex,\n unstakedFeeTokens: feeTokens,\n })\n },\n )\n\n return { feeTokens, isFetched: !isEnabled || isFetched }\n}\n", "import type {\n WithdrawalFlowConfig,\n WithdrawalMethodOption,\n} from '../../src/flow/withdrawalFlowConfig'\nimport { buildLighterFastWithdrawalConfig } from './lighterFastWithdrawal'\nimport { LIGHTER_FAST_METHOD_ID } from './lighterWithdrawalConfig'\nimport type { LighterWithdrawalFlowConfig } from './lighterWithdrawalConfig'\nimport { useLighterUnstakedFee } from './useLighterUnstakedFee'\nimport { useLighterWithdrawalMethods } from './useLighterWithdrawalMethods'\n\n/**\n * The Lighter methods to hand `beginWithdrawal`, each carrying the config it\n * runs. Mirrors web's `useLighterWithdrawalConfig`: the host calls this and\n * passes the result on, so the SDK never holds Lighter config.\n *\n * Empty until the L2 account resolves \u2014 both rails address the account by\n * index, so there is nothing to offer before then, and the flow falls back to\n * its generic crypto row.\n */\nexport function useLighterWithdrawal({\n lighter,\n config,\n}: {\n lighter: LighterWithdrawalFlowConfig | undefined\n /**\n * The host's own withdrawal config; title and callbacks carry over. Absent\n * until the host has one \u2014 a hook can't be called conditionally, so there is\n * no placeholder worth inventing.\n */\n config: WithdrawalFlowConfig | undefined\n}): WithdrawalMethodOption[] {\n const { methods, accountIndex, isUnifiedTradingMode } =\n useLighterWithdrawalMethods(lighter)\n // Fast only; Secure charges no such fee. Keyed off the row actually being\n // offered, so the two account lookups stay off the wire when it isn't.\n const isFastOffered = methods.some(\n (method) => method.id === LIGHTER_FAST_METHOD_ID,\n )\n const { feeTokens: quoteInputFeeTokens, isFetched: quoteInputFeeSettled } =\n useLighterUnstakedFee({\n accountIndex,\n enabled: isFastOffered,\n })\n\n if (!lighter || !config || !accountIndex) {\n return []\n }\n\n // Native Bridge is filtered out: its screens have not shipped, and a row\n // that fails on tap is worse than no row.\n return methods\n .filter((method) => method.id === LIGHTER_FAST_METHOD_ID)\n .map((method) => ({\n id: method.id,\n title: method.title,\n subtitle: method.subtitle,\n config: {\n ...buildLighterFastWithdrawalConfig({\n config,\n lighter,\n accountIndex,\n isUnifiedTradingMode,\n }),\n // Lighter takes this off the amount before it is quoted.\n quoteInputFeeTokens,\n quoteInputFeeSettled,\n },\n }))\n}\n", "import { isUserRejectedError } from '@funkit/connect-core'\nimport {\n type LighterRouteType,\n getLighterBaseSymbol,\n getLighterSecureMainnetAddress,\n trackLighterSecureWithdrawal,\n} from '@funkit/connect-core/clients/lighter'\nimport { useCallback, useRef, useState } from 'react'\nimport type { Address } from 'viem'\n\nimport { useFunkitIdentity } from '../../src/identity/IdentityContext'\nimport { logger } from '../../src/logging/logger'\nimport type { LighterWithdrawalFlowConfig } from './lighterWithdrawalConfig'\n\n// Module-scoped: closing the sheet mid-withdrawal unmounts the hook, and the\n// fresh one a reopen mounts would know nothing about the in-flight submission.\nconst inFlightSecureWithdrawals = new Set<string>()\n\n/** What makes two presses the same withdrawal rather than two of them. */\nfunction secureWithdrawalKey({\n accountIndex,\n assetIndex,\n routeType,\n amountTokenUnits,\n}: {\n accountIndex: string\n assetIndex: number\n routeType: LighterRouteType\n amountTokenUnits: string\n}): string {\n return [accountIndex, assetIndex, routeType, amountTokenUnits].join('|')\n}\n\n/**\n * @internal Test-only: clear the process-wide in-flight set so suites that\n * reuse withdrawal details stay isolated. Not part of the public API.\n */\nexport function __resetInFlightSecureWithdrawals(): void {\n inFlightSecureWithdrawals.clear()\n}\n\nexport type LighterSecureSubmission =\n | { status: 'idle' }\n | { status: 'submitting' }\n | { status: 'submitted'; txHash: string; amountTokenUnits: string }\n // Carries the message, not the error: Lighter's SDK surfaces rate limits and\n // nonce collisions as plain strings the screen classifies for itself.\n | { status: 'failed'; message: string }\n\nexport interface UseLighterSecureWithdrawalParams {\n lighter: LighterWithdrawalFlowConfig\n /** The user's L2 main-account index \u2014 also the tracking key. */\n accountIndex: string | undefined\n /** Connected wallet: Secure locks the destination to it. */\n recipientAddress: Address\n}\n\n/**\n * Submits a Lighter Secure withdrawal: the host's L2 signer bridges the asset\n * to Ethereum 1:1, with no relay and no quote in the path. Fun is not in that\n * path, so the direct-execution row is attribution only and fire-and-forget.\n */\nexport function useLighterSecureWithdrawal({\n lighter,\n accountIndex,\n recipientAddress,\n}: UseLighterSecureWithdrawalParams) {\n const { apiKey } = useFunkitIdentity()\n const isSubmittingRef = useRef(false)\n const [submission, setSubmission] = useState<LighterSecureSubmission>({\n status: 'idle',\n })\n\n const submit = useCallback(\n async ({\n amountTokenUnits,\n assetIndex,\n routeType,\n sourceSymbol,\n withdrawalUSD,\n }: {\n amountTokenUnits: string\n /** Resolved from the account's asset list; never guessed. */\n assetIndex: number\n routeType: LighterRouteType\n /** May carry a ` (Spot)` suffix \u2014 tracking wants the base symbol. */\n sourceSymbol: string\n /** Token amount \u00D7 spot price, for attribution. '0' when unpriced. */\n withdrawalUSD: string\n }) => {\n if (!accountIndex) {\n // Neither rail can address the user without it; the screen blocks the\n // CTA on the same condition, so this is a belt-and-braces guard.\n logger.warn('lighter:withdrawal:secure:noAccountIndex')\n return\n }\n if (isSubmittingRef.current) {\n logger.warn('lighter:withdrawal:secure:already_submitting')\n return\n }\n const key = secureWithdrawalKey({\n accountIndex,\n assetIndex,\n routeType,\n amountTokenUnits,\n })\n if (inFlightSecureWithdrawals.has(key)) {\n logger.warn('lighter:withdrawal:secure:already_in_flight')\n return\n }\n isSubmittingRef.current = true\n inFlightSecureWithdrawals.add(key)\n setSubmission({ status: 'submitting' })\n\n let txHash: string\n try {\n // Lighter strategies and withdrawals share one L2 signing account, so\n // an in-flight strategy would bump the nonce out from under this.\n await lighter.onBeforeSign?.()\n\n logger.info('lighter:withdrawal:secure:start', {\n assetIndex,\n routeType,\n amountTokenUnits,\n destinationAddress: recipientAddress,\n })\n txHash = await lighter.sendLighterSecureWithdrawal({\n amountTokenUnits,\n assetIndex,\n routeType,\n })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (isUserRejectedError(error)) {\n // Declining is recoverable \u2014 the form stays as it was.\n logger.warn('lighter:withdrawal:secure:user_rejected')\n setSubmission({ status: 'idle' })\n return\n }\n // Recovered: the screen offers the on-chain fallback for a rate limit,\n // and a retry otherwise. Not an alertable ERROR.\n logger.warn('lighter:withdrawal:secure:failed', {\n error: message,\n assetIndex,\n routeType,\n })\n setSubmission({ status: 'failed', message })\n return\n } finally {\n isSubmittingRef.current = false\n inFlightSecureWithdrawals.delete(key)\n }\n\n logger.info('lighter:withdrawal:secure:submitted', {\n amountTokenUnits,\n assetIndex,\n routeType,\n txHash,\n })\n\n const mainnetTokenAddress = getLighterSecureMainnetAddress(sourceSymbol)\n if (mainnetTokenAddress) {\n // Fire-and-forget \u2014 never block the success screen on tracking.\n void trackLighterSecureWithdrawal({\n apiKey,\n logger,\n // Secure locks the destination to the connected wallet, so the L1\n // recipient address doubles as the userId for tracking purposes.\n userId: recipientAddress,\n txHash,\n recipientAddr: recipientAddress,\n assetIndex,\n mainnetTokenAddress,\n amountTokenUnits,\n withdrawalUSD,\n })\n } else {\n // Attribution only, so a symbol we can't map is a monitoring problem,\n // not a user-facing one.\n logger.warn('lighter:withdrawal:secure:unknownMainnetToken', {\n sourceSymbol: getLighterBaseSymbol(sourceSymbol),\n txHash,\n })\n }\n\n setSubmission({ status: 'submitted', txHash, amountTokenUnits })\n },\n [apiKey, accountIndex, lighter, recipientAddress],\n )\n\n const reset = useCallback(() => setSubmission({ status: 'idle' }), [])\n\n return { submission, submit, reset }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
5
|
+
"mappings": ";;;;;;;;;AAAA,SAAS,+BAA+B;AACxC,SAAS,iCAAiC;AAC1C,SAAS,gBAAgB;AAEzB,SAAS,WAAW,cAAc;;;ACG3B,IAAM,yBAAyB;AAC/B,IAAM,2BAA2B;;;AD2BxC,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AACzB,IAAM,mBAAmB,qBAAqB;AAW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AQ,iBAAiB,CAAC;AAAA,IACjE;AAAA,IACA,CAAC,QAAQ,cAAc,SAAS,gBAAgB;AAAA,EAClD;AAEA,QAAM,QAAQ,YAAY,MAAM,cAAc,EAAE,QAAQ,OAAO,CAAC,GAAG,CAAC,CAAC;AAErE,SAAO,EAAE,YAAY,QAAQ,MAAM;AACrC;",
|
|
6
6
|
"names": ["useRef", "useRef"]
|
|
7
7
|
}
|
package/dist/clients/nado.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useSourceTokenUsdPrice
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-75U7A2Q5.js";
|
|
4
4
|
import {
|
|
5
5
|
i18n,
|
|
6
|
-
logger,
|
|
7
6
|
useFunkitTranslation
|
|
8
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-4YNYOJJK.js";
|
|
8
|
+
import {
|
|
9
|
+
logger
|
|
10
|
+
} from "../chunk-D64EJ57D.js";
|
|
9
11
|
|
|
10
12
|
// clients/nado/useNadoWithdrawal.ts
|
|
11
13
|
import {
|
|
@@ -366,7 +368,7 @@ function useNadoWithdrawal({
|
|
|
366
368
|
symbol: sourceOption.symbol,
|
|
367
369
|
decimals: sourceOption.decimals
|
|
368
370
|
};
|
|
369
|
-
const sourceTokenUsdPrice = useSourceTokenUsdPrice(sourceToken);
|
|
371
|
+
const { data: sourceTokenUsdPrice } = useSourceTokenUsdPrice(sourceToken);
|
|
370
372
|
const invalidateMaxWithdrawable = useInvalidateNadoMaxWithdrawable();
|
|
371
373
|
const hasMaximum = maxWithdrawableX18 !== void 0;
|
|
372
374
|
if (!nado || !config?.withdrawalWallet || !subaccount || !isFeeSettled || !isMaxSettled) {
|
package/dist/clients/nado.js.map
CHANGED
|
@@ -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": "
|
|
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(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U,aAAa;AAAA,QACzB,CAAC,IACH;AAAA,QACJ,qBAAqB,OAAO,uBAAuB,aAAa;AAAA,QAChE,wBACE,OAAO,2BAA2B,MAAM;AAAA;AAAA,QAE1C,qBAAqB,aAAa;AAAA,QAClC,mBAAmB,aAAa,cAAc;AAAA,QAC9C,kBAAkB,2BAA2B;AAAA,UAC3C;AAAA,UACA;AAAA,UACA,aAAa;AAAA,UACb,QAAQ,OAAO;AAAA,UACf,aAAa;AAAA,QACf,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,kBACP,MACiB;AACjB,QAAM,EAAE,eAAe,eAAe,IAAI,QAAQ,CAAC;AACnD,SAAO;AAAA,IACL,MAAM,sBAAsB,EAAE,eAAe,gBAAgB,OAAO,CAAC;AAAA,IACrE,CAAC,eAAe,cAAc;AAAA,EAChC;AACF;",
|
|
6
6
|
"names": ["INK_CHAIN_ID", "INK_CHAIN_ID"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { useSolanaWithdrawal } from './useSolanaWithdrawal';
|
|
2
|
+
export { SOLANA_USDC_MINT, SOLANA_USDC_SOURCE_TOKEN, buildSolanaWithdrawalConfig, } from './solanaWithdrawal';
|
|
3
|
+
export type { SolanaHostWithdrawalConfig, SolanaWithdrawalFlowConfig, } from './solanaWithdrawal';
|
|
4
|
+
export type { SolanaWalletSigner } from '@funkit/connect-core/clients/solana';
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../clients/solana/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA;AAC3D,OAAO,EACL,gBAAgB,EAChB,wBAAwB,EACxB,2BAA2B,GAC5B,MAAM,oBAAoB,CAAA;AAC3B,YAAY,EACV,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,oBAAoB,CAAA;AAC3B,YAAY,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAA"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { SolanaAddress } from '@funkit/api-base';
|
|
2
|
+
import type { WithdrawalClient } from '@funkit/connect-core';
|
|
3
|
+
import type { SolanaWalletSigner } from '@funkit/connect-core/clients/solana';
|
|
4
|
+
import type { WithdrawalFlowConfig, WithdrawalToken } from '../../src/flow/withdrawalFlowConfig';
|
|
5
|
+
/** The only Solana source offered today. */
|
|
6
|
+
export declare const SOLANA_USDC_MINT: SolanaAddress;
|
|
7
|
+
/** USDC on Solana as the rail's source token. */
|
|
8
|
+
export declare const SOLANA_USDC_SOURCE_TOKEN: WithdrawalToken;
|
|
9
|
+
/** A Solana withdrawal, as the host configures it. */
|
|
10
|
+
export interface SolanaWithdrawalFlowConfig {
|
|
11
|
+
/** The host's connected Solana wallet. The SDK never holds key material. */
|
|
12
|
+
signer: SolanaWalletSigner;
|
|
13
|
+
}
|
|
14
|
+
/** Everything the host sets that is not decided by the Solana source. */
|
|
15
|
+
export type SolanaHostWithdrawalConfig = Omit<WithdrawalFlowConfig, 'sourceToken' | 'sourceTokens' | 'withdrawalWallet' | 'swappedAcceptedToken'>;
|
|
16
|
+
export declare function buildSolanaWithdrawalConfig({ config, withdrawalWallet, }: {
|
|
17
|
+
config: SolanaHostWithdrawalConfig;
|
|
18
|
+
withdrawalWallet: WithdrawalClient;
|
|
19
|
+
}): WithdrawalFlowConfig;
|
|
20
|
+
//# sourceMappingURL=solanaWithdrawal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"solanaWithdrawal.d.ts","sourceRoot":"","sources":["../../../clients/solana/solanaWithdrawal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAErD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AAC5D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAA;AAG7E,OAAO,KAAK,EACV,oBAAoB,EACpB,eAAe,EAChB,MAAM,qCAAqC,CAAA;AAE5C,4CAA4C;AAC5C,eAAO,MAAM,gBAAgB,EACuB,aAAa,CAAA;AAEjE,iDAAiD;AACjD,eAAO,MAAM,wBAAwB,EAAE,eAMtC,CAAA;AAED,sDAAsD;AACtD,MAAM,WAAW,0BAA0B;IACzC,4EAA4E;IAC5E,MAAM,EAAE,kBAAkB,CAAA;CAC3B;AAED,yEAAyE;AACzE,MAAM,MAAM,0BAA0B,GAAG,IAAI,CAC3C,oBAAoB,EACpB,aAAa,GAAG,cAAc,GAAG,kBAAkB,GAAG,sBAAsB,CAC7E,CAAA;AAED,wBAAgB,2BAA2B,CAAC,EAC1C,MAAM,EACN,gBAAgB,GACjB,EAAE;IACD,MAAM,EAAE,0BAA0B,CAAA;IAClC,gBAAgB,EAAE,gBAAgB,CAAA;CACnC,GAAG,oBAAoB,CAcvB"}
|