@symmio/trading-react 3.2.0 → 3.3.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/dist/instant-layer/use-instant-open-auto.d.ts +3 -3
- package/dist/instant-layer/use-instant-open-auto.js.map +1 -1
- package/dist/instant-layer/use-instant-open-fees.d.ts +7 -0
- package/dist/instant-layer/use-instant-open-fees.d.ts.map +1 -1
- package/dist/instant-layer/use-instant-open-fees.js +1 -0
- package/dist/instant-layer/use-instant-open-fees.js.map +1 -1
- package/dist/instant-layer/use-instant-open-inputs.d.ts +2 -0
- package/dist/instant-layer/use-instant-open-inputs.d.ts.map +1 -1
- package/dist/instant-layer/use-instant-open-inputs.js +2 -0
- package/dist/instant-layer/use-instant-open-inputs.js.map +1 -1
- package/dist/instant-layer/use-prepare-instant-open-params.d.ts +9 -0
- package/dist/instant-layer/use-prepare-instant-open-params.d.ts.map +1 -1
- package/dist/instant-layer/use-prepare-instant-open-params.js +2 -0
- package/dist/instant-layer/use-prepare-instant-open-params.js.map +1 -1
- package/package.json +2 -2
|
@@ -26,9 +26,9 @@ export type UseInstantOpenAutoReturnType = UseMutationResult<InstantOpenReturnTy
|
|
|
26
26
|
* ```tsx
|
|
27
27
|
* const { mutateAsync } = useInstantOpenAuto();
|
|
28
28
|
* await mutateAsync({
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
29
|
+
* subAccountAddress, from: sessionKeyAddress,
|
|
30
|
+
* market: { id: 1 }, positionType: PositionType.LONG,
|
|
31
|
+
* fund: { mode: "full-balance", balance: "100" }, leverage: 5, slippage: 1,
|
|
32
32
|
* });
|
|
33
33
|
* ```
|
|
34
34
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-instant-open-auto.js","names":[],"sources":["../../src/instant-layer/use-instant-open-auto.ts"],"sourcesContent":["\"use client\";\n\nimport {\n getInstantOpensQueryKey,\n instantOpenAutoMutationOptions,\n type ConfigParameter,\n type InstantOpenReturnType,\n type PrepareInstantOpenParameters,\n} from \"@symmio/trading-core\";\nimport { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport { normalizeSymmError } from \"../errors/normalize-symm-error\";\nimport type { SymmioRequestError } from \"../errors/symmio-request-error\";\nimport { useSymmioChainId } from \"../provider/use-symmio-chain-id\";\nimport { useSymmioConfig } from \"../provider/use-symmio-config\";\nimport { invalidateAccountBalances, predicateMatch } from \"../utils\";\n\n/**\n * Parameters for {@link useInstantOpenAuto}.\n */\nexport type UseInstantOpenAutoParameters = ConfigParameter;\n\n/** Return type of {@link useInstantOpenAuto}. */\nexport type UseInstantOpenAutoReturnType = UseMutationResult<\n InstantOpenReturnType,\n SymmioRequestError,\n PrepareInstantOpenParameters\n>;\n\n/**\n * Open a lowcap instant position via the wizard `instantOpenAuto` action.\n *\n * Friendly default: accepts the minimal trade intent and lets the SDK fetch\n * market metadata, mark price, locked params, and fee rates. Pre-fill any\n * optional field on the variables (e.g. cache-hot `markPrice`) to skip its\n * fetch. For full control — inspect / mutate resolved params between fetch and\n * submit — use {@link useInstantOpen} after calling\n * `prepareInstantOpenParams(config, …)` directly.\n *\n * Funding is a one-of on the variables: a typed `initialMargin`, or\n * `fund: { mode: \"full-balance\", balance }` (lowcap only) to deploy the whole\n * balance into the position's VA with the quantity sized down to fit it —\n * see `FullBalanceFunding` in `@symmio/trading-core`.\n *\n * @example\n * ```tsx\n * const { mutateAsync } = useInstantOpenAuto();\n * await mutateAsync({\n *
|
|
1
|
+
{"version":3,"file":"use-instant-open-auto.js","names":[],"sources":["../../src/instant-layer/use-instant-open-auto.ts"],"sourcesContent":["\"use client\";\n\nimport {\n getInstantOpensQueryKey,\n instantOpenAutoMutationOptions,\n type ConfigParameter,\n type InstantOpenReturnType,\n type PrepareInstantOpenParameters,\n} from \"@symmio/trading-core\";\nimport { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport { normalizeSymmError } from \"../errors/normalize-symm-error\";\nimport type { SymmioRequestError } from \"../errors/symmio-request-error\";\nimport { useSymmioChainId } from \"../provider/use-symmio-chain-id\";\nimport { useSymmioConfig } from \"../provider/use-symmio-config\";\nimport { invalidateAccountBalances, predicateMatch } from \"../utils\";\n\n/**\n * Parameters for {@link useInstantOpenAuto}.\n */\nexport type UseInstantOpenAutoParameters = ConfigParameter;\n\n/** Return type of {@link useInstantOpenAuto}. */\nexport type UseInstantOpenAutoReturnType = UseMutationResult<\n InstantOpenReturnType,\n SymmioRequestError,\n PrepareInstantOpenParameters\n>;\n\n/**\n * Open a lowcap instant position via the wizard `instantOpenAuto` action.\n *\n * Friendly default: accepts the minimal trade intent and lets the SDK fetch\n * market metadata, mark price, locked params, and fee rates. Pre-fill any\n * optional field on the variables (e.g. cache-hot `markPrice`) to skip its\n * fetch. For full control — inspect / mutate resolved params between fetch and\n * submit — use {@link useInstantOpen} after calling\n * `prepareInstantOpenParams(config, …)` directly.\n *\n * Funding is a one-of on the variables: a typed `initialMargin`, or\n * `fund: { mode: \"full-balance\", balance }` (lowcap only) to deploy the whole\n * balance into the position's VA with the quantity sized down to fit it —\n * see `FullBalanceFunding` in `@symmio/trading-core`.\n *\n * @example\n * ```tsx\n * const { mutateAsync } = useInstantOpenAuto();\n * await mutateAsync({\n * subAccountAddress, from: sessionKeyAddress,\n * market: { id: 1 }, positionType: PositionType.LONG,\n * fund: { mode: \"full-balance\", balance: \"100\" }, leverage: 5, slippage: 1,\n * });\n * ```\n */\nexport function useInstantOpenAuto(parameters: UseInstantOpenAutoParameters = {}): UseInstantOpenAutoReturnType {\n const config = useSymmioConfig(parameters);\n const chainId = useSymmioChainId();\n const queryClient = useQueryClient();\n const base = instantOpenAutoMutationOptions(config);\n\n return useMutation<InstantOpenReturnType, SymmioRequestError, PrepareInstantOpenParameters>({\n mutationKey: base.mutationKey,\n mutationFn: async (variables) => {\n try {\n return await base.mutationFn({ ...variables, chainId: variables.chainId ?? chainId });\n } catch (err) {\n throw normalizeSymmError(err);\n }\n },\n onSuccess: (_result, variables) => {\n /**\n * A freshly submitted instant-open exists on the hedger but not in any\n * cached read yet. Invalidate the instant-opens feed so it refetches and\n * the optimistic row appears immediately — without waiting for a poll.\n */\n const configKey = config.getChainConfigKey(variables.chainId ?? chainId);\n void queryClient.invalidateQueries({ predicate: predicateMatch(getInstantOpensQueryKey, { configKey }) });\n /** The open locks margin and charges a fee — every balance read on this chain is now suspect. */\n invalidateAccountBalances(queryClient, { configKey });\n },\n });\n}\n"],"mappings":";;;;;;;;;AAqDA,SAAgB,EAAmB,IAA2C,CAAC,GAAiC;CAC9G,IAAM,IAAS,EAAgB,CAAU,GACnC,IAAU,EAAiB,GAC3B,IAAc,EAAe,GAC7B,IAAO,EAA+B,CAAM;CAElD,OAAO,EAAqF;EAC1F,aAAa,EAAK;EAClB,YAAY,OAAO,MAAc;GAC/B,IAAI;IACF,OAAO,MAAM,EAAK,WAAW;KAAE,GAAG;KAAW,SAAS,EAAU,WAAW;IAAQ,CAAC;GACtF,SAAS,GAAK;IACZ,MAAM,EAAmB,CAAG;GAC9B;EACF;EACA,YAAY,GAAS,MAAc;GAMjC,IAAM,IAAY,EAAO,kBAAkB,EAAU,WAAW,CAAO;GAGvE,AAFA,EAAiB,kBAAkB,EAAE,WAAW,EAAe,GAAyB,EAAE,aAAU,CAAC,EAAE,CAAC,GAExG,EAA0B,GAAa,EAAE,aAAU,CAAC;EACtD;CACF,CAAC;AACH"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ConfigParameter, GetInstantOpenFeesOptions, GetInstantOpenFeesReturnType } from '@symmio/trading-core';
|
|
2
2
|
import { UseQueryResult } from '@tanstack/react-query';
|
|
3
3
|
import { SymmioRequestError } from '../errors/symmio-request-error.js';
|
|
4
|
+
import { UseEstimatedPriceReturnType } from '../estimated-price/use-estimated-price.js';
|
|
4
5
|
/**
|
|
5
6
|
* Parameters for {@link useInstantOpenFees}: the trade intent
|
|
6
7
|
* (`subAccountAddress`, `market`, `positionType`, `initialMargin` **or**
|
|
@@ -10,6 +11,12 @@ import { SymmioRequestError } from '../errors/symmio-request-error.js';
|
|
|
10
11
|
export type UseInstantOpenFeesParameters = GetInstantOpenFeesOptions & ConfigParameter;
|
|
11
12
|
/** Return type of {@link useInstantOpenFees}. */
|
|
12
13
|
export type UseInstantOpenFeesReturnType = UseQueryResult<GetInstantOpenFeesReturnType, SymmioRequestError> & {
|
|
14
|
+
/**
|
|
15
|
+
* Refetch the SDK-managed estimate on the frontend's schedule. Resolves when
|
|
16
|
+
* the estimate request finishes; use isReady to await fee calculation. A supplied
|
|
17
|
+
* estimatedOpenPrice still takes precedence over the fetched value.
|
|
18
|
+
*/
|
|
19
|
+
refetchEstimatedPrice: UseEstimatedPriceReturnType["refetch"];
|
|
13
20
|
/** Synchronous input error. Display before query.error; dependent queries stay disabled. */
|
|
14
21
|
validationError: SymmioRequestError | undefined;
|
|
15
22
|
/** True when all inputs and the current fee preview have settled successfully. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-instant-open-fees.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-instant-open-fees.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,yBAAyB,EAC9B,KAAK,4BAA4B,EAClC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEtE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;
|
|
1
|
+
{"version":3,"file":"use-instant-open-fees.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-instant-open-fees.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,yBAAyB,EAC9B,KAAK,4BAA4B,EAClC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEtE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AAG1F;;;;;GAKG;AACH,MAAM,MAAM,4BAA4B,GAAG,yBAAyB,GAAG,eAAe,CAAC;AAEvF,iDAAiD;AACjD,MAAM,MAAM,4BAA4B,GAAG,cAAc,CAAC,4BAA4B,EAAE,kBAAkB,CAAC,GAAG;IAC5G;;;;OAIG;IACH,qBAAqB,EAAE,2BAA2B,CAAC,SAAS,CAAC,CAAC;IAC9D,4FAA4F;IAC5F,eAAe,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAChD,kFAAkF;IAClF,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,4BAA4B,GAAG,4BAA4B,CA4BzG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-instant-open-fees.js","names":[],"sources":["../../src/instant-layer/use-instant-open-fees.ts"],"sourcesContent":["\"use client\";\n\nimport {\n getInstantOpenFeesQueryOptions,\n type ConfigParameter,\n type GetInstantOpenFeesOptions,\n type GetInstantOpenFeesReturnType,\n} from \"@symmio/trading-core\";\nimport { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { normalizeSymmError } from \"../errors/normalize-symm-error\";\nimport type { SymmioRequestError } from \"../errors/symmio-request-error\";\nimport { useInstantOpenInputs } from \"./use-instant-open-inputs\";\n\n/**\n * Parameters for {@link useInstantOpenFees}: the trade intent\n * (`subAccountAddress`, `market`, `positionType`, `initialMargin` **or**\n * `fund` for a full-balance preview, `leverage`, optional `slippage` /\n * pre-fetched data, TanStack `query` overrides) plus an optional `config`.\n */\nexport type UseInstantOpenFeesParameters = GetInstantOpenFeesOptions & ConfigParameter;\n\n/** Return type of {@link useInstantOpenFees}. */\nexport type UseInstantOpenFeesReturnType = UseQueryResult<GetInstantOpenFeesReturnType, SymmioRequestError> & {\n /** Synchronous input error. Display before query.error; dependent queries stay disabled. */\n validationError: SymmioRequestError | undefined;\n /** True when all inputs and the current fee preview have settled successfully. */\n isReady: boolean;\n};\n\n/**\n * Preview every fee a new instant-open quote pays — separated by leg plus the\n * total — before the user submits. Read-only; nothing is signed.\n *\n * Wraps `getInstantOpenFees`, but **pre-fetches every input through its own\n * cached queries and passes them in as prefills**, so the query function is\n * pure math with zero network hops: market metadata (`useMarkets`) and\n * on-chain fee rates (`useFeeForUser`) and solver info are cached for minutes.\n * The mark price rides the shared price stream; the lowcap dry-run estimate\n * uses `useEstimatedPrice` (debounced internally). Previous data is\n * kept while inputs move, so a mark-price tick updates the numbers in place —\n * it never resets the result to a loading state.\n *\n * The result is a `kind`-discriminated union of the **open-side** legs: both\n * kinds carry `platformOpenFee`, the sized `quantity`, and `totalFee`; an\n * `\"enigma\"` (lowcap) result adds `openSolverFee`, `staticSolverFeeOpen`, and\n * `expectedSettlementLoss`. Close fees are charged at close from the position\n * and are deliberately not part of this preview — price them in the close flow\n * with `useInstantCloseFees`, where the notional and holding time are real.\n * `totalFee` includes the settlement provision by default; pass\n * `includeSettlementInTotalFee: false` to sum the fee legs only.\n *\n * With `fund` (`FullBalanceFunding`) instead of `initialMargin`, the\n * preview runs the same probe-and-rescale sizing as the open, so the legs and\n * `quantity` equal what a full-balance open will actually charge and submit —\n * the extra inputs it needs (locked-param percents, market quote constraints)\n * are prefetched here through the same cached queries.\n *\n * With `initialMargin` and `availableBalance`, core automatically uses full-balance\n * sizing when required funding exceeds the raw balance. `data.fundingMode` reports\n * the effective choice; pass the same inputs to preparation and submission.\n * Display `validationError ?? error` and check `isReady` before using the fees\n * for the current input. Input errors are synchronous, including offline.\n * A disabled hook or empty input remains idle without input validation.\n *\n * @example\n * ```tsx\n * const { data: fees } = useInstantOpenFees({\n * subAccountAddress,\n * market: { id: symbolId },\n * positionType,\n * initialMargin,\n * leverage,\n * });\n * // fees?.totalFee; fees?.kind === \"enigma\" && fees.expectedSettlementLoss\n * ```\n */\nexport function useInstantOpenFees(parameters: UseInstantOpenFeesParameters): UseInstantOpenFeesReturnType {\n const inputs = useInstantOpenInputs(parameters, \"fees\", parameters.query?.enabled !== false);\n const options = getInstantOpenFeesQueryOptions(inputs.config, {\n ...parameters,\n ...inputs.prefills,\n query: {\n ...parameters.query,\n enabled: inputs.ready,\n placeholderData: (previous) => (inputs.validationError === undefined ? previous : undefined),\n },\n });\n const query = useQuery({\n ...options,\n queryFn: async () => {\n try {\n return await options.queryFn();\n } catch (err) {\n throw normalizeSymmError(err);\n }\n },\n }) as UseQueryResult<GetInstantOpenFeesReturnType, SymmioRequestError>;\n\n return {\n ...query,\n validationError: inputs.validationError,\n isReady: inputs.ready && query.isSuccess && !query.isFetching && !query.isPlaceholderData,\n };\n}\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"use-instant-open-fees.js","names":[],"sources":["../../src/instant-layer/use-instant-open-fees.ts"],"sourcesContent":["\"use client\";\n\nimport {\n getInstantOpenFeesQueryOptions,\n type ConfigParameter,\n type GetInstantOpenFeesOptions,\n type GetInstantOpenFeesReturnType,\n} from \"@symmio/trading-core\";\nimport { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { normalizeSymmError } from \"../errors/normalize-symm-error\";\nimport type { SymmioRequestError } from \"../errors/symmio-request-error\";\nimport type { UseEstimatedPriceReturnType } from \"../estimated-price/use-estimated-price\";\nimport { useInstantOpenInputs } from \"./use-instant-open-inputs\";\n\n/**\n * Parameters for {@link useInstantOpenFees}: the trade intent\n * (`subAccountAddress`, `market`, `positionType`, `initialMargin` **or**\n * `fund` for a full-balance preview, `leverage`, optional `slippage` /\n * pre-fetched data, TanStack `query` overrides) plus an optional `config`.\n */\nexport type UseInstantOpenFeesParameters = GetInstantOpenFeesOptions & ConfigParameter;\n\n/** Return type of {@link useInstantOpenFees}. */\nexport type UseInstantOpenFeesReturnType = UseQueryResult<GetInstantOpenFeesReturnType, SymmioRequestError> & {\n /**\n * Refetch the SDK-managed estimate on the frontend's schedule. Resolves when\n * the estimate request finishes; use isReady to await fee calculation. A supplied\n * estimatedOpenPrice still takes precedence over the fetched value.\n */\n refetchEstimatedPrice: UseEstimatedPriceReturnType[\"refetch\"];\n /** Synchronous input error. Display before query.error; dependent queries stay disabled. */\n validationError: SymmioRequestError | undefined;\n /** True when all inputs and the current fee preview have settled successfully. */\n isReady: boolean;\n};\n\n/**\n * Preview every fee a new instant-open quote pays — separated by leg plus the\n * total — before the user submits. Read-only; nothing is signed.\n *\n * Wraps `getInstantOpenFees`, but **pre-fetches every input through its own\n * cached queries and passes them in as prefills**, so the query function is\n * pure math with zero network hops: market metadata (`useMarkets`) and\n * on-chain fee rates (`useFeeForUser`) and solver info are cached for minutes.\n * The mark price rides the shared price stream; the lowcap dry-run estimate\n * uses `useEstimatedPrice` (debounced internally). Previous data is\n * kept while inputs move, so a mark-price tick updates the numbers in place —\n * it never resets the result to a loading state.\n *\n * The result is a `kind`-discriminated union of the **open-side** legs: both\n * kinds carry `platformOpenFee`, the sized `quantity`, and `totalFee`; an\n * `\"enigma\"` (lowcap) result adds `openSolverFee`, `staticSolverFeeOpen`, and\n * `expectedSettlementLoss`. Close fees are charged at close from the position\n * and are deliberately not part of this preview — price them in the close flow\n * with `useInstantCloseFees`, where the notional and holding time are real.\n * `totalFee` includes the settlement provision by default; pass\n * `includeSettlementInTotalFee: false` to sum the fee legs only.\n *\n * With `fund` (`FullBalanceFunding`) instead of `initialMargin`, the\n * preview runs the same probe-and-rescale sizing as the open, so the legs and\n * `quantity` equal what a full-balance open will actually charge and submit —\n * the extra inputs it needs (locked-param percents, market quote constraints)\n * are prefetched here through the same cached queries.\n *\n * With `initialMargin` and `availableBalance`, core automatically uses full-balance\n * sizing when required funding exceeds the raw balance. `data.fundingMode` reports\n * the effective choice; pass the same inputs to preparation and submission.\n * Display `validationError ?? error` and check `isReady` before using the fees\n * for the current input. Input errors are synchronous, including offline.\n * A disabled hook or empty input remains idle without input validation.\n *\n * @example\n * ```tsx\n * const { data: fees } = useInstantOpenFees({\n * subAccountAddress,\n * market: { id: symbolId },\n * positionType,\n * initialMargin,\n * leverage,\n * });\n * // fees?.totalFee; fees?.kind === \"enigma\" && fees.expectedSettlementLoss\n * ```\n */\nexport function useInstantOpenFees(parameters: UseInstantOpenFeesParameters): UseInstantOpenFeesReturnType {\n const inputs = useInstantOpenInputs(parameters, \"fees\", parameters.query?.enabled !== false);\n const options = getInstantOpenFeesQueryOptions(inputs.config, {\n ...parameters,\n ...inputs.prefills,\n query: {\n ...parameters.query,\n enabled: inputs.ready,\n placeholderData: (previous) => (inputs.validationError === undefined ? previous : undefined),\n },\n });\n const query = useQuery({\n ...options,\n queryFn: async () => {\n try {\n return await options.queryFn();\n } catch (err) {\n throw normalizeSymmError(err);\n }\n },\n }) as UseQueryResult<GetInstantOpenFeesReturnType, SymmioRequestError>;\n\n return {\n ...query,\n refetchEstimatedPrice: inputs.refetchEstimatedPrice,\n validationError: inputs.validationError,\n isReady: inputs.ready && query.isSuccess && !query.isFetching && !query.isPlaceholderData,\n };\n}\n"],"mappings":";;;;;;AAmFA,SAAgB,EAAmB,GAAwE;CACzG,IAAM,IAAS,EAAqB,GAAY,QAAQ,EAAW,OAAO,YAAY,EAAK,GACrF,IAAU,EAA+B,EAAO,QAAQ;EAC5D,GAAG;EACH,GAAG,EAAO;EACV,OAAO;GACL,GAAG,EAAW;GACd,SAAS,EAAO;GAChB,kBAAkB,MAAc,EAAO,oBAAoB,KAAA,IAAY,IAAW,KAAA;EACpF;CACF,CAAC,GACK,IAAQ,EAAS;EACrB,GAAG;EACH,SAAS,YAAY;GACnB,IAAI;IACF,OAAO,MAAM,EAAQ,QAAQ;GAC/B,SAAS,GAAK;IACZ,MAAM,EAAmB,CAAG;GAC9B;EACF;CACF,CAAC;CAED,OAAO;EACL,GAAG;EACH,uBAAuB,EAAO;EAC9B,iBAAiB,EAAO;EACxB,SAAS,EAAO,SAAS,EAAM,aAAa,CAAC,EAAM,cAAc,CAAC,EAAM;CAC1E;AACF"}
|
|
@@ -4,6 +4,8 @@ export declare function useInstantOpenInputs(parameters: GetInstantOpenFeesParam
|
|
|
4
4
|
config: import('@symmio/trading-core').Config;
|
|
5
5
|
validationError: import('../index.js').SymmioRequestError | undefined;
|
|
6
6
|
ready: boolean;
|
|
7
|
+
refetchEstimatedPrice: (options?: import('@tanstack/query-core').RefetchOptions) => Promise<import('@tanstack/query-core').QueryObserverResult<import('@symmio/trading-core').GetEstimatedPriceReturnType, import('../index.js').SymmioRequestError>>;
|
|
8
|
+
estimatedOpenPriceTimestamp: number | undefined;
|
|
7
9
|
prefills: {
|
|
8
10
|
chainId: number;
|
|
9
11
|
market: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-instant-open-inputs.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-instant-open-inputs.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,4BAA4B,EAClC,MAAM,sBAAsB,CAAC;AAY9B,8FAA8F;AAC9F,wBAAgB,oBAAoB,CAClC,UAAU,EAAE,4BAA4B,GAAG,eAAe,EAC1D,OAAO,EAAE,SAAS,GAAG,MAAM,EAC3B,YAAY,UAAO
|
|
1
|
+
{"version":3,"file":"use-instant-open-inputs.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-instant-open-inputs.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,4BAA4B,EAClC,MAAM,sBAAsB,CAAC;AAY9B,8FAA8F;AAC9F,wBAAgB,oBAAoB,CAClC,UAAU,EAAE,4BAA4B,GAAG,eAAe,EAC1D,OAAO,EAAE,SAAS,GAAG,MAAM,EAC3B,YAAY,UAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+NpB"}
|
|
@@ -99,6 +99,8 @@ function o(o, s, c = !0) {
|
|
|
99
99
|
config: l,
|
|
100
100
|
validationError: w,
|
|
101
101
|
ready: T && D !== void 0 && O !== void 0 && k !== void 0 && J !== void 0 && Y !== void 0 && de && (!C || A !== void 0 && j !== void 0) && H && ce && fe && Q,
|
|
102
|
+
refetchEstimatedPrice: Z.refetch,
|
|
103
|
+
estimatedOpenPriceTimestamp: Z.isPlaceholderData ? void 0 : Z.dataUpdatedAt || void 0,
|
|
102
104
|
prefills: {
|
|
103
105
|
chainId: d,
|
|
104
106
|
market: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-instant-open-inputs.js","names":[],"sources":["../../src/instant-layer/use-instant-open-inputs.ts"],"sourcesContent":["\"use client\";\n\nimport {\n calculateTradeParams,\n PositionType,\n type ConfigParameter,\n type GetInstantOpenFeesParameters,\n} from \"@symmio/trading-core\";\nimport { useMemo } from \"react\";\nimport { useEstimatedPrice } from \"../estimated-price/use-estimated-price\";\nimport { useFeeForUser } from \"../fees/use-fee-for-user\";\nimport { useLockedParams } from \"../locked-params/use-locked-params\";\nimport { useMarkets } from \"../markets/use-markets\";\nimport { usePriceByName } from \"../price-service/use-price-by-name\";\nimport { useSymmioChainId } from \"../provider/use-symmio-chain-id\";\nimport { useSymmioConfig } from \"../provider/use-symmio-config\";\nimport { useSolverInfo } from \"../solvers/use-solver-info\";\nimport { getInstantOpenFundingError } from \"./get-instant-open-funding-error\";\n\n/** Shared input orchestration for preparation and fee previews; calculations stay in core. */\nexport function useInstantOpenInputs(\n parameters: GetInstantOpenFeesParameters & ConfigParameter,\n purpose: \"prepare\" | \"fees\",\n queryEnabled = true,\n) {\n const config = useSymmioConfig(parameters);\n const contextChainId = useSymmioChainId();\n const chainId = parameters.chainId ?? contextChainId;\n const { subAccountAddress, market, positionType, initialMargin, fund, leverage, solverId } = parameters;\n const isFullBalance = fund !== undefined;\n const canSizeFullBalance = isFullBalance || parameters.availableBalance !== undefined;\n const needsLockedParams = purpose === \"prepare\" || canSizeFullBalance;\n const needsSolverFeeCaps = purpose === \"prepare\" && config.getChainConfig(chainId).contractsVersion === \"0.8.6\";\n /** The amount driving the sizing math — the typed margin, or the whole balance in full-balance mode. */\n const sizingInput = isFullBalance ? fund.balance : (initialMargin ?? \"\");\n const requested = queryEnabled && sizingInput.length > 0;\n\n /** The dry-run estimate exists only on lowcap (Enigma) solvers. */\n const isLowcap = config.getSolver({ chainId, solverId }).id === \"enigma\";\n const validationError = requested ? getInstantOpenFundingError({ ...parameters, isLowcap }) : undefined;\n const enabled = requested && validationError === undefined;\n\n // Market metadata — slow-moving; dedupes with any other useMarkets on the page.\n const marketsQuery = useMarkets({\n config: parameters.config,\n chainId,\n solverId,\n query: { enabled, staleTime: 300_000 },\n });\n const resolvedMarket = marketsQuery.data?.find((entry) => entry.symbolId === market.id);\n const marketName = market.name ?? resolvedMarket?.name;\n const pricePrecision = market.pricePrecision ?? resolvedMarket?.pricePrecision;\n const quantityPrecision = market.quantityPrecision ?? resolvedMarket?.quantityPrecision;\n const hedgerFeeOpen = market.hedgerFeeOpen ?? resolvedMarket?.hedgerFeeOpen;\n const hedgerFeeClose = market.hedgerFeeClose ?? resolvedMarket?.hedgerFeeClose;\n\n const minOpenSolverFeeCap =\n market.minOpenSolverFeeCap ??\n (resolvedMarket ? (resolvedMarket.kind === \"enigma\" ? resolvedMarket.minOpenSolverFeeCap : \"0\") : undefined);\n const minCloseSolverFeeCap =\n market.minCloseSolverFeeCap ??\n (resolvedMarket ? (resolvedMarket.kind === \"enigma\" ? resolvedMarket.minCloseSolverFeeCap : \"0\") : undefined);\n const capsReady = !needsSolverFeeCaps || (minOpenSolverFeeCap !== undefined && minCloseSolverFeeCap !== undefined);\n\n // Time-decaying close-fee rates ride the same `useMarkets` read — Enigma-only\n // fields on `EnigmaMarket`, so narrow on `kind` before reading.\n const resolvedEnigmaMarket = resolvedMarket?.kind === \"enigma\" ? resolvedMarket : undefined;\n const hedgerFeeCloseEarlyRate =\n market.hedgerFeeCloseEarlyRate ?? resolvedEnigmaMarket?.hedgerFeeCloseEarlyRate ?? hedgerFeeClose;\n const hedgerFeeCloseEarlyThreshold =\n market.hedgerFeeCloseEarlyThreshold ?? resolvedEnigmaMarket?.hedgerFeeCloseEarlyThreshold ?? 0;\n const hedgerFeeCloseStandardThreshold =\n market.hedgerFeeCloseStandardThreshold ?? resolvedEnigmaMarket?.hedgerFeeCloseStandardThreshold ?? 0;\n\n // Quote constraints — explicit or automatic full-balance sizing snaps to the lot grid and checks the\n // published floors; they ride the same `useMarkets` read.\n const minAcceptablePortionLf = market.minAcceptablePortionLf ?? resolvedMarket?.minAcceptablePortionLf;\n const minAcceptableQuoteValue = market.minAcceptableQuoteValue ?? resolvedMarket?.minAcceptableQuoteValue;\n const maxNotionalValue = market.maxNotionalValue ?? resolvedMarket?.maxNotionalValue;\n const minNotionalValue = market.minNotionalValue ?? resolvedMarket?.minNotionalValue;\n const maxQuantity = market.maxQuantity ?? resolvedMarket?.maxQuantity;\n const lotSize = market.lotSize ?? resolvedMarket?.lotSize;\n const constraintsReady =\n !canSizeFullBalance ||\n (minAcceptablePortionLf !== undefined &&\n minAcceptableQuoteValue !== undefined &&\n maxNotionalValue !== undefined &&\n minNotionalValue !== undefined &&\n maxQuantity !== undefined &&\n lotSize !== undefined);\n\n // Preparation always needs locks; the fee preview needs them only for balance sizing.\n const locksPrefilled =\n parameters.lockedParamPercent?.cva !== undefined &&\n parameters.lockedParamPercent.lf !== undefined &&\n parameters.lockedParamPercent.partyAmm !== undefined &&\n parameters.lockedParamPercent.partyBmm !== undefined;\n const lockedParamsQuery = useLockedParams({\n config: parameters.config,\n chainId,\n solverId,\n symbol: marketName ?? \"\",\n leverage,\n query: {\n enabled: enabled && needsLockedParams && !locksPrefilled && marketName !== undefined,\n staleTime: 300_000,\n },\n });\n const lockedParamPercent = locksPrefilled\n ? parameters.lockedParamPercent\n : lockedParamsQuery.data\n ? {\n // The resolver skips its fetch only when all four fields are present —\n // mirror its `\"0\"` defaults for fields the solver omits.\n cva: lockedParamsQuery.data.cva ?? \"0\",\n lf: lockedParamsQuery.data.lf ?? \"0\",\n partyAmm: lockedParamsQuery.data.partyAmm ?? \"0\",\n partyBmm: lockedParamsQuery.data.partyBmm ?? \"0\",\n }\n : undefined;\n const lockedParamsReady = !needsLockedParams || lockedParamPercent !== undefined;\n\n // Static solver fees follow the same cached input path as the other prefills.\n // A failed optional /info read keeps core's existing zero-static-fee fallback.\n const solverInfoQuery = useSolverInfo({\n config: parameters.config,\n chainId,\n solverId,\n query: { enabled: enabled && isLowcap && parameters.solverInfo === undefined, staleTime: 300_000, retry: false },\n });\n const solverInfo = parameters.solverInfo ?? solverInfoQuery.data ?? (solverInfoQuery.isError ? {} : undefined);\n const solverInfoReady = !isLowcap || solverInfo !== undefined;\n\n // On-chain platform fee rates — contract state, changes rarely; cached hard.\n const feeQuery = useFeeForUser({\n config: parameters.config,\n chainId,\n user: subAccountAddress,\n symbolId: BigInt(market.id),\n query: { enabled: enabled && parameters.feeRates === undefined, staleTime: 300_000 },\n });\n const feeRates = parameters.feeRates ?? feeQuery.data;\n\n // Mark price — caller's cache-hot value wins; otherwise the shared stream.\n const priceQuery = usePriceByName({\n name: marketName,\n solverId,\n enabled: enabled && parameters.markPrice === undefined,\n });\n const markPrice = parameters.markPrice ?? priceQuery.markPrice ?? undefined;\n\n // Lowcap dry-run estimate: mark-sized quantity, wide fixed request bound so the\n // solver's price gate never rejects the question. Debounced internally.\n const estimateQuantity = useMemo(() => {\n if (!enabled || !isLowcap || markPrice === undefined) return \"\";\n if (pricePrecision === undefined || quantityPrecision === undefined) return \"\";\n const sized = calculateTradeParams({\n markPrice,\n slippage: 0,\n positionType,\n userInput: sizingInput,\n inputField: \"PRICE\",\n leverage,\n pricePrecision,\n quantityPrecision,\n });\n return sized?.quantity ?? \"\";\n }, [enabled, isLowcap, markPrice, pricePrecision, quantityPrecision, positionType, sizingInput, leverage]);\n const estimateRequestPrice =\n markPrice !== undefined ? String(Number(markPrice) * (positionType === PositionType.SHORT ? 0.5 : 1.5)) : \"\";\n const estimateQuery = useEstimatedPrice({\n config: parameters.config,\n chainId,\n solverId,\n symbolId: market.id,\n quantity: estimateQuantity,\n positionType,\n entry: \"open\",\n price: estimateRequestPrice,\n query: {\n enabled: enabled && isLowcap && parameters.estimatedOpenPrice === undefined && estimateQuantity.length > 0,\n staleTime: 30_000,\n },\n });\n // undefined = pending, string = available, null = settled but unavailable.\n // Pass null through to core so a failed cached request is not fetched again.\n const estimateUpdating =\n isLowcap && parameters.estimatedOpenPrice === undefined && (estimateQuery.isDebouncing || estimateQuery.isFetching);\n const estimateSettled =\n !isLowcap ||\n parameters.estimatedOpenPrice !== undefined ||\n (!estimateUpdating && (estimateQuery.isFetched || estimateQuery.isError));\n const resolvedEstimate =\n parameters.estimatedOpenPrice !== undefined ? parameters.estimatedOpenPrice : estimateQuery.data?.estimatedPrice;\n const estimatedOpenPrice =\n !isLowcap || !estimateSettled ? undefined : resolvedEstimate && resolvedEstimate !== \"0\" ? resolvedEstimate : null;\n\n // Every prefill present → the query function is pure, zero fetches.\n const ready =\n enabled &&\n marketName !== undefined &&\n pricePrecision !== undefined &&\n quantityPrecision !== undefined &&\n feeRates !== undefined &&\n markPrice !== undefined &&\n lockedParamsReady &&\n (!isLowcap || (hedgerFeeOpen !== undefined && hedgerFeeClose !== undefined)) &&\n constraintsReady &&\n capsReady &&\n solverInfoReady &&\n estimateSettled;\n\n return {\n config,\n validationError,\n ready,\n prefills: {\n chainId,\n market: {\n id: market.id,\n name: marketName,\n pricePrecision,\n quantityPrecision,\n minOpenSolverFeeCap,\n minCloseSolverFeeCap,\n hedgerFeeOpen,\n hedgerFeeClose,\n hedgerFeeCloseEarlyRate,\n hedgerFeeCloseEarlyThreshold,\n hedgerFeeCloseStandardThreshold,\n minAcceptablePortionLf,\n minAcceptableQuoteValue,\n maxNotionalValue,\n minNotionalValue,\n maxQuantity,\n lotSize,\n },\n markPrice,\n feeRates,\n lockedParamPercent,\n solverInfo,\n estimatedOpenPrice,\n },\n };\n}\n"],"mappings":";;;;;;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ACb,MAAc,KAAA,KACd,OACC,CAAC,KAAa,MAAkB,KAAA,KAAa,MAAmB,KAAA,MACjE,KACA,MACA,MACA;EAMA,UAAU;GACR;GACA,QAAQ;IACN,IAAI,EAAO;IACX,MAAM;IACN;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GACF;GACA;GACA;GACA;GACA;GACA;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"use-instant-open-inputs.js","names":[],"sources":["../../src/instant-layer/use-instant-open-inputs.ts"],"sourcesContent":["\"use client\";\n\nimport {\n calculateTradeParams,\n PositionType,\n type ConfigParameter,\n type GetInstantOpenFeesParameters,\n} from \"@symmio/trading-core\";\nimport { useMemo } from \"react\";\nimport { useEstimatedPrice } from \"../estimated-price/use-estimated-price\";\nimport { useFeeForUser } from \"../fees/use-fee-for-user\";\nimport { useLockedParams } from \"../locked-params/use-locked-params\";\nimport { useMarkets } from \"../markets/use-markets\";\nimport { usePriceByName } from \"../price-service/use-price-by-name\";\nimport { useSymmioChainId } from \"../provider/use-symmio-chain-id\";\nimport { useSymmioConfig } from \"../provider/use-symmio-config\";\nimport { useSolverInfo } from \"../solvers/use-solver-info\";\nimport { getInstantOpenFundingError } from \"./get-instant-open-funding-error\";\n\n/** Shared input orchestration for preparation and fee previews; calculations stay in core. */\nexport function useInstantOpenInputs(\n parameters: GetInstantOpenFeesParameters & ConfigParameter,\n purpose: \"prepare\" | \"fees\",\n queryEnabled = true,\n) {\n const config = useSymmioConfig(parameters);\n const contextChainId = useSymmioChainId();\n const chainId = parameters.chainId ?? contextChainId;\n const { subAccountAddress, market, positionType, initialMargin, fund, leverage, solverId } = parameters;\n const isFullBalance = fund !== undefined;\n const canSizeFullBalance = isFullBalance || parameters.availableBalance !== undefined;\n const needsLockedParams = purpose === \"prepare\" || canSizeFullBalance;\n const needsSolverFeeCaps = purpose === \"prepare\" && config.getChainConfig(chainId).contractsVersion === \"0.8.6\";\n /** The amount driving the sizing math — the typed margin, or the whole balance in full-balance mode. */\n const sizingInput = isFullBalance ? fund.balance : (initialMargin ?? \"\");\n const requested = queryEnabled && sizingInput.length > 0;\n\n /** The dry-run estimate exists only on lowcap (Enigma) solvers. */\n const isLowcap = config.getSolver({ chainId, solverId }).id === \"enigma\";\n const validationError = requested ? getInstantOpenFundingError({ ...parameters, isLowcap }) : undefined;\n const enabled = requested && validationError === undefined;\n\n // Market metadata — slow-moving; dedupes with any other useMarkets on the page.\n const marketsQuery = useMarkets({\n config: parameters.config,\n chainId,\n solverId,\n query: { enabled, staleTime: 300_000 },\n });\n const resolvedMarket = marketsQuery.data?.find((entry) => entry.symbolId === market.id);\n const marketName = market.name ?? resolvedMarket?.name;\n const pricePrecision = market.pricePrecision ?? resolvedMarket?.pricePrecision;\n const quantityPrecision = market.quantityPrecision ?? resolvedMarket?.quantityPrecision;\n const hedgerFeeOpen = market.hedgerFeeOpen ?? resolvedMarket?.hedgerFeeOpen;\n const hedgerFeeClose = market.hedgerFeeClose ?? resolvedMarket?.hedgerFeeClose;\n\n const minOpenSolverFeeCap =\n market.minOpenSolverFeeCap ??\n (resolvedMarket ? (resolvedMarket.kind === \"enigma\" ? resolvedMarket.minOpenSolverFeeCap : \"0\") : undefined);\n const minCloseSolverFeeCap =\n market.minCloseSolverFeeCap ??\n (resolvedMarket ? (resolvedMarket.kind === \"enigma\" ? resolvedMarket.minCloseSolverFeeCap : \"0\") : undefined);\n const capsReady = !needsSolverFeeCaps || (minOpenSolverFeeCap !== undefined && minCloseSolverFeeCap !== undefined);\n\n // Time-decaying close-fee rates ride the same `useMarkets` read — Enigma-only\n // fields on `EnigmaMarket`, so narrow on `kind` before reading.\n const resolvedEnigmaMarket = resolvedMarket?.kind === \"enigma\" ? resolvedMarket : undefined;\n const hedgerFeeCloseEarlyRate =\n market.hedgerFeeCloseEarlyRate ?? resolvedEnigmaMarket?.hedgerFeeCloseEarlyRate ?? hedgerFeeClose;\n const hedgerFeeCloseEarlyThreshold =\n market.hedgerFeeCloseEarlyThreshold ?? resolvedEnigmaMarket?.hedgerFeeCloseEarlyThreshold ?? 0;\n const hedgerFeeCloseStandardThreshold =\n market.hedgerFeeCloseStandardThreshold ?? resolvedEnigmaMarket?.hedgerFeeCloseStandardThreshold ?? 0;\n\n // Quote constraints — explicit or automatic full-balance sizing snaps to the lot grid and checks the\n // published floors; they ride the same `useMarkets` read.\n const minAcceptablePortionLf = market.minAcceptablePortionLf ?? resolvedMarket?.minAcceptablePortionLf;\n const minAcceptableQuoteValue = market.minAcceptableQuoteValue ?? resolvedMarket?.minAcceptableQuoteValue;\n const maxNotionalValue = market.maxNotionalValue ?? resolvedMarket?.maxNotionalValue;\n const minNotionalValue = market.minNotionalValue ?? resolvedMarket?.minNotionalValue;\n const maxQuantity = market.maxQuantity ?? resolvedMarket?.maxQuantity;\n const lotSize = market.lotSize ?? resolvedMarket?.lotSize;\n const constraintsReady =\n !canSizeFullBalance ||\n (minAcceptablePortionLf !== undefined &&\n minAcceptableQuoteValue !== undefined &&\n maxNotionalValue !== undefined &&\n minNotionalValue !== undefined &&\n maxQuantity !== undefined &&\n lotSize !== undefined);\n\n // Preparation always needs locks; the fee preview needs them only for balance sizing.\n const locksPrefilled =\n parameters.lockedParamPercent?.cva !== undefined &&\n parameters.lockedParamPercent.lf !== undefined &&\n parameters.lockedParamPercent.partyAmm !== undefined &&\n parameters.lockedParamPercent.partyBmm !== undefined;\n const lockedParamsQuery = useLockedParams({\n config: parameters.config,\n chainId,\n solverId,\n symbol: marketName ?? \"\",\n leverage,\n query: {\n enabled: enabled && needsLockedParams && !locksPrefilled && marketName !== undefined,\n staleTime: 300_000,\n },\n });\n const lockedParamPercent = locksPrefilled\n ? parameters.lockedParamPercent\n : lockedParamsQuery.data\n ? {\n // The resolver skips its fetch only when all four fields are present —\n // mirror its `\"0\"` defaults for fields the solver omits.\n cva: lockedParamsQuery.data.cva ?? \"0\",\n lf: lockedParamsQuery.data.lf ?? \"0\",\n partyAmm: lockedParamsQuery.data.partyAmm ?? \"0\",\n partyBmm: lockedParamsQuery.data.partyBmm ?? \"0\",\n }\n : undefined;\n const lockedParamsReady = !needsLockedParams || lockedParamPercent !== undefined;\n\n // Static solver fees follow the same cached input path as the other prefills.\n // A failed optional /info read keeps core's existing zero-static-fee fallback.\n const solverInfoQuery = useSolverInfo({\n config: parameters.config,\n chainId,\n solverId,\n query: { enabled: enabled && isLowcap && parameters.solverInfo === undefined, staleTime: 300_000, retry: false },\n });\n const solverInfo = parameters.solverInfo ?? solverInfoQuery.data ?? (solverInfoQuery.isError ? {} : undefined);\n const solverInfoReady = !isLowcap || solverInfo !== undefined;\n\n // On-chain platform fee rates — contract state, changes rarely; cached hard.\n const feeQuery = useFeeForUser({\n config: parameters.config,\n chainId,\n user: subAccountAddress,\n symbolId: BigInt(market.id),\n query: { enabled: enabled && parameters.feeRates === undefined, staleTime: 300_000 },\n });\n const feeRates = parameters.feeRates ?? feeQuery.data;\n\n // Mark price — caller's cache-hot value wins; otherwise the shared stream.\n const priceQuery = usePriceByName({\n name: marketName,\n solverId,\n enabled: enabled && parameters.markPrice === undefined,\n });\n const markPrice = parameters.markPrice ?? priceQuery.markPrice ?? undefined;\n\n // Lowcap dry-run estimate: mark-sized quantity, wide fixed request bound so the\n // solver's price gate never rejects the question. Debounced internally.\n const estimateQuantity = useMemo(() => {\n if (!enabled || !isLowcap || markPrice === undefined) return \"\";\n if (pricePrecision === undefined || quantityPrecision === undefined) return \"\";\n const sized = calculateTradeParams({\n markPrice,\n slippage: 0,\n positionType,\n userInput: sizingInput,\n inputField: \"PRICE\",\n leverage,\n pricePrecision,\n quantityPrecision,\n });\n return sized?.quantity ?? \"\";\n }, [enabled, isLowcap, markPrice, pricePrecision, quantityPrecision, positionType, sizingInput, leverage]);\n const estimateRequestPrice =\n markPrice !== undefined ? String(Number(markPrice) * (positionType === PositionType.SHORT ? 0.5 : 1.5)) : \"\";\n const estimateQuery = useEstimatedPrice({\n config: parameters.config,\n chainId,\n solverId,\n symbolId: market.id,\n quantity: estimateQuantity,\n positionType,\n entry: \"open\",\n price: estimateRequestPrice,\n query: {\n enabled: enabled && isLowcap && parameters.estimatedOpenPrice === undefined && estimateQuantity.length > 0,\n staleTime: 30_000,\n },\n });\n // undefined = pending, string = available, null = settled but unavailable.\n // Pass null through to core so a failed cached request is not fetched again.\n const estimateUpdating =\n isLowcap && parameters.estimatedOpenPrice === undefined && (estimateQuery.isDebouncing || estimateQuery.isFetching);\n const estimateSettled =\n !isLowcap ||\n parameters.estimatedOpenPrice !== undefined ||\n (!estimateUpdating && (estimateQuery.isFetched || estimateQuery.isError));\n const resolvedEstimate =\n parameters.estimatedOpenPrice !== undefined ? parameters.estimatedOpenPrice : estimateQuery.data?.estimatedPrice;\n const estimatedOpenPrice =\n !isLowcap || !estimateSettled ? undefined : resolvedEstimate && resolvedEstimate !== \"0\" ? resolvedEstimate : null;\n\n // Every prefill present → the query function is pure, zero fetches.\n const ready =\n enabled &&\n marketName !== undefined &&\n pricePrecision !== undefined &&\n quantityPrecision !== undefined &&\n feeRates !== undefined &&\n markPrice !== undefined &&\n lockedParamsReady &&\n (!isLowcap || (hedgerFeeOpen !== undefined && hedgerFeeClose !== undefined)) &&\n constraintsReady &&\n capsReady &&\n solverInfoReady &&\n estimateSettled;\n\n return {\n config,\n validationError,\n ready,\n refetchEstimatedPrice: estimateQuery.refetch,\n estimatedOpenPriceTimestamp: estimateQuery.isPlaceholderData ? undefined : estimateQuery.dataUpdatedAt || undefined,\n prefills: {\n chainId,\n market: {\n id: market.id,\n name: marketName,\n pricePrecision,\n quantityPrecision,\n minOpenSolverFeeCap,\n minCloseSolverFeeCap,\n hedgerFeeOpen,\n hedgerFeeClose,\n hedgerFeeCloseEarlyRate,\n hedgerFeeCloseEarlyThreshold,\n hedgerFeeCloseStandardThreshold,\n minAcceptablePortionLf,\n minAcceptableQuoteValue,\n maxNotionalValue,\n minNotionalValue,\n maxQuantity,\n lotSize,\n },\n markPrice,\n feeRates,\n lockedParam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A,KACf,MAAmB,KAAA,KACnB,MAAsB,KAAA,KACtB,MAAa,KAAA,KACb,MAAc,KAAA,KACd,OACC,CAAC,KAAa,MAAkB,KAAA,KAAa,MAAmB,KAAA,MACjE,KACA,MACA,MACA;EAMA,uBAAuB,EAAc;EACrC,6BAA6B,EAAc,oBAAoB,KAAA,IAAY,EAAc,iBAAiB,KAAA;EAC1G,UAAU;GACR;GACA,QAAQ;IACN,IAAI,EAAO;IACX,MAAM;IACN;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GACF;GACA;GACA;GACA;GACA;GACA;EACF;CACF;AACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ConfigParameter, PrepareInstantOpenParamsOptions, PrepareInstantOpenParamsReturnType } from '@symmio/trading-core';
|
|
2
2
|
import { UseQueryResult } from '@tanstack/react-query';
|
|
3
3
|
import { SymmioRequestError } from '../errors/symmio-request-error.js';
|
|
4
|
+
import { UseEstimatedPriceReturnType } from '../estimated-price/use-estimated-price.js';
|
|
4
5
|
/**
|
|
5
6
|
* Parameters for {@link usePrepareInstantOpenParams}: the same trade intent the
|
|
6
7
|
* submit takes (`subAccountAddress`, `from`, `market`, `positionType`,
|
|
@@ -22,6 +23,14 @@ export type UsePrepareInstantOpenParamsReturnType = UseQueryResult<PrepareInstan
|
|
|
22
23
|
* preview bit-for-bit.
|
|
23
24
|
*/
|
|
24
25
|
estimatedOpenPrice: string | null | undefined;
|
|
26
|
+
/** Arrival time of the fetched estimate in epoch milliseconds. The frontend decides when to refresh or expire it. */
|
|
27
|
+
estimatedOpenPriceTimestamp: number | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Refetch the SDK-managed estimate on the frontend's schedule. Resolves when
|
|
30
|
+
* the estimate request finishes; use isReady to await preparation. A supplied
|
|
31
|
+
* estimatedOpenPrice still takes precedence over the fetched value.
|
|
32
|
+
*/
|
|
33
|
+
refetchEstimatedPrice: UseEstimatedPriceReturnType["refetch"];
|
|
25
34
|
/** Synchronous input error. Display before query.error; dependent queries stay disabled. */
|
|
26
35
|
validationError: SymmioRequestError | undefined;
|
|
27
36
|
/** True when all inputs and the current preparation have settled; gate submission on this. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-prepare-instant-open-params.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-prepare-instant-open-params.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,+BAA+B,EACpC,KAAK,kCAAkC,EACxC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEtE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;
|
|
1
|
+
{"version":3,"file":"use-prepare-instant-open-params.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-prepare-instant-open-params.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,+BAA+B,EACpC,KAAK,kCAAkC,EACxC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEtE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AAG1F;;;;;;GAMG;AACH,MAAM,MAAM,qCAAqC,GAAG,+BAA+B,GAAG,eAAe,CAAC;AAEtG;;;;GAIG;AACH,MAAM,MAAM,qCAAqC,GAAG,cAAc,CAChE,kCAAkC,EAClC,kBAAkB,CACnB,GAAG;IACF;;;;;OAKG;IACH,kBAAkB,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAC9C,qHAAqH;IACrH,2BAA2B,EAAE,MAAM,GAAG,SAAS,CAAC;IAChD;;;;OAIG;IACH,qBAAqB,EAAE,2BAA2B,CAAC,SAAS,CAAC,CAAC;IAC9D,4FAA4F;IAC5F,eAAe,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAChD,8FAA8F;IAC9F,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,2BAA2B,CACzC,UAAU,EAAE,qCAAqC,GAChD,qCAAqC,CA8BvC"}
|
|
@@ -25,8 +25,10 @@ function i(i) {
|
|
|
25
25
|
});
|
|
26
26
|
return {
|
|
27
27
|
...s,
|
|
28
|
+
refetchEstimatedPrice: a.refetchEstimatedPrice,
|
|
28
29
|
validationError: a.validationError,
|
|
29
30
|
estimatedOpenPrice: a.prefills.estimatedOpenPrice,
|
|
31
|
+
estimatedOpenPriceTimestamp: i.estimatedOpenPriceTimestamp ?? a.estimatedOpenPriceTimestamp,
|
|
30
32
|
isReady: a.ready && s.isSuccess && !s.isFetching && !s.isPlaceholderData
|
|
31
33
|
};
|
|
32
34
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-prepare-instant-open-params.js","names":[],"sources":["../../src/instant-layer/use-prepare-instant-open-params.ts"],"sourcesContent":["\"use client\";\n\nimport {\n prepareInstantOpenParamsQueryOptions,\n type ConfigParameter,\n type PrepareInstantOpenParamsOptions,\n type PrepareInstantOpenParamsReturnType,\n} from \"@symmio/trading-core\";\nimport { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { normalizeSymmError } from \"../errors/normalize-symm-error\";\nimport type { SymmioRequestError } from \"../errors/symmio-request-error\";\nimport { useInstantOpenInputs } from \"./use-instant-open-inputs\";\n\n/**\n * Parameters for {@link usePrepareInstantOpenParams}: the same trade intent the\n * submit takes (`subAccountAddress`, `from`, `market`, `positionType`,\n * `initialMargin` **or** `fund`, optional `availableBalance` for automatic sizing,\n * `leverage`, optional `slippage` / pre-fetched\n * data, TanStack `query` overrides) plus an optional `config`.\n */\nexport type UsePrepareInstantOpenParamsParameters = PrepareInstantOpenParamsOptions & ConfigParameter;\n\n/**\n * Return type of {@link usePrepareInstantOpenParams}: the query result carrying\n * the prepared {@link PrepareInstantOpenParamsReturnType}, plus the dry-run estimate the\n * params were built with.\n */\nexport type UsePrepareInstantOpenParamsReturnType = UseQueryResult<\n PrepareInstantOpenParamsReturnType,\n SymmioRequestError\n> & {\n /**\n * The dry-run estimate the preview was built with (`null` when unavailable;\n * `undefined` while pending or on a non-lowcap solver). Forward it as\n * `estimatedOpenPrice` to the submit so its `margin.amount` — whose settlement leg tracks the estimate — matches this\n * preview bit-for-bit.\n */\n estimatedOpenPrice: string | null | undefined;\n /** Synchronous input error. Display before query.error; dependent queries stay disabled. */\n validationError: SymmioRequestError | undefined;\n /** True when all inputs and the current preparation have settled; gate submission on this. */\n isReady: boolean;\n};\n\n/**\n * Live-preview the exact {@link PrepareInstantOpenParamsReturnType} an instant-open submit\n * will sign — `order` (price + quantity), `lockedParam`, `margin.amount`, and\n * `solverFeeCaps` — by running `prepareInstantOpenParams` as a read.\n * `prepareInstantOpenParams` neither signs nor submits, so this is safe to run\n * live; drive a \"quote preview\" from it and what the user sees is bit-for-bit\n * what `sendQuote` receives, with no separate local recomputation to drift.\n *\n * Like {@link useInstantOpenFees}, it **pre-fetches every input through its own\n * cached queries** (market metadata, mark price, locked params, on-chain fee\n * rates, solver info, and the lowcap dry-run estimate) and passes them in as\n * prefills, so the query function is pure and does no per-render network. Previous data is kept\n * while inputs move, so a mark-price tick updates the numbers in place.\n *\n * For bit-for-bit parity on `margin.amount`, forward {@link\n * UsePrepareInstantOpenParamsReturnType.estimatedOpenPrice} to the submit call\n * (`useInstantOpenAuto` / `useInstantOpenWithTpSl`) as `estimatedOpenPrice`, so\n * both the preview and the send provision settlement at the same estimate. The\n * full-balance sizing decision and quantity also depend on that estimate.\n * Gate submission on `isReady` while inputs or the estimate are settling.\n * Display `validationError ?? error`; input errors are synchronous, including offline.\n * A disabled hook or empty input remains idle without input validation.\n *\n * @example\n * ```tsx\n * const preview = usePrepareInstantOpenParams({\n * subAccountAddress,\n * from: sessionKey,\n * market: { id: symbolId },\n * positionType,\n * initialMargin,\n * leverage,\n * slippage,\n * });\n * // preview.data?.order.quantity — the exact leveraged quantity (wei) the send signs\n * // submit: mutate({ …, estimatedOpenPrice: preview.estimatedOpenPrice })\n * ```\n */\nexport function usePrepareInstantOpenParams(\n parameters: UsePrepareInstantOpenParamsParameters,\n): UsePrepareInstantOpenParamsReturnType {\n const inputs = useInstantOpenInputs(parameters, \"prepare\", parameters.query?.enabled !== false);\n const options = prepareInstantOpenParamsQueryOptions(inputs.config, {\n ...parameters,\n ...inputs.prefills,\n query: {\n ...parameters.query,\n enabled: inputs.ready,\n placeholderData: (previous) => (inputs.validationError === undefined ? previous : undefined),\n },\n });\n const query = useQuery({\n ...options,\n queryFn: async () => {\n try {\n return await options.queryFn();\n } catch (err) {\n throw normalizeSymmError(err);\n }\n },\n }) as UseQueryResult<PrepareInstantOpenParamsReturnType, SymmioRequestError>;\n\n return {\n ...query,\n validationError: inputs.validationError,\n estimatedOpenPrice: inputs.prefills.estimatedOpenPrice,\n isReady: inputs.ready && query.isSuccess && !query.isFetching && !query.isPlaceholderData,\n };\n}\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"use-prepare-instant-open-params.js","names":[],"sources":["../../src/instant-layer/use-prepare-instant-open-params.ts"],"sourcesContent":["\"use client\";\n\nimport {\n prepareInstantOpenParamsQueryOptions,\n type ConfigParameter,\n type PrepareInstantOpenParamsOptions,\n type PrepareInstantOpenParamsReturnType,\n} from \"@symmio/trading-core\";\nimport { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { normalizeSymmError } from \"../errors/normalize-symm-error\";\nimport type { SymmioRequestError } from \"../errors/symmio-request-error\";\nimport type { UseEstimatedPriceReturnType } from \"../estimated-price/use-estimated-price\";\nimport { useInstantOpenInputs } from \"./use-instant-open-inputs\";\n\n/**\n * Parameters for {@link usePrepareInstantOpenParams}: the same trade intent the\n * submit takes (`subAccountAddress`, `from`, `market`, `positionType`,\n * `initialMargin` **or** `fund`, optional `availableBalance` for automatic sizing,\n * `leverage`, optional `slippage` / pre-fetched\n * data, TanStack `query` overrides) plus an optional `config`.\n */\nexport type UsePrepareInstantOpenParamsParameters = PrepareInstantOpenParamsOptions & ConfigParameter;\n\n/**\n * Return type of {@link usePrepareInstantOpenParams}: the query result carrying\n * the prepared {@link PrepareInstantOpenParamsReturnType}, plus the dry-run estimate the\n * params were built with.\n */\nexport type UsePrepareInstantOpenParamsReturnType = UseQueryResult<\n PrepareInstantOpenParamsReturnType,\n SymmioRequestError\n> & {\n /**\n * The dry-run estimate the preview was built with (`null` when unavailable;\n * `undefined` while pending or on a non-lowcap solver). Forward it as\n * `estimatedOpenPrice` to the submit so its `margin.amount` — whose settlement leg tracks the estimate — matches this\n * preview bit-for-bit.\n */\n estimatedOpenPrice: string | null | undefined;\n /** Arrival time of the fetched estimate in epoch milliseconds. The frontend decides when to refresh or expire it. */\n estimatedOpenPriceTimestamp: number | undefined;\n /**\n * Refetch the SDK-managed estimate on the frontend's schedule. Resolves when\n * the estimate request finishes; use isReady to await preparation. A supplied\n * estimatedOpenPrice still takes precedence over the fetched value.\n */\n refetchEstimatedPrice: UseEstimatedPriceReturnType[\"refetch\"];\n /** Synchronous input error. Display before query.error; dependent queries stay disabled. */\n validationError: SymmioRequestError | undefined;\n /** True when all inputs and the current preparation have settled; gate submission on this. */\n isReady: boolean;\n};\n\n/**\n * Live-preview the exact {@link PrepareInstantOpenParamsReturnType} an instant-open submit\n * will sign — `order` (price + quantity), `lockedParam`, `margin.amount`, and\n * `solverFeeCaps` — by running `prepareInstantOpenParams` as a read.\n * `prepareInstantOpenParams` neither signs nor submits, so this is safe to run\n * live; drive a \"quote preview\" from it and what the user sees is bit-for-bit\n * what `sendQuote` receives, with no separate local recomputation to drift.\n *\n * Like {@link useInstantOpenFees}, it **pre-fetches every input through its own\n * cached queries** (market metadata, mark price, locked params, on-chain fee\n * rates, solver info, and the lowcap dry-run estimate) and passes them in as\n * prefills, so the query function is pure and does no per-render network. Previous data is kept\n * while inputs move, so a mark-price tick updates the numbers in place.\n *\n * For bit-for-bit parity on `margin.amount`, forward {@link\n * UsePrepareInstantOpenParamsReturnType.estimatedOpenPrice} to the submit call\n * (`useInstantOpenAuto` / `useInstantOpenWithTpSl`) as `estimatedOpenPrice`, so\n * both the preview and the send provision settlement at the same estimate. The\n * full-balance sizing decision and quantity also depend on that estimate.\n * Gate submission on `isReady` while inputs or the estimate are settling.\n * Display `validationError ?? error`; input errors are synchronous, including offline.\n * A disabled hook or empty input remains idle without input validation.\n *\n * @example\n * ```tsx\n * const preview = usePrepareInstantOpenParams({\n * subAccountAddress,\n * from: sessionKey,\n * market: { id: symbolId },\n * positionType,\n * initialMargin,\n * leverage,\n * slippage,\n * });\n * // preview.data?.order.quantity — the exact leveraged quantity (wei) the send signs\n * // submit: mutate({ …, estimatedOpenPrice: preview.estimatedOpenPrice })\n * ```\n */\nexport function usePrepareInstantOpenParams(\n parameters: UsePrepareInstantOpenParamsParameters,\n): UsePrepareInstantOpenParamsReturnType {\n const inputs = useInstantOpenInputs(parameters, \"prepare\", parameters.query?.enabled !== false);\n const options = prepareInstantOpenParamsQueryOptions(inputs.config, {\n ...parameters,\n ...inputs.prefills,\n query: {\n ...parameters.query,\n enabled: inputs.ready,\n placeholderData: (previous) => (inputs.validationError === undefined ? previous : undefined),\n },\n });\n const query = useQuery({\n ...options,\n queryFn: async () => {\n try {\n return await options.queryFn();\n } catch (err) {\n throw normalizeSymmError(err);\n }\n },\n }) as UseQueryResult<PrepareInstantOpenParamsReturnType, SymmioRequestError>;\n\n return {\n ...query,\n refetchEstimatedPrice: inputs.refetchEstimatedPrice,\n validationError: inputs.validationError,\n estimatedOpenPrice: inputs.prefills.estimatedOpenPrice,\n estimatedOpenPriceTimestamp: parameters.estimatedOpenPriceTimestamp ?? inputs.estimatedOpenPriceTimestamp,\n isReady: inputs.ready && query.isSuccess && !query.isFetching && !query.isPlaceholderData,\n };\n}\n"],"mappings":";;;;;;AA2FA,SAAgB,EACd,GACuC;CACvC,IAAM,IAAS,EAAqB,GAAY,WAAW,EAAW,OAAO,YAAY,EAAK,GACxF,IAAU,EAAqC,EAAO,QAAQ;EAClE,GAAG;EACH,GAAG,EAAO;EACV,OAAO;GACL,GAAG,EAAW;GACd,SAAS,EAAO;GAChB,kBAAkB,MAAc,EAAO,oBAAoB,KAAA,IAAY,IAAW,KAAA;EACpF;CACF,CAAC,GACK,IAAQ,EAAS;EACrB,GAAG;EACH,SAAS,YAAY;GACnB,IAAI;IACF,OAAO,MAAM,EAAQ,QAAQ;GAC/B,SAAS,GAAK;IACZ,MAAM,EAAmB,CAAG;GAC9B;EACF;CACF,CAAC;CAED,OAAO;EACL,GAAG;EACH,uBAAuB,EAAO;EAC9B,iBAAiB,EAAO;EACxB,oBAAoB,EAAO,SAAS;EACpC,6BAA6B,EAAW,+BAA+B,EAAO;EAC9E,SAAS,EAAO,SAAS,EAAM,aAAa,CAAC,EAAM,cAAc,CAAC,EAAM;CAC1E;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@symmio/trading-react",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"description": "React adapter for the SYMMIO SDK. Hooks, providers, and React-bound ergonomics on top of @symmio/trading-core.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://github.com/SYMM-IO/Trading-SDK/tree/main/packages/trading-react#readme",
|
|
@@ -91,7 +91,7 @@
|
|
|
91
91
|
"@tanstack/react-query": "^5.100.0",
|
|
92
92
|
"decimal.js": "^10.4.3",
|
|
93
93
|
"zustand": "^5.0.0",
|
|
94
|
-
"@symmio/trading-core": "^3.
|
|
94
|
+
"@symmio/trading-core": "^3.4.0"
|
|
95
95
|
},
|
|
96
96
|
"peerDependencies": {
|
|
97
97
|
"react": "^19.0.0",
|