@velora-dex/widget 0.0.19 → 0.0.21
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/dist/hooks/permit/hooks/permit2/usePermit2TransferFromNonce.d.ts.map +1 -1
- package/dist/hooks/permit/hooks/permit2/usePermit2TransferFromNonce.js +2 -1
- package/dist/hooks/permit/hooks/permit2/usePermit2TransferFromNonce.js.map +1 -1
- package/dist/hooks/swap/prices/delta/queries/useWatchDeltaOrder.d.ts.map +1 -1
- package/dist/hooks/swap/prices/delta/queries/useWatchDeltaOrder.js +2 -1
- package/dist/hooks/swap/prices/delta/queries/useWatchDeltaOrder.js.map +1 -1
- package/dist/hooks/tokens/balances/useInvalidateTokenData.d.ts.map +1 -1
- package/dist/hooks/tokens/balances/useInvalidateTokenData.js +2 -1
- package/dist/hooks/tokens/balances/useInvalidateTokenData.js.map +1 -1
- package/dist/hooks/txs/queries/useAwaitTx.js +1 -1
- package/dist/hooks/txs/queries/useAwaitTx.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/lib/queryClient.d.ts +1 -0
- package/dist/lib/queryClient.d.ts.map +1 -1
- package/dist/lib/queryClient.js +5 -2
- package/dist/lib/queryClient.js.map +1 -1
- package/dist/test/Configurator.d.ts.map +1 -1
- package/dist/widget/types.d.ts +11 -2
- package/dist/widget/types.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usePermit2TransferFromNonce.d.ts","sourceRoot":"","sources":["../../../../../src/hooks/permit/hooks/permit2/usePermit2TransferFromNonce.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"usePermit2TransferFromNonce.d.ts","sourceRoot":"","sources":["../../../../../src/hooks/permit/hooks/permit2/usePermit2TransferFromNonce.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,mBAAmB,EACxB,KAAK,cAAc,EACpB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D"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { useQuery } from '@tanstack/react-query';
|
|
2
2
|
import { maxUint256 } from 'viem';
|
|
3
3
|
import { useConfig } from 'wagmi';
|
|
4
4
|
import { readContract } from '@wagmi/core';
|
|
@@ -6,6 +6,7 @@ import { assert } from 'ts-essentials';
|
|
|
6
6
|
import { PERMIT2_ABI } from '../../utils/abi.js';
|
|
7
7
|
import { PERMIT2_ADDRESS } from '../../utils/construct.js';
|
|
8
8
|
import { useLogger, getLogger } from '../../../../widget/logger.js';
|
|
9
|
+
import { useQueryClient } from '../../../../lib/queryClient.js';
|
|
9
10
|
|
|
10
11
|
const PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY = "permit2-nonce";
|
|
11
12
|
function usePermit2TransferFromNonce({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usePermit2TransferFromNonce.js","sources":["../../../../../src/hooks/permit/hooks/permit2/usePermit2TransferFromNonce.ts"],"sourcesContent":["import {\n useQuery,\n useQueryClient,\n type QueryObserverResult,\n type RefetchOptions,\n} from \"@tanstack/react-query\";\nimport { type Address, maxUint256 } from \"viem\";\nimport { useConfig, type Config } from \"wagmi\";\nimport { readContract } from \"@wagmi/core\";\nimport { assert } from \"ts-essentials\";\nimport { PERMIT2_ABI } from \"../../utils/abi\";\nimport { PERMIT2_ADDRESS } from \"../../utils/construct\";\nimport { getLogger, useLogger } from \"@/widget/logger\";\n\n/**\n * Permit2 stores nonces using a nested bitmap structure:\n *\n * mapping(address => mapping(uint256 => uint256)) public nonceBitmap;\n *\n * - The outer key (`address`) is the permit signer (the `owner`)\n * - The inner key (`uint256 word`) is the index of a 256-bit \"page\"\n * - The value (`uint256`) is the bitmap for that page — each bit (0 to 255) represents a nonce\n * - If bit `i` is `0`, then nonce `word * 256 + i` is **unused**\n * - If bit `i` is `1`, then that nonce has **already been used**\n *\n * This is what enables Permit2 to support unordered nonces while saving gas.\n */\n\n// Result of finding an available nonce\ntype NonceState = {\n word: bigint; // which 256-bit \"page\" of the bitmap we used\n bitmap: bigint; // the bitmap for that word\n nonce: bigint; // full 256-based offset: word * 256 + bit index\n};\n\nconst PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY = \"permit2-nonce\";\n\ntype Permit2TransferFromQueryKey = [\n typeof PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY,\n owner?: Address,\n chainId?: number,\n];\n\ninterface UsePermit2TransferFromNonceOptions {\n owner?: Address;\n chainId?: number;\n initWord?: bigint; // word offset to begin scanning from\n enabled?: boolean;\n}\n\nexport type UsePermit2TransferFromNonceResult = {\n // null when no can't calculate Permit2 nonce\n nonceToUse?: bigint | null;\n nonceState?: NonceState | null;\n isLoading: boolean;\n isError: boolean;\n isSuccess: boolean;\n error: Error | null;\n refetch: (\n options?: RefetchOptions\n ) => Promise<QueryObserverResult<NonceState | null, Error>>;\n};\n\n/**\n * React hook to find the next unused Permit2 nonce for `permitTransferFrom`.\n *\n * Permit2 stores nonces as a bitmap:\n * - Each address has a mapping from uint256 => uint256\n * - Each value is a 256-bit bitmap (called a \"word\")\n * - If a bit is 1, the nonce (word * 256 + bit index) is used\n * - If it's 0, it's free and can be used\n */\nexport function usePermit2TransferFromNonce({\n owner,\n chainId,\n initWord = 0n,\n enabled = true,\n}: UsePermit2TransferFromNonceOptions) {\n const queryClient = useQueryClient();\n const config = useConfig();\n const logger = useLogger(\"PERMIT2::TransferFromNonce\");\n\n const queryKey: Permit2TransferFromQueryKey = [\n PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY,\n owner,\n chainId,\n ];\n\n const {\n data: nonceState,\n isLoading,\n isError,\n isSuccess,\n error,\n refetch,\n } = useQuery<\n NonceState | null,\n Error,\n NonceState | null,\n Permit2TransferFromQueryKey\n >({\n enabled: enabled && !!(owner && chainId),\n\n queryKey,\n\n queryFn: async () => {\n // Safety checks\n assert(owner, \"owner is required\");\n assert(chainId, \"chainId is required\");\n\n // Try to resume scanning from last known state if available\n const last = queryClient.getQueryData<NonceState>(queryKey);\n\n // Find a bitmap word that has at least one unused bit (i.e. a usable nonce)\n const nextOpenWord = await getNextOpenWord({\n owner,\n config,\n startWord: last?.word ?? initWord,\n });\n\n if (!nextOpenWord) {\n logger.warn(\"No available nonce found\");\n return null;\n }\n\n const { word, bitmap } = nextOpenWord;\n // Identify the first 0-bit in the bitmap — that’s our next nonce\n const bitPos = getFirstUnsetBit(bitmap);\n if (bitPos === -1) {\n logger.warn(\"No available nonce found\");\n return null;\n }\n\n const nonceState = {\n word,\n bitmap,\n nonce: word * 256n + BigInt(bitPos),\n };\n\n logger.log(\"nonceState\", nonceState);\n\n // The final usable nonce is: word * 256 + bit index\n return nonceState;\n },\n\n // Useful defaults\n refetchOnWindowFocus: false,\n notifyOnChangeProps: [\"data\", \"isLoading\"],\n });\n\n return {\n nonceState,\n nonceToUse: nonceState === null ? null : nonceState?.nonce,\n isLoading,\n isError,\n isSuccess,\n error,\n refetch,\n };\n}\n\ninterface GetNextOpenWordInput {\n owner: Address;\n config: Config;\n startWord: bigint;\n}\n\n/**\n * Scans bitmap word-by-word starting at `startWord` until it finds\n * one with at least one unused bit (i.e., not all bits are set to 1).\n */\nasync function getNextOpenWord({\n owner,\n config,\n startWord,\n}: GetNextOpenWordInput): Promise<{ word: bigint; bitmap: bigint } | null> {\n let word = startWord;\n const MAX = maxUint256; // full 256-bit word (0xffff...ffff)\n\n while (true) {\n // Read the bitmap word for the given owner and word index\n const bitmap = await readContract(config, {\n address: PERMIT2_ADDRESS,\n abi: PERMIT2_ABI,\n functionName: \"nonceBitmap\",\n args: [owner, word],\n });\n\n // If the bitmap is not fully used (i.e., not all bits are 1)\n if (bitmap !== MAX) {\n return { word, bitmap };\n }\n\n word += 1n;\n\n // Fail-safe: don't scan more than 1024 words (262,144 nonces)\n if (word - startWord > 1024n) {\n getLogger(\"PERMIT2::getNextOpenWord\").warn(\"Exceeded nonce search limit\");\n return null;\n }\n }\n}\n\n/**\n * Returns the index (0–255) of the first unset (zero) bit in a 256-bit bitmap.\n *\n * Uses a classic bit-hack: (~bitmap) & (bitmap + 1)\n *\n * This produces a bitmask with only the lowest 0-bit set to 1.\n * Example:\n * bitmap = 0b1110 → unset bit at index 0\n * ~bitmap = 0b...0001\n * bitmap + 1 = 0b1111\n * result = 0b0001 → bitmask for index 0\n *\n * We then convert the bitmask to binary and count how many bits it takes\n * to shift that 1 into place = its position.\n */\nfunction getFirstUnsetBit(bitmap: bigint): number {\n // Create a bitmask with a 1 only at the first 0-bit (LSB side)\n const mask = ~bitmap & (bitmap + 1n);\n\n // If all bits are set (mask is zero), there are no available nonces\n if (mask === 0n) return -1;\n\n // Convert mask to binary and count digits – the length is the index + 1\n // e.g. mask = 0b1000 → \"1000\" → length = 4 → index = 3\n return mask.toString(2).length - 1;\n}\n\n/////// MARK NONCE AS USED ///////\n\ntype SetNonceInput = {\n owner: Address;\n chainId: number;\n usedNonce: bigint;\n};\n\ntype UseMarkNonceAsUsedResult = {\n /**\n * Mark a nonce as \"used\" in the local cache after submitting a transaction or order\n * This prevents reuse of the same nonce while it's still pending on-chain.\n */\n markNonceAsUsed: (input: SetNonceInput) => void;\n};\n\n/**\n * Hook to manually bump the locally cached Permit2 nonce to avoid reuse\n *\n * Permit2 allows unordered nonces, but while a tx is pending, it's safer to use\n * a strictly increasing nonce to avoid accidental replays or reuse.\n *\n * clearing an unsued nonce is not necessary because nonces are unordered\n */\nexport function useMarkNonceAsUsed(): UseMarkNonceAsUsedResult {\n const queryClient = useQueryClient();\n\n const markNonceAsUsed: UseMarkNonceAsUsedResult[\"markNonceAsUsed\"] = ({\n owner,\n chainId,\n usedNonce,\n }) => {\n const queryKey: Permit2TransferFromQueryKey = [\n PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY,\n owner,\n chainId,\n ];\n\n // Update cached nonce state if the used nonce was >= current one\n queryClient.setQueryData<NonceState>(queryKey, (oldNonceState) => {\n if (!oldNonceState) return oldNonceState; // should not happen unless cache was cleared\n\n // If we're already past this nonce, nothing to do\n if (oldNonceState.nonce > usedNonce) return oldNonceState;\n\n const newNonce = oldNonceState.nonce + 1n;\n const { word, bitPos } = splitNonce(newNonce);\n\n return {\n word,\n bitmap: 1n << bitPos, // ✅ convert bit index to actual 256-bit bitmap\n nonce: newNonce,\n };\n });\n };\n\n return {\n markNonceAsUsed,\n };\n}\n\n/**\n * Splits a Permit2 nonce into:\n * - `word`: which 256-bit bitmap page (nonce / 256)\n * - `bitPos`: position within that word (nonce % 256)\n */\nfunction splitNonce(nonce: bigint): { word: bigint; bitPos: bigint } {\n const word = nonce / 256n;\n const bitPos = nonce % 256n;\n return { word, bitPos };\n}\n"],"names":["PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY","usePermit2TransferFromNonce","owner","chainId","initWord","enabled","queryClient","useQueryClient","config","useConfig","logger","useLogger","queryKey","data","nonceState","isLoading","isError","isSuccess","error","refetch","useQuery","queryFn","assert","last","getQueryData","nextOpenWord","getNextOpenWord","startWord","word","warn","bitmap","bitPos","getFirstUnsetBit","nonce","BigInt","log","refetchOnWindowFocus","notifyOnChangeProps","nonceToUse","MAX","maxUint256","readContract","address","PERMIT2_ADDRESS","abi","PERMIT2_ABI","functionName","args","getLogger","mask","toString","length","useMarkNonceAsUsed","markNonceAsUsed","usedNonce","setQueryData","oldNonceState","newNonce","splitNonce"],"mappings":";;;;;;;;;AAmCA,MAAMA,qCAAAA,GAAwC,eAAA;AAqCvC,SAASC,2BAAAA,CAA4B;AAAA,EAC1CC,KAAAA;AAAAA,EACAC,OAAAA;AAAAA,EACAC,QAAAA,GAAW,EAAA;AAAA,EACXC,OAAAA,GAAU;AACwB,CAAA,EAAG;AACrC,EAAA,MAAMC,cAAcC,cAAAA,EAAe;AACnC,EAAA,MAAMC,SAASC,SAAAA,EAAU;AACzB,EAAA,MAAMC,MAAAA,GAASC,UAAU,4BAA4B,CAAA;AAErD,EAAA,MAAMC,QAAAA,GAAwC,CAC5CZ,qCAAAA,EACAE,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AA,OAAO;AAAA,IAAEL,IAAAA;AAAAA,IAAMG;AAAAA,GAAO;AACxB;;;;"}
|
|
1
|
+
{"version":3,"file":"usePermit2TransferFromNonce.js","sources":["../../../../../src/hooks/permit/hooks/permit2/usePermit2TransferFromNonce.ts"],"sourcesContent":["import {\n useQuery,\n type QueryObserverResult,\n type RefetchOptions,\n} from \"@tanstack/react-query\";\nimport { type Address, maxUint256 } from \"viem\";\nimport { useConfig, type Config } from \"wagmi\";\nimport { readContract } from \"@wagmi/core\";\nimport { assert } from \"ts-essentials\";\nimport { PERMIT2_ABI } from \"../../utils/abi\";\nimport { PERMIT2_ADDRESS } from \"../../utils/construct\";\nimport { getLogger, useLogger } from \"@/widget/logger\";\nimport { useQueryClient } from \"@/lib/queryClient\";\n\n/**\n * Permit2 stores nonces using a nested bitmap structure:\n *\n * mapping(address => mapping(uint256 => uint256)) public nonceBitmap;\n *\n * - The outer key (`address`) is the permit signer (the `owner`)\n * - The inner key (`uint256 word`) is the index of a 256-bit \"page\"\n * - The value (`uint256`) is the bitmap for that page — each bit (0 to 255) represents a nonce\n * - If bit `i` is `0`, then nonce `word * 256 + i` is **unused**\n * - If bit `i` is `1`, then that nonce has **already been used**\n *\n * This is what enables Permit2 to support unordered nonces while saving gas.\n */\n\n// Result of finding an available nonce\ntype NonceState = {\n word: bigint; // which 256-bit \"page\" of the bitmap we used\n bitmap: bigint; // the bitmap for that word\n nonce: bigint; // full 256-based offset: word * 256 + bit index\n};\n\nconst PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY = \"permit2-nonce\";\n\ntype Permit2TransferFromQueryKey = [\n typeof PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY,\n owner?: Address,\n chainId?: number,\n];\n\ninterface UsePermit2TransferFromNonceOptions {\n owner?: Address;\n chainId?: number;\n initWord?: bigint; // word offset to begin scanning from\n enabled?: boolean;\n}\n\nexport type UsePermit2TransferFromNonceResult = {\n // null when no can't calculate Permit2 nonce\n nonceToUse?: bigint | null;\n nonceState?: NonceState | null;\n isLoading: boolean;\n isError: boolean;\n isSuccess: boolean;\n error: Error | null;\n refetch: (\n options?: RefetchOptions\n ) => Promise<QueryObserverResult<NonceState | null, Error>>;\n};\n\n/**\n * React hook to find the next unused Permit2 nonce for `permitTransferFrom`.\n *\n * Permit2 stores nonces as a bitmap:\n * - Each address has a mapping from uint256 => uint256\n * - Each value is a 256-bit bitmap (called a \"word\")\n * - If a bit is 1, the nonce (word * 256 + bit index) is used\n * - If it's 0, it's free and can be used\n */\nexport function usePermit2TransferFromNonce({\n owner,\n chainId,\n initWord = 0n,\n enabled = true,\n}: UsePermit2TransferFromNonceOptions) {\n const queryClient = useQueryClient();\n const config = useConfig();\n const logger = useLogger(\"PERMIT2::TransferFromNonce\");\n\n const queryKey: Permit2TransferFromQueryKey = [\n PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY,\n owner,\n chainId,\n ];\n\n const {\n data: nonceState,\n isLoading,\n isError,\n isSuccess,\n error,\n refetch,\n } = useQuery<\n NonceState | null,\n Error,\n NonceState | null,\n Permit2TransferFromQueryKey\n >({\n enabled: enabled && !!(owner && chainId),\n\n queryKey,\n\n queryFn: async () => {\n // Safety checks\n assert(owner, \"owner is required\");\n assert(chainId, \"chainId is required\");\n\n // Try to resume scanning from last known state if available\n const last = queryClient.getQueryData<NonceState>(queryKey);\n\n // Find a bitmap word that has at least one unused bit (i.e. a usable nonce)\n const nextOpenWord = await getNextOpenWord({\n owner,\n config,\n startWord: last?.word ?? initWord,\n });\n\n if (!nextOpenWord) {\n logger.warn(\"No available nonce found\");\n return null;\n }\n\n const { word, bitmap } = nextOpenWord;\n // Identify the first 0-bit in the bitmap — that’s our next nonce\n const bitPos = getFirstUnsetBit(bitmap);\n if (bitPos === -1) {\n logger.warn(\"No available nonce found\");\n return null;\n }\n\n const nonceState = {\n word,\n bitmap,\n nonce: word * 256n + BigInt(bitPos),\n };\n\n logger.log(\"nonceState\", nonceState);\n\n // The final usable nonce is: word * 256 + bit index\n return nonceState;\n },\n\n // Useful defaults\n refetchOnWindowFocus: false,\n notifyOnChangeProps: [\"data\", \"isLoading\"],\n });\n\n return {\n nonceState,\n nonceToUse: nonceState === null ? null : nonceState?.nonce,\n isLoading,\n isError,\n isSuccess,\n error,\n refetch,\n };\n}\n\ninterface GetNextOpenWordInput {\n owner: Address;\n config: Config;\n startWord: bigint;\n}\n\n/**\n * Scans bitmap word-by-word starting at `startWord` until it finds\n * one with at least one unused bit (i.e., not all bits are set to 1).\n */\nasync function getNextOpenWord({\n owner,\n config,\n startWord,\n}: GetNextOpenWordInput): Promise<{ word: bigint; bitmap: bigint } | null> {\n let word = startWord;\n const MAX = maxUint256; // full 256-bit word (0xffff...ffff)\n\n while (true) {\n // Read the bitmap word for the given owner and word index\n const bitmap = await readContract(config, {\n address: PERMIT2_ADDRESS,\n abi: PERMIT2_ABI,\n functionName: \"nonceBitmap\",\n args: [owner, word],\n });\n\n // If the bitmap is not fully used (i.e., not all bits are 1)\n if (bitmap !== MAX) {\n return { word, bitmap };\n }\n\n word += 1n;\n\n // Fail-safe: don't scan more than 1024 words (262,144 nonces)\n if (word - startWord > 1024n) {\n getLogger(\"PERMIT2::getNextOpenWord\").warn(\"Exceeded nonce search limit\");\n return null;\n }\n }\n}\n\n/**\n * Returns the index (0–255) of the first unset (zero) bit in a 256-bit bitmap.\n *\n * Uses a classic bit-hack: (~bitmap) & (bitmap + 1)\n *\n * This produces a bitmask with only the lowest 0-bit set to 1.\n * Example:\n * bitmap = 0b1110 → unset bit at index 0\n * ~bitmap = 0b...0001\n * bitmap + 1 = 0b1111\n * result = 0b0001 → bitmask for index 0\n *\n * We then convert the bitmask to binary and count how many bits it takes\n * to shift that 1 into place = its position.\n */\nfunction getFirstUnsetBit(bitmap: bigint): number {\n // Create a bitmask with a 1 only at the first 0-bit (LSB side)\n const mask = ~bitmap & (bitmap + 1n);\n\n // If all bits are set (mask is zero), there are no available nonces\n if (mask === 0n) return -1;\n\n // Convert mask to binary and count digits – the length is the index + 1\n // e.g. mask = 0b1000 → \"1000\" → length = 4 → index = 3\n return mask.toString(2).length - 1;\n}\n\n/////// MARK NONCE AS USED ///////\n\ntype SetNonceInput = {\n owner: Address;\n chainId: number;\n usedNonce: bigint;\n};\n\ntype UseMarkNonceAsUsedResult = {\n /**\n * Mark a nonce as \"used\" in the local cache after submitting a transaction or order\n * This prevents reuse of the same nonce while it's still pending on-chain.\n */\n markNonceAsUsed: (input: SetNonceInput) => void;\n};\n\n/**\n * Hook to manually bump the locally cached Permit2 nonce to avoid reuse\n *\n * Permit2 allows unordered nonces, but while a tx is pending, it's safer to use\n * a strictly increasing nonce to avoid accidental replays or reuse.\n *\n * clearing an unsued nonce is not necessary because nonces are unordered\n */\nexport function useMarkNonceAsUsed(): UseMarkNonceAsUsedResult {\n const queryClient = useQueryClient();\n\n const markNonceAsUsed: UseMarkNonceAsUsedResult[\"markNonceAsUsed\"] = ({\n owner,\n chainId,\n usedNonce,\n }) => {\n const queryKey: Permit2TransferFromQueryKey = [\n PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY,\n owner,\n chainId,\n ];\n\n // Update cached nonce state if the used nonce was >= current one\n queryClient.setQueryData<NonceState>(queryKey, (oldNonceState) => {\n if (!oldNonceState) return oldNonceState; // should not happen unless cache was cleared\n\n // If we're already past this nonce, nothing to do\n if (oldNonceState.nonce > usedNonce) return oldNonceState;\n\n const newNonce = oldNonceState.nonce + 1n;\n const { word, bitPos } = splitNonce(newNonce);\n\n return {\n word,\n bitmap: 1n << bitPos, // ✅ convert bit index to actual 256-bit bitmap\n nonce: newNonce,\n };\n });\n };\n\n return {\n markNonceAsUsed,\n };\n}\n\n/**\n * Splits a Permit2 nonce into:\n * - `word`: which 256-bit bitmap page (nonce / 256)\n * - `bitPos`: position within that word (nonce % 256)\n */\nfunction splitNonce(nonce: bigint): { word: bigint; bitPos: bigint } {\n const word = nonce / 256n;\n const bitPos = nonce % 256n;\n return { word, bitPos };\n}\n"],"names":["PERMIT2_TRANSFER_FROM_NONCE_QUERY_KEY","usePermit2TransferFromNonce","owner","chainId","initWord","enabled","queryClient","useQueryClient","config","useConfig","logger","useLogger","queryKey","data","nonceState","isLoading","isError","isSuccess","error","refetch","useQuery","queryFn","assert","last","getQueryData","nextOpenWord","getNextOpenWord","startWord","word","warn","bitmap","bitPos","getFirstUnsetBit","nonce","BigInt","log","refetchOnWindowFocus","notifyOnChangeProps","nonceToUse","MAX","maxUint256","readContract","address","PERMIT2_ADDRESS","abi","PERMIT2_ABI","functionName","args","getLogger","mask","toString","length","useMarkNonceAsUsed","markNonceAsUsed","usedNonce","setQueryData","oldNonceState","newNonce","splitNonce"],"mappings":";;;;;;;;;;AAmCA,MAAMA,qCAAAA,GAAwC,eAAA;AAqCvC,SAASC,2BAAAA,CAA4B;AAAA,EAC1CC,KAAAA;AAAAA,EACAC,OAAAA;AAAAA,EACAC,QAAAA,GAAW,EAAA;AAAA,EACXC,OAAAA,GAAU;AACwB,CAAA,EAAG;AACrC,EAAA,MAAMC,cAAcC,cAAAA,EAAe;AACnC,EAAA,MAAMC,SAASC,SAAAA,EAAU;AACzB,EAAA,MAAMC,MAAAA,GAASC,UAAU,4BAA4B,CAAA;AAErD,EAAA,MAAMC,QAAAA,GAAwC,CAC5CZ,qCAAAA,EACAE,KAAAA,EACAC,OAAO,CAAA;AAGT,EAAA,MAAM;AAAA,IACJU,IAAAA,EAAMC,YAAAA;AAAAA,IACNC,SAAAA;AAAAA,IACAC,OAAAA;AAAAA,IACAC,SAAAA;AAAAA,IACAC,KAAAA;AAAAA,IACAC;AAAAA,MACEC,QAAAA,CAKF;AAAA,IACAf,OAAAA,EAASA,OAAAA,IAAW,CAAC,EAAEH,KAAAA,IAASC,OAAAA,CAAAA;AAAAA,IAEhCS,QAAAA;AAAAA,IAEAS,SAAS,YAAY;AAEnBC,MAAAA,MAAAA,CAAOpB,OAAO,mBAAmB,CAAA;AACjCoB,MAAAA,MAAAA,CAAOnB,SAAS,qBAAqB,CAAA;AAGrC,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,GACF,KAAM;AACJ,IAAA,MAAM1C,QAAAA,GAAwC,CAC5CZ,qCAAAA,EACAE,KAAAA,EACAC,OAAO,CAAA;AAITG,IAAAA,WAAAA,CAAYiD,YAAAA,CAAyB3C,UAAW4C,CAAAA,aAAAA,KAAkB;AAChE,MAAA,IAAI,CAACA,eAAe,OAAOA,aAAAA;AAG3B,MAAA,IAAIA,aAAAA,CAAcvB,KAAAA,GAAQqB,SAAAA,EAAW,OAAOE,aAAAA;AAE5C,MAAA,MAAMC,QAAAA,GAAWD,cAAcvB,KAAAA,GAAQ,EAAA;AACvC,MAAA,MAAM;AAAA,QAAEL,IAAAA;AAAAA,QAAMG;AAAAA,OAAO,GAAI2B,WAAWD,QAAQ,CAAA;AAE5C,MAAA,OAAO;AAAA,QACL7B,IAAAA;AAAAA,QACAE,QAAQ,EAAA,IAAMC,MAAAA;AAAAA;AAAAA,QACdE,KAAAA,EAAOwB;AAAAA,OACT;AAAA,KACD,CAAA;AAAA,GACH;AAEA,EAAA,OAAO;AAAA,IACLJ;AAAAA,GACF;AACF;AAOA,SAASK,WAAWzB,KAAAA,EAAiD;AACnE,EAAA,MAAML,OAAOK,KAAAA,GAAQ,IAAA;AACrB,EAAA,MAAMF,SAASE,KAAAA,GAAQ,IAAA;AACvB,EAAA,OAAO;AAAA,IAAEL,IAAAA;AAAAA,IAAMG;AAAAA,GAAO;AACxB;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useWatchDeltaOrder.d.ts","sourceRoot":"","sources":["../../../../../../src/hooks/swap/prices/delta/queries/useWatchDeltaOrder.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"useWatchDeltaOrder.d.ts","sourceRoot":"","sources":["../../../../../../src/hooks/swap/prices/delta/queries/useWatchDeltaOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,cAAc,EACpB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAU,KAAK,YAAY,EA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AO,CAAC,EAAE,OAAO,CAAC;IAClB,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,oBAAoB,KAAK,IAAI,CAAC;IAC3D,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,kBAAkB,KAAK,IAAI,CAAC;IACzD,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,YAAY,EAAE,WAAW,CAAC,KAAK,IAAI,CAAC;IAC9E,qBAAqB,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,KAAK,IAAI,CAAC;CACrE,CAAC;AAEF,wBAAgB,0BAA0B,CAAC,EACzC,QAAQ,EACR,OAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,qBAAqB,GACtB,EAAE,0BAA0B,GAAG,cAAc,CAAC,uBAAuB,CAAC,EAAE,CA6CxE;AAED,KAAK,gCAAgC,GAAG;IACtC,MAAM,EAAE,iBAAiB,EAAE,CAAC;IAC5B,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;IACtD,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;IACtD,gBAAgB,CAAC,EAAE,CACjB,OAAO,EAAE,YAAY,CAAC,YAAY,EAAE,WAAW,CAAC,EAChD,cAAc,EAAE,sBAAsB,KACnC,IAAI,CAAC;CACX,CAAC;AAIF,wBAAgB,mCAAmC,CAAC,EAClD,MAAM,EACN,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,GACjB,EAAE,gCAAgC,GAAG,cAAc,CAAC,sBAAsB,CAAC,EAAE,CAuE7E"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { d as distExports } from '../../../../../_virtual/index.js';
|
|
2
|
-
import { useQuery,
|
|
2
|
+
import { useQuery, QueryObserver } from '@tanstack/react-query';
|
|
3
3
|
import { useRef, useLayoutEffect, useMemo } from 'react';
|
|
4
4
|
import { assert } from 'ts-essentials';
|
|
5
5
|
import { useDeltaSDK } from '../../../../useSDK.js';
|
|
6
6
|
import { isMetaWithTimeStart } from '../bridge/utils.js';
|
|
7
7
|
import { DeltaOrderStatusChecker, isExecutedDeltaAuction, isFailedDeltaAuction, isOrderExpired } from '../orders/utils.js';
|
|
8
8
|
import { useLogger, getLogger } from '../../../../../widget/logger.js';
|
|
9
|
+
import { useQueryClient } from '../../../../../lib/queryClient.js';
|
|
9
10
|
|
|
10
11
|
const SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX = "single_delta_auction";
|
|
11
12
|
const DELTA_ORDER_POLLING_INTERVAL = 3e3;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useWatchDeltaOrder.js","sources":["../../../../../../src/hooks/swap/prices/delta/queries/useWatchDeltaOrder.ts"],"sourcesContent":["import {\n QueryObserver,\n useQueries,\n useQuery,\n useQueryClient,\n type QueryMeta,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\nimport { useLayoutEffect, useMemo, useRef } from \"react\";\nimport { assert, type MarkOptional } from \"ts-essentials\";\nimport { useDeltaSDK } from \"@/hooks/useSDK\";\nimport type { DeltaOrderFromAPI } from \"./useDeltaOrders\";\nimport {\n isMetaWithTimeStart,\n type BridgedDepositResponseFailure,\n type BridgedDepositResponseSuccess,\n type GetBridgedDepositStatusInput,\n type RefetchMetaWithTiming,\n} from \"../bridge/utils\";\nimport type { BridgedDepositResponse } from \"../bridge/types\";\nimport { useBridgedDepositStatus } from \"../bridge/useBridgedDeposit\";\nimport type { DeltaAuction } from \"@velora-dex/sdk\";\nimport {\n DeltaOrderStatusChecker,\n isExecutedDeltaAuction,\n isFailedDeltaAuction,\n isOrderExpired,\n} from \"../orders/utils\";\nimport type { ExecutedDeltaAuction, FailedDeltaAuction } from \"../orders/types\";\nimport { getLogger, useLogger } from \"@/widget/logger\";\n\n// ------------------------------------ Single Delta Auction -----------------------------------\n\nconst SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX = \"single_delta_auction\";\ntype SingleDeltaAuctionQueryKey = [\n base: typeof SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX,\n orderId?: string,\n];\n\nexport type MaybeVeloraDeltaAuction = DeltaOrderFromAPI | null; // null is when no such Order for orderId\n\ntype UseDeltaAuctionQueryOptions<TData = MaybeVeloraDeltaAuction> =\n UseQueryOptions<\n MaybeVeloraDeltaAuction,\n Error,\n TData,\n SingleDeltaAuctionQueryKey\n >;\n\nconst DELTA_ORDER_POLLING_INTERVAL = 3_000;\n\ntype ConstructDeltaAuctionPollingQueryOptionsInput = {\n orderId?: string;\n enabled?: boolean;\n getAuction(\n orderId: string,\n requestParams: { signal?: AbortSignal }\n ): Promise<MaybeVeloraDeltaAuction>;\n} & Pick<\n UseWatchMultiDeltaAuctions,\n | \"onAuctionSuccess\"\n | \"onAuctionFailure\"\n | \"onUpdatedAuction\"\n | \"onTimeoutGettingOrder\"\n>;\n\nconst LOOK_FOR_ORDER_TIMEOUT = 60_000;\n\nfunction constructDeltaAuctionPollingQueryOptions({\n orderId,\n enabled,\n getAuction,\n onUpdatedAuction,\n onAuctionSuccess,\n onAuctionFailure,\n onTimeoutGettingOrder,\n}: ConstructDeltaAuctionPollingQueryOptionsInput): Pick<\n UseDeltaAuctionQueryOptions<MaybeVeloraDeltaAuction>,\n \"queryKey\" | \"queryFn\" | \"meta\" | \"refetchInterval\" | \"enabled\"\n> {\n const doneState = false;\n\n const isMetaWithDoneState = (\n queryMeta: QueryMeta\n ): queryMeta is { doneState: boolean } => {\n return \"doneState\" in queryMeta && typeof queryMeta.doneState === \"boolean\";\n };\n\n // queryOptions has to be memoized, otherwise queryMeta is updated on each render,\n // including startedQueryAt\n const meta: RefetchMetaWithTiming & {\n doneState: boolean;\n } = {\n startedQueryAt: Date.now(),\n doneState,\n };\n\n return {\n queryKey: [SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX, orderId],\n queryFn: ({ signal }) => {\n assert(orderId, \"orderId is required\");\n return getAuction(orderId, { signal });\n },\n meta,\n refetchInterval: (query) => {\n const maybeOrder = query.state.data;\n\n const queryMeta = query.options.meta;\n // refetchInterval is called on each render, regardless of queryOptions memoizations.\n // @TODO rework Watch Order logic to avoid callbacks inside refetchInterval,\n // or do away with these callbacks, they are unused currently.\n const isWithDoneState = !!queryMeta && isMetaWithDoneState(queryMeta);\n if (isWithDoneState && queryMeta.doneState) {\n getLogger(\"DeltaAuctionPollingQueryOptions\").log(\n \"Shortcut return for refetchInterval\"\n );\n return false;\n }\n\n // Order could have an updated status during its lifecycle\n if (maybeOrder) onUpdatedAuction?.(maybeOrder);\n\n // Order done with one way or the other\n if (\n maybeOrder &&\n DeltaOrderStatusChecker.completed.has(maybeOrder.status)\n ) {\n // Crosschain Orders are considered executed when both srcChain and destChain are executed\n if (isExecutedDeltaAuction(maybeOrder)) {\n onAuctionSuccess?.(maybeOrder);\n if (isWithDoneState) {\n queryMeta.doneState = true;\n }\n return false; // stop polling\n }\n if (isFailedDeltaAuction(maybeOrder) || isOrderExpired(maybeOrder)) {\n onAuctionFailure?.(maybeOrder);\n if (isWithDoneState) {\n queryMeta.doneState = true;\n }\n return false; // stop polling\n }\n }\n\n if (maybeOrder === null && queryMeta && isMetaWithTimeStart(queryMeta)) {\n // no Order for this orderId for a long time\n const elapsed = Date.now() - queryMeta.startedQueryAt;\n if (elapsed > LOOK_FOR_ORDER_TIMEOUT) {\n assert(orderId, \"orderId is required\");\n onTimeoutGettingOrder?.({ id: orderId });\n if (isWithDoneState) {\n queryMeta.doneState = true;\n }\n return false; // stop polling after 1 minute\n }\n }\n\n return DELTA_ORDER_POLLING_INTERVAL; // default interval for both crosschain and singlechain Orders\n },\n enabled: !!orderId && enabled,\n };\n}\n\n// ----------------- Single Delta Query -----------------------------------\n\ntype UseWatchDeltaAuctionQueryInput = {\n orderId?: string;\n enabled?: boolean;\n onAuctionSuccess?: (auction: ExecutedDeltaAuction) => void;\n onAuctionFailure?: (auction: FailedDeltaAuction) => void;\n onUpdatedAuction?: (auction: MarkOptional<DeltaAuction, \"signature\">) => void;\n onTimeoutGettingOrder?: (auction: Pick<DeltaAuction, \"id\">) => void;\n};\n\nexport function useWatchDeltaAuction({\n orderId,\n enabled = true,\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n}: UseWatchDeltaAuctionQueryInput): UseQueryResult<MaybeVeloraDeltaAuction> {\n const { sdk } = useDeltaSDK({ chainId: 1 }); // chain doesn't matter\n\n const callbacksRef = useRef({\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n });\n\n useLayoutEffect(() => {\n callbacksRef.current = {\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n };\n }, [\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n ]);\n\n const queryOptions = useMemo(() => {\n return constructDeltaAuctionPollingQueryOptions({\n orderId,\n enabled,\n getAuction: sdk.getDeltaOrderById,\n onUpdatedAuction: callbacksRef.current.onUpdatedAuction,\n onAuctionSuccess: callbacksRef.current.onAuctionSuccess,\n onAuctionFailure: callbacksRef.current.onAuctionFailure,\n onTimeoutGettingOrder: callbacksRef.current.onTimeoutGettingOrder,\n });\n }, [orderId, enabled, sdk.getDeltaOrderById]);\n\n return useQuery<\n MaybeVeloraDeltaAuction,\n Error,\n MaybeVeloraDeltaAuction,\n SingleDeltaAuctionQueryKey\n >(queryOptions);\n}\n\ntype EnsureOrderExecutedFn = (options: {\n orderId: string;\n signal?: AbortSignal;\n}) => Promise<MaybeVeloraDeltaAuction>;\n\nexport function useEnsureDeltaOrderExecuted(): EnsureOrderExecutedFn {\n const queryClient = useQueryClient();\n const logger = useLogger(\"EnsureDeltaOrderExecuted\");\n\n const ensureOrderSent: EnsureOrderExecutedFn = async ({\n orderId,\n signal,\n }): Promise<MaybeVeloraDeltaAuction> => {\n const queryKey: SingleDeltaAuctionQueryKey = [\n SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX,\n orderId,\n ];\n\n const observer = new QueryObserver<\n MaybeVeloraDeltaAuction,\n Error,\n MaybeVeloraDeltaAuction,\n SingleDeltaAuctionQueryKey\n >(queryClient, {\n queryKey,\n enabled: false, // no queryFn, just subscription\n // @TODO consider if we want queryFn to have refetching separate from useDeltaFlow\n });\n\n const promise = new Promise<MaybeVeloraDeltaAuction>((resolve, reject) => {\n const startedQueryAt = Date.now();\n\n // don't leave the promise and therefore the observer hanging,\n // if useWatchDeltaAuction doesn't finish its job and stops triggering the subscription\n let timeout: NodeJS.Timeout | null = setTimeout(() => {\n logger.log(\"QueryObserver\", queryKey, \"timeout\");\n unsubscribe();\n reject(new Error(`Order ${orderId} not found`));\n }, LOOK_FOR_ORDER_TIMEOUT + 1000); // a bit of jitter time\n\n signal?.addEventListener(\"abort\", () => {\n if (timeout) {\n clearTimeout(timeout);\n }\n unsubscribe();\n reject(new Error(`Order execution aborted: ${signal.reason}`));\n });\n\n const unsubscribe = observer.subscribe((result) => {\n const cleanup = () => {\n logger.log(\"QueryObserver\", queryKey, \"cleanup\");\n unsubscribe();\n };\n\n logger.log(\"QueryObserver\", queryKey, result);\n\n const maybeOrder = result.data;\n\n if (maybeOrder && timeout !== null) {\n // Order fetched at least once\n clearTimeout(timeout);\n timeout = null;\n }\n\n // Order done with one way or the other\n if (\n maybeOrder &&\n DeltaOrderStatusChecker.completed.has(maybeOrder.status)\n ) {\n // Crosschain Orders are considered executed when both srcChain and destChain are executed\n if (isExecutedDeltaAuction(maybeOrder)) {\n cleanup();\n resolve(maybeOrder);\n return;\n }\n if (isFailedDeltaAuction(maybeOrder)) {\n cleanup();\n reject(maybeOrder);\n return;\n }\n }\n\n if (maybeOrder === null) {\n // no Order for this orderId for a long time\n const elapsed = Date.now() - startedQueryAt;\n if (elapsed > LOOK_FOR_ORDER_TIMEOUT) {\n cleanup();\n reject(new Error(`Order ${orderId} not found`));\n return;\n }\n }\n if (result.error) {\n cleanup();\n reject(result.error);\n return;\n }\n });\n });\n\n return promise;\n };\n\n return ensureOrderSent;\n}\n\n// ----------------- Multi Delta Queries -----------------------------------\n\ntype UseWatchMultiDeltaAuctions = {\n orderIds: string[];\n enabled?: boolean;\n onAuctionSuccess?: (auction: ExecutedDeltaAuction) => void;\n onAuctionFailure?: (auction: FailedDeltaAuction) => void;\n onUpdatedAuction?: (auction: MarkOptional<DeltaAuction, \"signature\">) => void;\n onTimeoutGettingOrder?: (auction: Pick<DeltaAuction, \"id\">) => void;\n};\n\nexport function useWatchMultiDeltaAuctions({\n orderIds,\n enabled = true,\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n}: UseWatchMultiDeltaAuctions): UseQueryResult<MaybeVeloraDeltaAuction>[] {\n const { sdk } = useDeltaSDK({ chainId: 1 }); // chain doesn't matter\n\n const callbacksRef = useRef({\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n });\n\n useLayoutEffect(() => {\n callbacksRef.current = {\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n };\n }, [\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n ]);\n\n const queries = useMemo<\n UseDeltaAuctionQueryOptions<MaybeVeloraDeltaAuction>[]\n >(\n () =>\n orderIds.map((orderId) =>\n constructDeltaAuctionPollingQueryOptions({\n orderId,\n enabled,\n getAuction: sdk.getDeltaOrderById,\n onUpdatedAuction: callbacksRef.current.onUpdatedAuction,\n onAuctionSuccess: callbacksRef.current.onAuctionSuccess,\n onAuctionFailure: callbacksRef.current.onAuctionFailure,\n onTimeoutGettingOrder: callbacksRef.current.onTimeoutGettingOrder,\n })\n ),\n [enabled, orderIds, sdk.getDeltaOrderById]\n );\n\n const auctionsResults = useQueries({ queries });\n\n return auctionsResults;\n}\n\ntype MultiOrdersStatusCrossChainInput = {\n orders: DeltaOrderFromAPI[];\n onAuctionSuccess?: (order: DeltaOrderFromAPI) => void;\n onAuctionFailure?: (order: DeltaOrderFromAPI) => void;\n onUpdatedAuction?: (\n auction: MarkOptional<DeltaAuction, \"signature\">,\n bridgeResponse: BridgedDepositResponse\n ) => void;\n};\n\n// can be used for checking Crosschain Order status checking\n// if status check from API is slow to update\nexport function useWatchMultiOrdersStatusCrossChain({\n orders,\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n}: MultiOrdersStatusCrossChainInput): UseQueryResult<BridgedDepositResponse>[] {\n const { deposits, onNewResponse, onDepositSuccess, onDepositFailure } =\n useMemo(() => {\n const { deposits, depositId2Order } = orders.reduce<{\n deposits: GetBridgedDepositStatusInput[];\n depositId2Order: Record<string, DeltaOrderFromAPI>;\n }>(\n (acc, order) => {\n if (order.bridgeMetadata?.depositId) {\n acc.deposits.push({\n depositId: String(order.bridgeMetadata.depositId),\n originChainId: order.chainId,\n });\n acc.depositId2Order[order.bridgeMetadata.depositId] = order;\n }\n return acc;\n },\n { deposits: [], depositId2Order: {} }\n );\n const onNewResponse = (response: BridgedDepositResponse) => {\n const order = depositId2Order[response.depositId];\n if (order) {\n onUpdatedAuction?.(order, response);\n }\n };\n\n const onDepositSuccess = onAuctionSuccess\n ? (deposit: BridgedDepositResponseSuccess) => {\n const order = depositId2Order[deposit.depositId];\n if (order) {\n const successfulOrder = {\n ...order,\n bridgeStatus: deposit.status,\n bridgeMetadata: {\n ...order.bridgeMetadata,\n fillTx: deposit.fillTx,\n },\n } as DeltaOrderFromAPI; // order.bridgeMetadata should be filled but not according to types\n onAuctionSuccess(successfulOrder);\n }\n }\n : undefined;\n\n const onDepositFailure = onAuctionFailure\n ? (deposit: BridgedDepositResponseFailure) => {\n const order = depositId2Order[deposit.depositId];\n if (order) {\n const failedOrder = {\n ...order,\n bridgeStatus: deposit.status,\n bridgeMetadata: {\n ...order.bridgeMetadata,\n fillTx: deposit.fillTx || undefined,\n },\n } as DeltaOrderFromAPI; // order.bridgeMetadata should be filled but not according to types\n onAuctionFailure(failedOrder);\n }\n }\n : undefined;\n\n return { deposits, onNewResponse, onDepositSuccess, onDepositFailure };\n }, [orders, onAuctionSuccess, onAuctionFailure, onUpdatedAuction]);\n\n const depositStatuses = useBridgedDepositStatus({\n deposits,\n onNewResponse,\n onDepositSuccess,\n onDepositFailure,\n });\n\n return depositStatuses;\n}\n"],"names":["SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX","DELTA_ORDER_POLLING_INTERVAL","LOOK_FOR_ORDER_TIMEOUT","constructDeltaAuctionPollingQueryOptions","orderId","enabled","getAuction","onUpdatedAuction","onAuctionSuccess","onAuctionFailure","onTimeoutGettingOrder","doneState","isMetaWithDoneState","queryMeta","meta","startedQueryAt","Date","now","queryKey","queryFn","signal","assert","refetchInterval","query","maybeOrder","state","data","options","isWithDoneState","getLogger","log","DeltaOrderStatusChecker","completed","has","status","isExecutedDeltaAuction","isFailedDeltaAuction","isOrderExpired","isMetaWithTimeStart","elapsed","id","useWatchDeltaAuction","sdk","useDeltaSDK","chainId","callbacksRef","useRef","useLayoutEffect","current","queryOptions","useMemo","getDeltaOrderById","useQuery","useEnsureDeltaOrderExecuted","$","_c","queryClient","useQueryClient","logger","useLogger","t0","t1","observer","QueryObserver","promise","Promise","resolve","reject","timeout","setTimeout","unsubscribe","Error","addEventListener","clearTimeout","reason","subscribe","result","cleanup","error","ensureOrderSent"],"mappings":";;;;;;;;;AAkCA,MAAMA,qCAAAA,GAAwC,sBAAA;AAgB9C,MAAMC,4BAAAA,GAA+B,GAAA;AAiBrC,MAAMC,sBAAAA,GAAyB,GAAA;AAE/B,SAASC,wCAAAA,CAAyC;AAAA,EAChDC,OAAAA;AAAAA,EACAC,OAAAA;AAAAA,EACAC,UAAAA;AAAAA,EACAC,gBAAAA;AAAAA,EACAC,gBAAAA;AAAAA,EACAC,gBAAAA;AAAAA,EACAC;AAC6C,CAAA,EAG7C;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AAAA,SAGvB,CAAA;AAAA,OAAE,CAAA;AACF,MAAA,OAEId,OAAAA;AAAAA,KAAO;AACfV,IAAAA,CAAAA,MAAAI,MAAAA;AAAAJ,IAAAA,CAAAA,MAAAE,WAAAA;AAAAF,IAAAA,CAAAA,MAAAM,EAAAA;AAAAA,GAAA,MAAA;AAAAA,IAAAA,EAAAA,GAAAN,EAAA,CAAA,CAAA;AAAA;AA3FD,EAAA,MAAAyB,eAAAA,GAA+CnB,EAAAA;AA2F7C,EAAA,OAEKmB,eAAAA;AAAe;;;;"}
|
|
1
|
+
{"version":3,"file":"useWatchDeltaOrder.js","sources":["../../../../../../src/hooks/swap/prices/delta/queries/useWatchDeltaOrder.ts"],"sourcesContent":["import {\n QueryObserver,\n useQueries,\n useQuery,\n type QueryMeta,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\nimport { useLayoutEffect, useMemo, useRef } from \"react\";\nimport { assert, type MarkOptional } from \"ts-essentials\";\nimport { useDeltaSDK } from \"@/hooks/useSDK\";\nimport type { DeltaOrderFromAPI } from \"./useDeltaOrders\";\nimport {\n isMetaWithTimeStart,\n type BridgedDepositResponseFailure,\n type BridgedDepositResponseSuccess,\n type GetBridgedDepositStatusInput,\n type RefetchMetaWithTiming,\n} from \"../bridge/utils\";\nimport type { BridgedDepositResponse } from \"../bridge/types\";\nimport { useBridgedDepositStatus } from \"../bridge/useBridgedDeposit\";\nimport type { DeltaAuction } from \"@velora-dex/sdk\";\nimport {\n DeltaOrderStatusChecker,\n isExecutedDeltaAuction,\n isFailedDeltaAuction,\n isOrderExpired,\n} from \"../orders/utils\";\nimport type { ExecutedDeltaAuction, FailedDeltaAuction } from \"../orders/types\";\nimport { getLogger, useLogger } from \"@/widget/logger\";\nimport { useQueryClient } from \"@/lib/queryClient\";\n\n// ------------------------------------ Single Delta Auction -----------------------------------\n\nconst SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX = \"single_delta_auction\";\ntype SingleDeltaAuctionQueryKey = [\n base: typeof SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX,\n orderId?: string,\n];\n\nexport type MaybeVeloraDeltaAuction = DeltaOrderFromAPI | null; // null is when no such Order for orderId\n\ntype UseDeltaAuctionQueryOptions<TData = MaybeVeloraDeltaAuction> =\n UseQueryOptions<\n MaybeVeloraDeltaAuction,\n Error,\n TData,\n SingleDeltaAuctionQueryKey\n >;\n\nconst DELTA_ORDER_POLLING_INTERVAL = 3_000;\n\ntype ConstructDeltaAuctionPollingQueryOptionsInput = {\n orderId?: string;\n enabled?: boolean;\n getAuction(\n orderId: string,\n requestParams: { signal?: AbortSignal }\n ): Promise<MaybeVeloraDeltaAuction>;\n} & Pick<\n UseWatchMultiDeltaAuctions,\n | \"onAuctionSuccess\"\n | \"onAuctionFailure\"\n | \"onUpdatedAuction\"\n | \"onTimeoutGettingOrder\"\n>;\n\nconst LOOK_FOR_ORDER_TIMEOUT = 60_000;\n\nfunction constructDeltaAuctionPollingQueryOptions({\n orderId,\n enabled,\n getAuction,\n onUpdatedAuction,\n onAuctionSuccess,\n onAuctionFailure,\n onTimeoutGettingOrder,\n}: ConstructDeltaAuctionPollingQueryOptionsInput): Pick<\n UseDeltaAuctionQueryOptions<MaybeVeloraDeltaAuction>,\n \"queryKey\" | \"queryFn\" | \"meta\" | \"refetchInterval\" | \"enabled\"\n> {\n const doneState = false;\n\n const isMetaWithDoneState = (\n queryMeta: QueryMeta\n ): queryMeta is { doneState: boolean } => {\n return \"doneState\" in queryMeta && typeof queryMeta.doneState === \"boolean\";\n };\n\n // queryOptions has to be memoized, otherwise queryMeta is updated on each render,\n // including startedQueryAt\n const meta: RefetchMetaWithTiming & {\n doneState: boolean;\n } = {\n startedQueryAt: Date.now(),\n doneState,\n };\n\n return {\n queryKey: [SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX, orderId],\n queryFn: ({ signal }) => {\n assert(orderId, \"orderId is required\");\n return getAuction(orderId, { signal });\n },\n meta,\n refetchInterval: (query) => {\n const maybeOrder = query.state.data;\n\n const queryMeta = query.options.meta;\n // refetchInterval is called on each render, regardless of queryOptions memoizations.\n // @TODO rework Watch Order logic to avoid callbacks inside refetchInterval,\n // or do away with these callbacks, they are unused currently.\n const isWithDoneState = !!queryMeta && isMetaWithDoneState(queryMeta);\n if (isWithDoneState && queryMeta.doneState) {\n getLogger(\"DeltaAuctionPollingQueryOptions\").log(\n \"Shortcut return for refetchInterval\"\n );\n return false;\n }\n\n // Order could have an updated status during its lifecycle\n if (maybeOrder) onUpdatedAuction?.(maybeOrder);\n\n // Order done with one way or the other\n if (\n maybeOrder &&\n DeltaOrderStatusChecker.completed.has(maybeOrder.status)\n ) {\n // Crosschain Orders are considered executed when both srcChain and destChain are executed\n if (isExecutedDeltaAuction(maybeOrder)) {\n onAuctionSuccess?.(maybeOrder);\n if (isWithDoneState) {\n queryMeta.doneState = true;\n }\n return false; // stop polling\n }\n if (isFailedDeltaAuction(maybeOrder) || isOrderExpired(maybeOrder)) {\n onAuctionFailure?.(maybeOrder);\n if (isWithDoneState) {\n queryMeta.doneState = true;\n }\n return false; // stop polling\n }\n }\n\n if (maybeOrder === null && queryMeta && isMetaWithTimeStart(queryMeta)) {\n // no Order for this orderId for a long time\n const elapsed = Date.now() - queryMeta.startedQueryAt;\n if (elapsed > LOOK_FOR_ORDER_TIMEOUT) {\n assert(orderId, \"orderId is required\");\n onTimeoutGettingOrder?.({ id: orderId });\n if (isWithDoneState) {\n queryMeta.doneState = true;\n }\n return false; // stop polling after 1 minute\n }\n }\n\n return DELTA_ORDER_POLLING_INTERVAL; // default interval for both crosschain and singlechain Orders\n },\n enabled: !!orderId && enabled,\n };\n}\n\n// ----------------- Single Delta Query -----------------------------------\n\ntype UseWatchDeltaAuctionQueryInput = {\n orderId?: string;\n enabled?: boolean;\n onAuctionSuccess?: (auction: ExecutedDeltaAuction) => void;\n onAuctionFailure?: (auction: FailedDeltaAuction) => void;\n onUpdatedAuction?: (auction: MarkOptional<DeltaAuction, \"signature\">) => void;\n onTimeoutGettingOrder?: (auction: Pick<DeltaAuction, \"id\">) => void;\n};\n\nexport function useWatchDeltaAuction({\n orderId,\n enabled = true,\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n}: UseWatchDeltaAuctionQueryInput): UseQueryResult<MaybeVeloraDeltaAuction> {\n const { sdk } = useDeltaSDK({ chainId: 1 }); // chain doesn't matter\n\n const callbacksRef = useRef({\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n });\n\n useLayoutEffect(() => {\n callbacksRef.current = {\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n };\n }, [\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n ]);\n\n const queryOptions = useMemo(() => {\n return constructDeltaAuctionPollingQueryOptions({\n orderId,\n enabled,\n getAuction: sdk.getDeltaOrderById,\n onUpdatedAuction: callbacksRef.current.onUpdatedAuction,\n onAuctionSuccess: callbacksRef.current.onAuctionSuccess,\n onAuctionFailure: callbacksRef.current.onAuctionFailure,\n onTimeoutGettingOrder: callbacksRef.current.onTimeoutGettingOrder,\n });\n }, [orderId, enabled, sdk.getDeltaOrderById]);\n\n return useQuery<\n MaybeVeloraDeltaAuction,\n Error,\n MaybeVeloraDeltaAuction,\n SingleDeltaAuctionQueryKey\n >(queryOptions);\n}\n\ntype EnsureOrderExecutedFn = (options: {\n orderId: string;\n signal?: AbortSignal;\n}) => Promise<MaybeVeloraDeltaAuction>;\n\nexport function useEnsureDeltaOrderExecuted(): EnsureOrderExecutedFn {\n const queryClient = useQueryClient();\n const logger = useLogger(\"EnsureDeltaOrderExecuted\");\n\n const ensureOrderSent: EnsureOrderExecutedFn = async ({\n orderId,\n signal,\n }): Promise<MaybeVeloraDeltaAuction> => {\n const queryKey: SingleDeltaAuctionQueryKey = [\n SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX,\n orderId,\n ];\n\n const observer = new QueryObserver<\n MaybeVeloraDeltaAuction,\n Error,\n MaybeVeloraDeltaAuction,\n SingleDeltaAuctionQueryKey\n >(queryClient, {\n queryKey,\n enabled: false, // no queryFn, just subscription\n // @TODO consider if we want queryFn to have refetching separate from useDeltaFlow\n });\n\n const promise = new Promise<MaybeVeloraDeltaAuction>((resolve, reject) => {\n const startedQueryAt = Date.now();\n\n // don't leave the promise and therefore the observer hanging,\n // if useWatchDeltaAuction doesn't finish its job and stops triggering the subscription\n let timeout: NodeJS.Timeout | null = setTimeout(() => {\n logger.log(\"QueryObserver\", queryKey, \"timeout\");\n unsubscribe();\n reject(new Error(`Order ${orderId} not found`));\n }, LOOK_FOR_ORDER_TIMEOUT + 1000); // a bit of jitter time\n\n signal?.addEventListener(\"abort\", () => {\n if (timeout) {\n clearTimeout(timeout);\n }\n unsubscribe();\n reject(new Error(`Order execution aborted: ${signal.reason}`));\n });\n\n const unsubscribe = observer.subscribe((result) => {\n const cleanup = () => {\n logger.log(\"QueryObserver\", queryKey, \"cleanup\");\n unsubscribe();\n };\n\n logger.log(\"QueryObserver\", queryKey, result);\n\n const maybeOrder = result.data;\n\n if (maybeOrder && timeout !== null) {\n // Order fetched at least once\n clearTimeout(timeout);\n timeout = null;\n }\n\n // Order done with one way or the other\n if (\n maybeOrder &&\n DeltaOrderStatusChecker.completed.has(maybeOrder.status)\n ) {\n // Crosschain Orders are considered executed when both srcChain and destChain are executed\n if (isExecutedDeltaAuction(maybeOrder)) {\n cleanup();\n resolve(maybeOrder);\n return;\n }\n if (isFailedDeltaAuction(maybeOrder)) {\n cleanup();\n reject(maybeOrder);\n return;\n }\n }\n\n if (maybeOrder === null) {\n // no Order for this orderId for a long time\n const elapsed = Date.now() - startedQueryAt;\n if (elapsed > LOOK_FOR_ORDER_TIMEOUT) {\n cleanup();\n reject(new Error(`Order ${orderId} not found`));\n return;\n }\n }\n if (result.error) {\n cleanup();\n reject(result.error);\n return;\n }\n });\n });\n\n return promise;\n };\n\n return ensureOrderSent;\n}\n\n// ----------------- Multi Delta Queries -----------------------------------\n\ntype UseWatchMultiDeltaAuctions = {\n orderIds: string[];\n enabled?: boolean;\n onAuctionSuccess?: (auction: ExecutedDeltaAuction) => void;\n onAuctionFailure?: (auction: FailedDeltaAuction) => void;\n onUpdatedAuction?: (auction: MarkOptional<DeltaAuction, \"signature\">) => void;\n onTimeoutGettingOrder?: (auction: Pick<DeltaAuction, \"id\">) => void;\n};\n\nexport function useWatchMultiDeltaAuctions({\n orderIds,\n enabled = true,\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n}: UseWatchMultiDeltaAuctions): UseQueryResult<MaybeVeloraDeltaAuction>[] {\n const { sdk } = useDeltaSDK({ chainId: 1 }); // chain doesn't matter\n\n const callbacksRef = useRef({\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n });\n\n useLayoutEffect(() => {\n callbacksRef.current = {\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n };\n }, [\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n onTimeoutGettingOrder,\n ]);\n\n const queries = useMemo<\n UseDeltaAuctionQueryOptions<MaybeVeloraDeltaAuction>[]\n >(\n () =>\n orderIds.map((orderId) =>\n constructDeltaAuctionPollingQueryOptions({\n orderId,\n enabled,\n getAuction: sdk.getDeltaOrderById,\n onUpdatedAuction: callbacksRef.current.onUpdatedAuction,\n onAuctionSuccess: callbacksRef.current.onAuctionSuccess,\n onAuctionFailure: callbacksRef.current.onAuctionFailure,\n onTimeoutGettingOrder: callbacksRef.current.onTimeoutGettingOrder,\n })\n ),\n [enabled, orderIds, sdk.getDeltaOrderById]\n );\n\n const auctionsResults = useQueries({ queries });\n\n return auctionsResults;\n}\n\ntype MultiOrdersStatusCrossChainInput = {\n orders: DeltaOrderFromAPI[];\n onAuctionSuccess?: (order: DeltaOrderFromAPI) => void;\n onAuctionFailure?: (order: DeltaOrderFromAPI) => void;\n onUpdatedAuction?: (\n auction: MarkOptional<DeltaAuction, \"signature\">,\n bridgeResponse: BridgedDepositResponse\n ) => void;\n};\n\n// can be used for checking Crosschain Order status checking\n// if status check from API is slow to update\nexport function useWatchMultiOrdersStatusCrossChain({\n orders,\n onAuctionSuccess,\n onAuctionFailure,\n onUpdatedAuction,\n}: MultiOrdersStatusCrossChainInput): UseQueryResult<BridgedDepositResponse>[] {\n const { deposits, onNewResponse, onDepositSuccess, onDepositFailure } =\n useMemo(() => {\n const { deposits, depositId2Order } = orders.reduce<{\n deposits: GetBridgedDepositStatusInput[];\n depositId2Order: Record<string, DeltaOrderFromAPI>;\n }>(\n (acc, order) => {\n if (order.bridgeMetadata?.depositId) {\n acc.deposits.push({\n depositId: String(order.bridgeMetadata.depositId),\n originChainId: order.chainId,\n });\n acc.depositId2Order[order.bridgeMetadata.depositId] = order;\n }\n return acc;\n },\n { deposits: [], depositId2Order: {} }\n );\n const onNewResponse = (response: BridgedDepositResponse) => {\n const order = depositId2Order[response.depositId];\n if (order) {\n onUpdatedAuction?.(order, response);\n }\n };\n\n const onDepositSuccess = onAuctionSuccess\n ? (deposit: BridgedDepositResponseSuccess) => {\n const order = depositId2Order[deposit.depositId];\n if (order) {\n const successfulOrder = {\n ...order,\n bridgeStatus: deposit.status,\n bridgeMetadata: {\n ...order.bridgeMetadata,\n fillTx: deposit.fillTx,\n },\n } as DeltaOrderFromAPI; // order.bridgeMetadata should be filled but not according to types\n onAuctionSuccess(successfulOrder);\n }\n }\n : undefined;\n\n const onDepositFailure = onAuctionFailure\n ? (deposit: BridgedDepositResponseFailure) => {\n const order = depositId2Order[deposit.depositId];\n if (order) {\n const failedOrder = {\n ...order,\n bridgeStatus: deposit.status,\n bridgeMetadata: {\n ...order.bridgeMetadata,\n fillTx: deposit.fillTx || undefined,\n },\n } as DeltaOrderFromAPI; // order.bridgeMetadata should be filled but not according to types\n onAuctionFailure(failedOrder);\n }\n }\n : undefined;\n\n return { deposits, onNewResponse, onDepositSuccess, onDepositFailure };\n }, [orders, onAuctionSuccess, onAuctionFailure, onUpdatedAuction]);\n\n const depositStatuses = useBridgedDepositStatus({\n deposits,\n onNewResponse,\n onDepositSuccess,\n onDepositFailure,\n });\n\n return depositStatuses;\n}\n"],"names":["SINGLE_DELTA_AUCTION_QUERY_KEY_PREFIX","DELTA_ORDER_POLLING_INTERVAL","LOOK_FOR_ORDER_TIMEOUT","constructDeltaAuctionPollingQueryOptions","orderId","enabled","getAuction","onUpdatedAuction","onAuctionSuccess","onAuctionFailure","onTimeoutGettingOrder","doneState","isMetaWithDoneState","queryMeta","meta","startedQueryAt","Date","now","queryKey","queryFn","signal","assert","refetchInterval","query","maybeOrder","state","data","options","isWithDoneState","getLogger","log","DeltaOrderStatusChecker","completed","has","status","isExecutedDeltaAuction","isFailedDeltaAuction","isOrderExpired","isMetaWithTimeStart","elapsed","id","useWatchDeltaAuction","sdk","useDeltaSDK","chainId","callbacksRef","useRef","useLayoutEffect","current","queryOptions","useMemo","getDeltaOrderById","useQuery","useEnsureDeltaOrderExecuted","$","_c","queryClient","useQueryClient","logger","useLogger","t0","t1","observer","QueryObserver","promise","Promise","resolve","reject","timeout","setTimeout","unsubscribe","Error","addEventListener","clearTimeout","reason","subscribe","result","cleanup","error","ensureOrderSent"],"mappings":";;;;;;;;;;AAkCA,MAAMA,qCAAAA,GAAwC,sBAAA;AAgB9C,MAAMC,4BAAAA,GAA+B,GAAA;AAiBrC,MAAMC,sBAAAA,GAAyB,GAAA;AAE/B,SAASC,wCAAAA,CAAyC;AAAA,EAChDC,OAAAA;AAAAA,EACAC,OAAAA;AAAAA,EACAC,UAAAA;AAAAA,EACAC,gBAAAA;AAAAA,EACAC,gBAAAA;AAAAA,EACAC,gBAAAA;AAAAA,EACAC;AAC6C,CAAA,EAG7C;AACA,EAAA,MAAMC,SAAAA,GAAY,KAAA;AAElB,EAAA,MAAMC,mBAAAA,GAAsBA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O;AACfV,IAAAA,CAAAA,MAAAI,MAAAA;AAAAJ,IAAAA,CAAAA,MAAAE,WAAAA;AAAAF,IAAAA,CAAAA,MAAAM,EAAAA;AAAAA,GAAA,MAAA;AAAAA,IAAAA,EAAAA,GAAAN,EAAA,CAAA,CAAA;AAAA;AA3FD,EAAA,MAAAyB,eAAAA,GAA+CnB,EAAAA;AA2F7C,EAAA,OAEKmB,eAAAA;AAAe;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useInvalidateTokenData.d.ts","sourceRoot":"","sources":["../../../../src/hooks/tokens/balances/useInvalidateTokenData.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"useInvalidateTokenData.d.ts","sourceRoot":"","sources":["../../../../src/hooks/tokens/balances/useInvalidateTokenData.ts"],"names":[],"mappings":"AAyDA,KAAK,sBAAsB,GAAG;IAC5B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,CAAC;CAElB,CAAC;AACF;;;;;GAKG;AAEH,wBAAgB,2BAA2B,IAAI,CAC7C,aAAa,CAAC,EAAE,sBAAsB,KACnC,OAAO,CAAC,IAAI,CAAC,CAsFjB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { d as distExports } from '../../../_virtual/index.js';
|
|
2
|
-
import { useQueryClient } from '
|
|
2
|
+
import { useQueryClient } from '../../../lib/queryClient.js';
|
|
3
|
+
import '@tanstack/react-query';
|
|
3
4
|
import 'viem';
|
|
4
5
|
import 'wagmi';
|
|
5
6
|
import 'wagmi/query';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useInvalidateTokenData.js","sources":["../../../../src/hooks/tokens/balances/useInvalidateTokenData.ts"],"sourcesContent":["import type { NonceMethod } from \"@/hooks/permit/hooks/permit1/usePermit1Nonce\";\nimport { Query,
|
|
1
|
+
{"version":3,"file":"useInvalidateTokenData.js","sources":["../../../../src/hooks/tokens/balances/useInvalidateTokenData.ts"],"sourcesContent":["import type { NonceMethod } from \"@/hooks/permit/hooks/permit1/usePermit1Nonce\";\nimport { useQueryClient } from \"@/lib/queryClient\";\nimport { Query, type QueryKey } from \"@tanstack/react-query\";\n\nimport { erc20Abi, type Address } from \"viem\";\nimport { type Config } from \"wagmi\";\nimport {\n type ReadContractQueryKey,\n type GetBalanceQueryKey,\n type ReadContractsQueryKey,\n} from \"wagmi/query\";\n\ntype LooseQueryMatchToInvalidate<Q extends QueryKey> = {\n queryKey: [Q[0]];\n exact: false;\n predicate?: (query: Query) => boolean;\n};\n\ntype ETHBalanceQueryMatch = LooseQueryMatchToInvalidate<\n GetBalanceQueryKey<Config>\n>;\n\ntype ERC20BalanceQueryKey = ReadContractQueryKey<\n typeof erc20Abi,\n \"balanceOf\" | \"allowance\",\n [Address],\n Config\n>;\ntype ERC20BalanceAllowanceQueryMatch =\n LooseQueryMatchToInvalidate<ERC20BalanceQueryKey>;\n\nfunction isReadContractQueryKey(\n queryKey: QueryKey\n): queryKey is ReadContractQueryKey<unknown[], string, unknown[], Config> {\n return queryKey[0] === \"readContract\";\n}\n\ntype NoncesQueryKey = ReadContractsQueryKey<\n {\n address: Address;\n abi: typeof erc20Abi;\n functionName: NonceMethod;\n args: [Address];\n }[],\n boolean,\n Config\n>;\n\ntype NoncesQueryMatch = LooseQueryMatchToInvalidate<NoncesQueryKey>;\nconst nonceMethods: NonceMethod[] = [\"nonces\", \"_nonces\", \"nonce\", \"getNonce\"];\n\nfunction isReadContractsQueryKey(\n queryKey: QueryKey\n): queryKey is ReadContractsQueryKey<unknown[], boolean, Config> {\n return queryKey[0] === \"readContracts\";\n}\n\ntype TokenFuncsToInvalidate = {\n allowance?: boolean;\n balanceOf?: boolean;\n nonces?: boolean; // invalidate queries with Permit1 nonces,\n // Permit2 nonces can be safely incremented without syncing with what's on chain\n};\n/**\n * Helper function to invalidate token-related query cache entries.\n * Used to refresh token balances and allowances after transactions that modify them.\n * Can selectively invalidate either balance or allowance queries, or both.\n * Invalidates for all tokens that have their queries currently mounted, which is easier than matching.\n */\n\nexport function useInvalidateTokenDataQuery(): (\n tokenDataType?: TokenFuncsToInvalidate\n) => Promise<void> {\n const queryClient = useQueryClient();\n\n const invalidateBalancesAndAllowances = async ({\n allowance = true,\n balanceOf = true,\n nonces = false,\n }: TokenFuncsToInvalidate = {}) => {\n const queries: LooseQueryMatchToInvalidate<QueryKey>[] = [];\n\n if (balanceOf) {\n const ethBalanceQuery: ETHBalanceQueryMatch = {\n // easier to just match the queryKey base\n queryKey: [\"balance\"],\n exact: false,\n };\n queries.push(ethBalanceQuery);\n }\n\n type ERC20Func = NonNullable<ERC20BalanceQueryKey[1][\"functionName\"]>;\n\n const tokenFuncs: ERC20Func[] = [];\n if (balanceOf) {\n tokenFuncs.push(\"balanceOf\");\n }\n if (allowance) {\n tokenFuncs.push(\"allowance\");\n }\n\n if (tokenFuncs.length > 0) {\n // relax type to allow string[].includes(string)\n const matchedERC20Funcs: string[] = tokenFuncs;\n\n const erc20BalanceQuery: ERC20BalanceAllowanceQueryMatch = {\n queryKey: [\"readContract\"],\n exact: false,\n predicate: (query) => {\n const { queryKey } = query;\n // all queries that read Contract.<anything>\n if (isReadContractQueryKey(queryKey)) {\n if (\n queryKey[1].functionName &&\n matchedERC20Funcs.includes(queryKey[1].functionName)\n // all queries that read Contract.balanceOf or Contract.allowance\n ) {\n return true;\n }\n }\n return false;\n },\n };\n queries.push(erc20BalanceQuery);\n }\n\n if (nonces) {\n // relax type to allow string[].includes(string)\n const matchedNonceMethods: string[] = nonceMethods;\n\n const nonceQuery: NoncesQueryMatch = {\n queryKey: [\"readContracts\"],\n exact: false,\n predicate: (query) => {\n const { queryKey } = query;\n // all queries that read multiple Contract.<anything>\n if (isReadContractsQueryKey(queryKey)) {\n // we only ever use nonce methods with other nonce methods only,\n // no non-nonce methods mixed in\n const firstMethod = queryKey[1].contracts?.[0]?.functionName;\n if (firstMethod && matchedNonceMethods.includes(firstMethod)) {\n return true;\n }\n }\n return false;\n },\n };\n queries.push(nonceQuery);\n }\n\n if (queries.length > 0) {\n await Promise.all(\n queries.map((query) => queryClient.invalidateQueries(query))\n );\n }\n };\n\n return invalidateBalancesAndAllowances;\n}\n"],"names":["isReadContractQueryKey","queryKey","nonceMethods","isReadContractsQueryKey","useInvalidateTokenDataQuery","$","_c","queryClient","useQueryClient","t0","t1","allowance","t2","balanceOf","t3","nonces","t4","undefined","queries","ethBalanceQuery","exact","push","tokenFuncs","length","matchedERC20Funcs","erc20BalanceQuery","predicate","query","functionName","includes","nonceQuery","_temp","Promise","all","map","query_1","invalidateQueries","invalidateBalancesAndAllowances","query_0","queryKey_0","firstMethod","contracts"],"mappings":";;;;;;;AA+BA,SAASA,uBACPC,QAAAA,EACwE;AACxE,EAAA,OAAOA,QAAAA,CAAS,CAAC,CAAA,KAAM,cAAA;AACzB;AAcA,MAAMC,YAAAA,GAA8B,CAAC,QAAA,EAAU,SAAA,EAAW,SAAS,UAAU,CAAA;AAE7E,SAASC,wBACPF,QAAAA,EAC+D;AAC/D,EAAA,OAAOA,QAAAA,CAAS,CAAC,CAAA,KAAM,eAAA;AACzB;AAeO,SAAAG,2BAAAA,GAAA;AAAA,EAAA,MAAAC,CAAAA,GAAAC,cAAA,CAAA,CAAA;AAGL,EAAA,MAAAC,cAAoBC,cAAAA,EAAe;AAAE,EAAA,IAAAC,EAAAA;AAAA,EAAA,IAAAJ,CAAAA,QAAAE,WAAAA,EAAA;AAEGE,IAAAA,EAAAA,UAAAC,EAAAA,KAAA;AAAO,MAAA,MAAA;AAAA,QAAAC,SAAAA,EAAAC,EAAAA;AAAAA,QAAAC,SAAAA,EAAAC,EAAAA;AAAAA,QAAAC,MAAAA,EAAAC;AAAAA,OAAA,GAAAN,EAAAA,KAIjBO,MAAAA,GAAA,EAAA,GAJiBP,EAAAA;AAC7C,MAAA,MAAAC,SAAAA,GAAAC,EAAAA,KAAgBK,MAAAA,UAAhBL,EAA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|
3
3
|
import { waitForTransactionReceipt } from '@wagmi/core';
|
|
4
4
|
import { useConfig, useWaitForTransactionReceipt } from 'wagmi';
|
|
5
5
|
import { waitForTransactionReceiptQueryKey } from 'wagmi/query';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAwaitTx.js","sources":["../../../../src/hooks/txs/queries/useAwaitTx.ts"],"sourcesContent":["import type { wagmiConfig } from \"@/lib/web3/wagmi/config\";\nimport type { SupportedChainId } from \"@/lib/web3/wagmi/types\";\nimport { useQueryClient } from \"
|
|
1
|
+
{"version":3,"file":"useAwaitTx.js","sources":["../../../../src/hooks/txs/queries/useAwaitTx.ts"],"sourcesContent":["import type { wagmiConfig } from \"@/lib/web3/wagmi/config\";\nimport type { SupportedChainId } from \"@/lib/web3/wagmi/types\";\nimport { useQueryClient } from \"@/lib/queryClient\";\nimport type { ReplacementReturnType, TransactionReceipt } from \"viem\";\nimport { waitForTransactionReceipt } from \"@wagmi/core\";\nimport {\n useConfig,\n useWaitForTransactionReceipt,\n type UseWaitForTransactionReceiptParameters,\n type UseWaitForTransactionReceiptReturnType,\n} from \"wagmi\";\nimport {\n waitForTransactionReceiptQueryKey,\n type WaitForTransactionReceiptData,\n} from \"wagmi/query\";\nimport { useLogger } from \"@/widget/logger\";\n\nexport type UseAwaitTxParameters<Select = DefaultTxReceiptSelect> = {\n chainId: SupportedChainId;\n confirmations?: number;\n hash?: `0x${string}`;\n query?: UseWaitForTransactionReceiptParameters<\n typeof wagmiConfig,\n SupportedChainId,\n Select\n >[\"query\"];\n};\n\ntype OnReplacedCb = (data: ReplacementReturnType) => void;\n\nexport type DefaultTxReceiptSelect = WaitForTransactionReceiptData<\n typeof wagmiConfig,\n SupportedChainId\n>;\n\nexport type UseAwaitTxReturnType<Select = DefaultTxReceiptSelect> =\n UseWaitForTransactionReceiptReturnType<\n typeof wagmiConfig,\n SupportedChainId,\n Select\n >;\n\nexport type TxReceiptFromWagmi = DefaultTxReceiptSelect;\n\nexport function useAwaitTx<Select = DefaultTxReceiptSelect>({\n chainId,\n confirmations,\n hash,\n query,\n}: UseAwaitTxParameters<Select>): UseAwaitTxReturnType<Select> {\n const logger = useLogger(\"AwaitTx\");\n const queryResult = useWaitForTransactionReceipt<\n typeof wagmiConfig,\n SupportedChainId,\n Select\n >({\n chainId,\n confirmations,\n hash,\n query,\n onReplaced: (data) => {\n // @TODO connect to some atom if needed to detect cancelled/sped-up txs,\n // but sped-up txs may be detected correct internally and re-awaited with a new hash,\n // need to test\n // https://viem.sh/docs/actions/public/waitForTransactionReceipt.html#json-rpc-methods\n logger.log(\"onReplaced:tx\", hash, data);\n },\n });\n\n return queryResult;\n}\n\ntype EnsureTxReceiptFn = (\n options: Required<Pick<UseAwaitTxParameters, \"hash\" | \"chainId\">> & {\n onReplaced?: OnReplacedCb;\n }\n) => Promise<TransactionReceipt>;\n\nexport function useEnsureTxReceipt(): EnsureTxReceiptFn {\n const queryClient = useQueryClient();\n const wagmiConfig = useConfig();\n\n const ensureTxReceipt: EnsureTxReceiptFn = async ({\n hash,\n chainId,\n onReplaced,\n }) => {\n const queryKey = waitForTransactionReceiptQueryKey({\n hash,\n chainId,\n });\n const receipt = await queryClient.ensureQueryData({\n queryKey,\n queryFn: () => {\n return waitForTransactionReceipt(wagmiConfig, {\n hash,\n chainId,\n onReplaced,\n });\n },\n });\n\n return receipt;\n };\n\n return ensureTxReceipt;\n}\n"],"names":["useAwaitTx","t0","$","_c","chainId","confirmations","hash","query","logger","useLogger","t1","data","log","t2","onReplaced","queryResult","useWaitForTransactionReceipt","useEnsureTxReceipt","queryClient","useQueryClient","wagmiConfig","useConfig","queryKey","waitForTransactionReceiptQueryKey","receipt","ensureQueryData","queryFn","waitForTransactionReceipt","ensureTxReceipt"],"mappings":";;;;;;;AA4CO,SAAAA,WAAAC,EAAAA,EAAA;AAAA,EAAA,MAAAC,CAAAA,GAAAC,cAAA,CAAA,CAAA;AAAqD,EAAA,MAAA;AAAA,IAAAC,OAAAA;AAAA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1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,YAAY,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,YAAY,EACV,WAAW,EACX,YAAY,EACZ,WAAW,EACX,kBAAkB,GACnB,MAAM,gBAAgB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queryClient.d.ts","sourceRoot":"","sources":["../../src/lib/queryClient.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"queryClient.d.ts","sourceRoot":"","sources":["../../src/lib/queryClient.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EAEZ,MAAM,uBAAuB,CAAC;AAE/B,eAAO,MAAM,WAAW,aAAoB,CAAC;AAE7C,eAAO,MAAM,cAAc,mBAE1B,CAAC"}
|
package/dist/lib/queryClient.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
import { QueryClient } from '@tanstack/react-query';
|
|
1
|
+
import { QueryClient, useQueryClient as useQueryClient$1 } from '@tanstack/react-query';
|
|
2
2
|
|
|
3
3
|
const queryClient = new QueryClient();
|
|
4
|
+
const useQueryClient = () => {
|
|
5
|
+
return useQueryClient$1(queryClient);
|
|
6
|
+
};
|
|
4
7
|
|
|
5
|
-
export { queryClient };
|
|
8
|
+
export { queryClient, useQueryClient };
|
|
6
9
|
//# sourceMappingURL=queryClient.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queryClient.js","sources":["../../src/lib/queryClient.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"queryClient.js","sources":["../../src/lib/queryClient.ts"],"sourcesContent":["import {\n QueryClient,\n useQueryClient as useRawQueryClient,\n} from \"@tanstack/react-query\";\n\nexport const queryClient = new QueryClient();\n\nexport const useQueryClient = () => {\n return useRawQueryClient(queryClient);\n};\n"],"names":["queryClient","QueryClient","useQueryClient","useRawQueryClient"],"mappings":";;AAKO,MAAMA,WAAAA,GAAc,IAAIC,WAAAA;AAExB,MAAMC,iBAAiBA,MAAA;AAAA,EAAA,OACrBC,iBAAAH,WAA6B,CAAA;AAAC;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Configurator.d.ts","sourceRoot":"","sources":["../../src/test/Configurator.tsx"],"names":[],"mappings":"AAEA,OAAO,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"Configurator.d.ts","sourceRoot":"","sources":["../../src/test/Configurator.tsx"],"names":[],"mappings":"AAEA,OAAO,YAAY,CAAC;AA+NpB,eAAO,MAAM,YAAY,+CAiGxB,CAAC"}
|
package/dist/widget/types.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { EIP1193Provider } from 'viem';
|
|
2
1
|
export type WidgetTheme = "light" | "dark";
|
|
3
2
|
export interface WidgetProps {
|
|
4
3
|
config?: WidgetConfig;
|
|
5
|
-
provider?:
|
|
4
|
+
provider?: EIP1193ProviderLax;
|
|
6
5
|
}
|
|
7
6
|
/** Configuration for the widget. */
|
|
8
7
|
export interface WidgetConfig {
|
|
@@ -21,4 +20,14 @@ export interface WidgetConfig {
|
|
|
21
20
|
/** Widget mode - "dapp" for embedded in dapp, "standalone" for standalone widget. */
|
|
22
21
|
widgetMode?: "dapp" | "standalone";
|
|
23
22
|
}
|
|
23
|
+
interface RequestArguments {
|
|
24
|
+
readonly method: any;
|
|
25
|
+
readonly params?: any;
|
|
26
|
+
}
|
|
27
|
+
export type EIP1193ProviderLax = {
|
|
28
|
+
request: (args: RequestArguments) => Promise<any>;
|
|
29
|
+
on: (event: any, callback: (arg: unknown) => void) => void;
|
|
30
|
+
removeListener: (event: any, callback: (arg: unknown) => void) => void;
|
|
31
|
+
};
|
|
32
|
+
export {};
|
|
24
33
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/widget/types.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/widget/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,GAAG,OAAO,GAAG,MAAM,CAAC;AAE3C,MAAM,WAAW,WAAW;IAC1B,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,QAAQ,CAAC,EAAE,kBAAkB,CAAC;CAC/B;AAED,qCAAqC;AACrC,MAAM,WAAW,YAAY;IAC3B,mDAAmD;IACnD,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,wEAAwE;IACxE,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,iCAAiC;IACjC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,oDAAoD;IACpD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,0EAA0E;IAC1E,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kEAAkE;IAClE,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,qFAAqF;IACrF,UAAU,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC;CACpC;AAGD,UAAU,gBAAgB;IACxB,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC;IACrB,QAAQ,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC;CACvB;AAOD,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,EAAE,CAAC,IAAI,EAAE,gBAAgB,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IAClD,EAAE,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,KAAK,IAAI,CAAC;IAC3D,cAAc,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,KAAK,IAAI,CAAC;CACxE,CAAC"}
|