@symmio/trading-react 2.0.0 → 3.0.1-staging-20260926093035

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/account-layer/use-deallocate-and-initiate-withdraw.d.ts +1 -1
  2. package/dist/account-layer/use-deallocate-and-initiate-withdraw.js.map +1 -1
  3. package/dist/estimated-price/use-estimated-price.d.ts +6 -3
  4. package/dist/estimated-price/use-estimated-price.d.ts.map +1 -1
  5. package/dist/estimated-price/use-estimated-price.js +12 -9
  6. package/dist/estimated-price/use-estimated-price.js.map +1 -1
  7. package/dist/index.d.ts +9 -9
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +169 -165
  10. package/dist/instant-layer/get-instant-open-funding-error.d.ts +5 -0
  11. package/dist/instant-layer/get-instant-open-funding-error.d.ts.map +1 -0
  12. package/dist/instant-layer/get-instant-open-funding-error.js +15 -0
  13. package/dist/instant-layer/get-instant-open-funding-error.js.map +1 -0
  14. package/dist/instant-layer/index.d.ts +4 -0
  15. package/dist/instant-layer/index.d.ts.map +1 -1
  16. package/dist/instant-layer/index.js +15 -11
  17. package/dist/instant-layer/use-instant-close-fees.d.ts +46 -0
  18. package/dist/instant-layer/use-instant-close-fees.d.ts.map +1 -0
  19. package/dist/instant-layer/use-instant-close-fees.js +83 -0
  20. package/dist/instant-layer/use-instant-close-fees.js.map +1 -0
  21. package/dist/instant-layer/use-instant-open-auto.d.ts +5 -0
  22. package/dist/instant-layer/use-instant-open-auto.d.ts.map +1 -1
  23. package/dist/instant-layer/use-instant-open-auto.js.map +1 -1
  24. package/dist/instant-layer/use-instant-open-fees.d.ts +66 -0
  25. package/dist/instant-layer/use-instant-open-fees.d.ts.map +1 -0
  26. package/dist/instant-layer/use-instant-open-fees.js +35 -0
  27. package/dist/instant-layer/use-instant-open-fees.js.map +1 -0
  28. package/dist/instant-layer/use-instant-open-inputs.d.ts +35 -0
  29. package/dist/instant-layer/use-instant-open-inputs.d.ts.map +1 -0
  30. package/dist/instant-layer/use-instant-open-inputs.js +134 -0
  31. package/dist/instant-layer/use-instant-open-inputs.js.map +1 -0
  32. package/dist/instant-layer/use-instant-open-with-tpsl.d.ts +6 -0
  33. package/dist/instant-layer/use-instant-open-with-tpsl.d.ts.map +1 -1
  34. package/dist/instant-layer/use-instant-open-with-tpsl.js.map +1 -1
  35. package/dist/instant-layer/use-instant-trade-required-selectors.d.ts +25 -0
  36. package/dist/instant-layer/use-instant-trade-required-selectors.d.ts.map +1 -0
  37. package/dist/instant-layer/use-instant-trade-required-selectors.js +13 -0
  38. package/dist/instant-layer/use-instant-trade-required-selectors.js.map +1 -0
  39. package/dist/instant-layer/use-prepare-instant-open-params.d.ts +69 -0
  40. package/dist/instant-layer/use-prepare-instant-open-params.d.ts.map +1 -0
  41. package/dist/instant-layer/use-prepare-instant-open-params.js +36 -0
  42. package/dist/instant-layer/use-prepare-instant-open-params.js.map +1 -0
  43. package/dist/margin/use-available-instant-open-margin.d.ts +3 -2
  44. package/dist/margin/use-available-instant-open-margin.d.ts.map +1 -1
  45. package/dist/margin/use-available-instant-open-margin.js +4 -5
  46. package/dist/margin/use-available-instant-open-margin.js.map +1 -1
  47. package/dist/price-service/index.js +4 -4
  48. package/dist/provider/symmio-provider.d.ts +1 -1
  49. package/dist/provider/symmio-provider.js.map +1 -1
  50. package/dist/rasa-solver/index.d.ts +0 -1
  51. package/dist/rasa-solver/index.d.ts.map +1 -1
  52. package/dist/solvers/index.d.ts +1 -0
  53. package/dist/solvers/index.d.ts.map +1 -1
  54. package/dist/solvers/use-solver-info.d.ts +14 -0
  55. package/dist/solvers/use-solver-info.d.ts.map +1 -0
  56. package/dist/solvers/use-solver-info.js +27 -0
  57. package/dist/solvers/use-solver-info.js.map +1 -0
  58. package/dist/solvers/use-solver-revenue.d.ts +7 -5
  59. package/dist/solvers/use-solver-revenue.d.ts.map +1 -1
  60. package/dist/solvers/use-solver-revenue.js +1 -1
  61. package/dist/solvers/use-solver-revenue.js.map +1 -1
  62. package/dist/withdraw/use-initiate-withdraw.d.ts +1 -1
  63. package/dist/withdraw/use-initiate-withdraw.js.map +1 -1
  64. package/package.json +2 -2
  65. package/dist/rasa-solver/use-add-solver-whitelist.d.ts +0 -21
  66. package/dist/rasa-solver/use-add-solver-whitelist.d.ts.map +0 -1
  67. package/dist/rasa-solver/use-add-solver-whitelist.js +0 -27
  68. package/dist/rasa-solver/use-add-solver-whitelist.js.map +0 -1
@@ -0,0 +1,83 @@
1
+ "use client";
2
+ import { useSymmioChainId as e } from "../provider/use-symmio-chain-id.js";
3
+ import { useSymmioConfig as t } from "../provider/use-symmio-config.js";
4
+ import { normalizeSymmError as n } from "../errors/normalize-symm-error.js";
5
+ import { useFeeForUser as r } from "../fees/use-fee-for-user.js";
6
+ import { useMarkets as i } from "../markets/use-markets.js";
7
+ import { usePriceByName as a } from "../price-service/use-price-by-name.js";
8
+ import { useSolverInfo as o } from "../solvers/use-solver-info.js";
9
+ import { getInstantCloseFeesQueryOptions as s } from "@symmio/trading-core";
10
+ import { useQuery as c } from "@tanstack/react-query";
11
+ //#region src/instant-layer/use-instant-close-fees.ts
12
+ function l(l) {
13
+ let u = t(l), d = e(), f = l.chainId ?? d, { subAccountAddress: p, market: m, quantity: h, openedAt: g, now: _, solverId: v } = l, y = (l.query?.enabled ?? !0) && h.length > 0, b = u.getSolver({
14
+ chainId: f,
15
+ solverId: v
16
+ }).id === "enigma", x = i({
17
+ config: l.config,
18
+ chainId: f,
19
+ solverId: v,
20
+ query: {
21
+ enabled: y,
22
+ staleTime: 3e5
23
+ }
24
+ }).data?.find((e) => e.symbolId === m.id), S = m.name ?? x?.name, C = m.pricePrecision ?? x?.pricePrecision, w = m.quantityPrecision ?? x?.quantityPrecision, T = m.hedgerFeeOpen ?? x?.hedgerFeeOpen, E = m.hedgerFeeClose ?? x?.hedgerFeeClose, D = x?.kind === "enigma" ? x : void 0, O = m.hedgerFeeCloseEarlyRate ?? D?.hedgerFeeCloseEarlyRate ?? E, k = m.hedgerFeeCloseEarlyThreshold ?? D?.hedgerFeeCloseEarlyThreshold ?? 0, A = m.hedgerFeeCloseStandardThreshold ?? D?.hedgerFeeCloseStandardThreshold ?? 0, j = r({
25
+ config: l.config,
26
+ chainId: f,
27
+ user: p,
28
+ symbolId: BigInt(m.id),
29
+ query: {
30
+ enabled: y && l.feeRates === void 0,
31
+ staleTime: 3e5
32
+ }
33
+ }), M = l.feeRates ?? j.data, N = o({
34
+ config: l.config,
35
+ chainId: f,
36
+ solverId: v,
37
+ query: { enabled: y && b && l.solverInfo === void 0 }
38
+ }), P = b ? l.solverInfo ?? N.data ?? (N.isError ? {} : void 0) : void 0, F = !b || P !== void 0, I = a({
39
+ name: S,
40
+ solverId: v,
41
+ enabled: y && l.markPrice === void 0
42
+ }), L = l.markPrice ?? I.markPrice ?? void 0, R = y && S !== void 0 && C !== void 0 && w !== void 0 && M !== void 0 && L !== void 0 && (!b || T !== void 0 && E !== void 0) && F, z = s(u, {
43
+ subAccountAddress: p,
44
+ solverId: v,
45
+ chainId: f,
46
+ market: {
47
+ id: m.id,
48
+ name: S,
49
+ pricePrecision: C,
50
+ quantityPrecision: w,
51
+ hedgerFeeOpen: T,
52
+ hedgerFeeClose: E,
53
+ hedgerFeeCloseEarlyRate: O,
54
+ hedgerFeeCloseEarlyThreshold: k,
55
+ hedgerFeeCloseStandardThreshold: A
56
+ },
57
+ quantity: h,
58
+ openedAt: g,
59
+ now: _,
60
+ markPrice: L,
61
+ feeRates: M,
62
+ solverInfo: P,
63
+ query: {
64
+ ...l.query,
65
+ enabled: R,
66
+ placeholderData: (e) => e
67
+ }
68
+ });
69
+ return c({
70
+ ...z,
71
+ queryFn: async () => {
72
+ try {
73
+ return await z.queryFn();
74
+ } catch (e) {
75
+ throw n(e);
76
+ }
77
+ }
78
+ });
79
+ }
80
+ //#endregion
81
+ export { l as useInstantCloseFees };
82
+
83
+ //# sourceMappingURL=use-instant-close-fees.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-instant-close-fees.js","names":[],"sources":["../../src/instant-layer/use-instant-close-fees.ts"],"sourcesContent":["\"use client\";\n\nimport {\n getInstantCloseFeesQueryOptions,\n type ConfigParameter,\n type GetInstantCloseFeesOptions,\n type GetInstantCloseFeesReturnType,\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 { useFeeForUser } from \"../fees/use-fee-for-user\";\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\";\n\n/**\n * Parameters for {@link useInstantCloseFees}: the close intent\n * (`subAccountAddress`, `market`, `quantity`, `openedAt`, optional pre-fetched\n * data, TanStack `query` overrides) plus an optional `config`.\n */\nexport type UseInstantCloseFeesParameters = GetInstantCloseFeesOptions & ConfigParameter;\n\n/** Return type of {@link useInstantCloseFees}. */\nexport type UseInstantCloseFeesReturnType = UseQueryResult<GetInstantCloseFeesReturnType, SymmioRequestError>;\n\n/**\n * Preview every fee closing a position pays **right now** — the platform close\n * fee plus, on lowcap (Enigma), the holding-time solver close fee and the flat\n * static close leg. Read-only; nothing is signed. This is the close-flow\n * counterpart of `useInstantOpenFees`, which deliberately previews only the\n * open-side legs: the honest close cost exists only at close time, where the\n * notional and the decaying solver rate are real.\n *\n * Wraps `getInstantCloseFees`, 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`), on-chain\n * fee rates (`useFeeForUser`), and the solver's static fees (`useSolverInfo`)\n * are slow-moving and cached for minutes; the mark price rides the shared\n * price stream. Previous data is kept while inputs move, so a mark-price tick\n * updates the numbers in place.\n *\n * The holding time is stamped each time the query function runs, so a refetch\n * after the position ages re-prices the decaying solver close fee; pass `now`\n * for a deterministic preview. Narrow on `kind` to reach the lowcap-only legs\n * (`closeSolverFee`, `closeSolverFeeRate`, `holdingSeconds`,\n * `staticSolverFeeClose`).\n *\n * @example\n * ```tsx\n * const { data: fees } = useInstantCloseFees({\n * subAccountAddress: partyA,\n * market: { id: symbolId },\n * quantity: quantityToClose,\n * openedAt: position.createTimestamp,\n * });\n * // fees?.totalFee; fees?.kind === \"enigma\" && fees.closeSolverFee\n * ```\n */\nexport function useInstantCloseFees(parameters: UseInstantCloseFeesParameters): UseInstantCloseFeesReturnType {\n const config = useSymmioConfig(parameters);\n const contextChainId = useSymmioChainId();\n const chainId = parameters.chainId ?? contextChainId;\n const { subAccountAddress, market, quantity, openedAt, now, solverId } = parameters;\n const enabled = (parameters.query?.enabled ?? true) && quantity.length > 0;\n\n /** The solver close-fee schedule and the static leg exist only on lowcap (Enigma) solvers. */\n const isLowcap = config.getSolver({ chainId, solverId }).id === \"enigma\";\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 // Time-decaying close-fee rates ride the same `useMarkets` read — they are\n // Enigma-only 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 // 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 // Static close fee from the solver's `/info` config — lowcap only. Fail-soft:\n // an unreachable `/info` prices the static leg at \"0\" instead of blocking the\n // preview (mirrors the action's own resolver).\n const solverInfoQuery = useSolverInfo({\n config: parameters.config,\n chainId,\n solverId,\n query: { enabled: enabled && isLowcap && parameters.solverInfo === undefined },\n });\n const solverInfo = !isLowcap\n ? undefined\n : (parameters.solverInfo ?? solverInfoQuery.data ?? (solverInfoQuery.isError ? {} : undefined));\n const solverInfoSettled = !isLowcap || solverInfo !== undefined;\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 // Every prefill present → the query function is pure math, zero fetches.\n const ready =\n enabled &&\n marketName !== undefined &&\n pricePrecision !== undefined &&\n quantityPrecision !== undefined &&\n feeRates !== undefined &&\n markPrice !== undefined &&\n (!isLowcap || (hedgerFeeOpen !== undefined && hedgerFeeClose !== undefined)) &&\n solverInfoSettled;\n\n const options = getInstantCloseFeesQueryOptions(config, {\n subAccountAddress,\n solverId,\n chainId,\n market: {\n id: market.id,\n name: marketName,\n pricePrecision,\n quantityPrecision,\n hedgerFeeOpen,\n hedgerFeeClose,\n hedgerFeeCloseEarlyRate,\n hedgerFeeCloseEarlyThreshold,\n hedgerFeeCloseStandardThreshold,\n },\n quantity,\n openedAt,\n now,\n markPrice,\n feeRates,\n solverInfo,\n query: {\n ...parameters.query,\n enabled: ready,\n // The mark price ticks often; keep showing the previous numbers while\n // the pure recompute runs instead of flashing a loader.\n placeholderData: (previous: GetInstantCloseFeesReturnType | undefined) => previous,\n },\n });\n\n return useQuery({\n ...options,\n queryFn: async () => {\n try {\n return await options.queryFn();\n } catch (err) {\n throw normalizeSymmError(err);\n }\n },\n }) as UseInstantCloseFeesReturnType;\n}\n"],"mappings":";;;;;;;;;;;AA6DA,SAAgB,EAAoB,GAA0E;CAC5G,IAAM,IAAS,EAAgB,CAAU,GACnC,IAAiB,EAAiB,GAClC,IAAU,EAAW,WAAW,GAChC,EAAE,sBAAmB,WAAQ,aAAU,aAAU,QAAK,gBAAa,GACnE,KAAW,EAAW,OAAO,WAAW,OAAS,EAAS,SAAS,GAGnE,IAAW,EAAO,UAAU;EAAE;EAAS;CAAS,CAAC,EAAE,OAAO,UAS1D,IANe,EAAW;EAC9B,QAAQ,EAAW;EACnB;EACA;EACA,OAAO;GAAE;GAAS,WAAW;EAAQ;CACvC,CACuB,EAAa,MAAM,MAAM,MAAU,EAAM,aAAa,EAAO,EAAE,GAChF,IAAa,EAAO,QAAQ,GAAgB,MAC5C,IAAiB,EAAO,kBAAkB,GAAgB,gBAC1D,IAAoB,EAAO,qBAAqB,GAAgB,mBAChE,IAAgB,EAAO,iBAAiB,GAAgB,eACxD,IAAiB,EAAO,kBAAkB,GAAgB,gBAI1D,IAAuB,GAAgB,SAAS,WAAW,IAAiB,KAAA,GAC5E,IACJ,EAAO,2BAA2B,GAAsB,2BAA2B,GAC/E,IACJ,EAAO,gCAAgC,GAAsB,gCAAgC,GACzF,IACJ,EAAO,mCAAmC,GAAsB,mCAAmC,GAG/F,IAAW,EAAc;EAC7B,QAAQ,EAAW;EACnB;EACA,MAAM;EACN,UAAU,OAAO,EAAO,EAAE;EAC1B,OAAO;GAAE,SAAS,KAAW,EAAW,aAAa,KAAA;GAAW,WAAW;EAAQ;CACrF,CAAC,GACK,IAAW,EAAW,YAAY,EAAS,MAK3C,IAAkB,EAAc;EACpC,QAAQ,EAAW;EACnB;EACA;EACA,OAAO,EAAE,SAAS,KAAW,KAAY,EAAW,eAAe,KAAA,EAAU;CAC/E,CAAC,GACK,IAAc,IAEf,EAAW,cAAc,EAAgB,SAAS,EAAgB,UAAU,CAAC,IAAI,KAAA,KADlF,KAAA,GAEE,IAAoB,CAAC,KAAY,MAAe,KAAA,GAGhD,IAAa,EAAe;EAChC,MAAM;EACN;EACA,SAAS,KAAW,EAAW,cAAc,KAAA;CAC/C,CAAC,GACK,IAAY,EAAW,aAAa,EAAW,aAAa,KAAA,GAG5D,IACJ,KACA,MAAe,KAAA,KACf,MAAmB,KAAA,KACnB,MAAsB,KAAA,KACtB,MAAa,KAAA,KACb,MAAc,KAAA,MACb,CAAC,KAAa,MAAkB,KAAA,KAAa,MAAmB,KAAA,MACjE,GAEI,IAAU,EAAgC,GAAQ;EACtD;EACA;EACA;EACA,QAAQ;GACN,IAAI,EAAO;GACX,MAAM;GACN;GACA;GACA;GACA;GACA;GACA;GACA;EACF;EACA;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;GACL,GAAG,EAAW;GACd,SAAS;GAGT,kBAAkB,MAAwD;EAC5E;CACF,CAAC;CAED,OAAO,EAAS;EACd,GAAG;EACH,SAAS,YAAY;GACnB,IAAI;IACF,OAAO,MAAM,EAAQ,QAAQ;GAC/B,SAAS,GAAK;IACZ,MAAM,EAAmB,CAAG;GAC9B;EACF;CACF,CAAC;AACH"}
@@ -17,6 +17,11 @@ export type UseInstantOpenAutoReturnType = UseMutationResult<InstantOpenReturnTy
17
17
  * submit — use {@link useInstantOpen} after calling
18
18
  * `prepareInstantOpenParams(config, …)` directly.
19
19
  *
20
+ * Funding is a one-of on the variables: a typed `initialMargin`, or
21
+ * `fund: { mode: "full-balance", balance }` (lowcap only) to deploy the whole
22
+ * balance into the position's VA with the quantity sized down to fit it —
23
+ * see `FullBalanceFunding` in `@symmio/trading-core`.
24
+ *
20
25
  * @example
21
26
  * ```tsx
22
27
  * const { mutateAsync } = useInstantOpenAuto();
@@ -1 +1 @@
1
- {"version":3,"file":"use-instant-open-auto.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-instant-open-auto.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,4BAA4B,EAClC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAA+B,KAAK,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE5F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAKzE;;GAEG;AACH,MAAM,MAAM,4BAA4B,GAAG,eAAe,CAAC;AAE3D,iDAAiD;AACjD,MAAM,MAAM,4BAA4B,GAAG,iBAAiB,CAC1D,qBAAqB,EACrB,kBAAkB,EAClB,4BAA4B,CAC7B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,GAAE,4BAAiC,GAAG,4BAA4B,CA2B9G"}
1
+ {"version":3,"file":"use-instant-open-auto.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-instant-open-auto.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,4BAA4B,EAClC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAA+B,KAAK,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE5F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAKzE;;GAEG;AACH,MAAM,MAAM,4BAA4B,GAAG,eAAe,CAAC;AAE3D,iDAAiD;AACjD,MAAM,MAAM,4BAA4B,GAAG,iBAAiB,CAC1D,qBAAqB,EACrB,kBAAkB,EAClB,4BAA4B,CAC7B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,GAAE,4BAAiC,GAAG,4BAA4B,CA2B9G"}
@@ -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 * @example\n * ```tsx\n * const { mutateAsync } = useInstantOpenAuto();\n * await mutateAsync({\n * walletAddress, sessionKeyAddress, signTypedData,\n * marketId: 1, positionType: \"LONG\",\n * userInput: \"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":";;;;;;;;;AAgDA,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
+ {"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 * walletAddress, sessionKeyAddress, signTypedData,\n * marketId: 1, positionType: \"LONG\",\n * userInput: \"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"}
@@ -0,0 +1,66 @@
1
+ import { ConfigParameter, GetInstantOpenFeesOptions, GetInstantOpenFeesReturnType } from '@symmio/trading-core';
2
+ import { UseQueryResult } from '@tanstack/react-query';
3
+ import { SymmioRequestError } from '../errors/symmio-request-error.js';
4
+ /**
5
+ * Parameters for {@link useInstantOpenFees}: the trade intent
6
+ * (`subAccountAddress`, `market`, `positionType`, `initialMargin` **or**
7
+ * `fund` for a full-balance preview, `leverage`, optional `slippage` /
8
+ * pre-fetched data, TanStack `query` overrides) plus an optional `config`.
9
+ */
10
+ export type UseInstantOpenFeesParameters = GetInstantOpenFeesOptions & ConfigParameter;
11
+ /** Return type of {@link useInstantOpenFees}. */
12
+ export type UseInstantOpenFeesReturnType = UseQueryResult<GetInstantOpenFeesReturnType, SymmioRequestError> & {
13
+ /** Synchronous input error. Display before query.error; dependent queries stay disabled. */
14
+ validationError: SymmioRequestError | undefined;
15
+ /** True when all inputs and the current fee preview have settled successfully. */
16
+ isReady: boolean;
17
+ };
18
+ /**
19
+ * Preview every fee a new instant-open quote pays — separated by leg plus the
20
+ * total — before the user submits. Read-only; nothing is signed.
21
+ *
22
+ * Wraps `getInstantOpenFees`, but **pre-fetches every input through its own
23
+ * cached queries and passes them in as prefills**, so the query function is
24
+ * pure math with zero network hops: market metadata (`useMarkets`) and
25
+ * on-chain fee rates (`useFeeForUser`) and solver info are cached for minutes.
26
+ * The mark price rides the shared price stream; the lowcap dry-run estimate
27
+ * uses `useEstimatedPrice` (debounced internally). Previous data is
28
+ * kept while inputs move, so a mark-price tick updates the numbers in place —
29
+ * it never resets the result to a loading state.
30
+ *
31
+ * The result is a `kind`-discriminated union of the **open-side** legs: both
32
+ * kinds carry `platformOpenFee`, the sized `quantity`, and `totalFee`; an
33
+ * `"enigma"` (lowcap) result adds `openSolverFee`, `staticSolverFeeOpen`, and
34
+ * `expectedSettlementLoss`. Close fees are charged at close from the position
35
+ * and are deliberately not part of this preview — price them in the close flow
36
+ * with `useInstantCloseFees`, where the notional and holding time are real.
37
+ * `totalFee` includes the settlement provision by default; pass
38
+ * `includeSettlementInTotalFee: false` to sum the fee legs only.
39
+ *
40
+ * With `fund` (`FullBalanceFunding`) instead of `initialMargin`, the
41
+ * preview runs the same probe-and-rescale sizing as the open, so the legs and
42
+ * `quantity` equal what a full-balance open will actually charge and submit —
43
+ * the extra inputs it needs (locked-param percents, market quote constraints)
44
+ * are prefetched here through the same cached queries.
45
+ *
46
+ * With `initialMargin` and `availableBalance`, core automatically uses full-balance
47
+ * sizing when required funding exceeds the raw balance. `data.fundingMode` reports
48
+ * the effective choice; pass the same inputs to preparation and submission.
49
+ * Display `validationError ?? error` and check `isReady` before using the fees
50
+ * for the current input. Input errors are synchronous, including offline.
51
+ * A disabled hook or empty input remains idle without input validation.
52
+ *
53
+ * @example
54
+ * ```tsx
55
+ * const { data: fees } = useInstantOpenFees({
56
+ * subAccountAddress,
57
+ * market: { id: symbolId },
58
+ * positionType,
59
+ * initialMargin,
60
+ * leverage,
61
+ * });
62
+ * // fees?.totalFee; fees?.kind === "enigma" && fees.expectedSettlementLoss
63
+ * ```
64
+ */
65
+ export declare function useInstantOpenFees(parameters: UseInstantOpenFeesParameters): UseInstantOpenFeesReturnType;
66
+ //# sourceMappingURL=use-instant-open-fees.d.ts.map
@@ -0,0 +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;AAGzE;;;;;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,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,CA2BzG"}
@@ -0,0 +1,35 @@
1
+ "use client";
2
+ import { normalizeSymmError as e } from "../errors/normalize-symm-error.js";
3
+ import { useInstantOpenInputs as t } from "./use-instant-open-inputs.js";
4
+ import { getInstantOpenFeesQueryOptions as n } from "@symmio/trading-core";
5
+ import { useQuery as r } from "@tanstack/react-query";
6
+ //#region src/instant-layer/use-instant-open-fees.ts
7
+ function i(i) {
8
+ let a = t(i, "fees", i.query?.enabled !== !1), o = n(a.config, {
9
+ ...i,
10
+ ...a.prefills,
11
+ query: {
12
+ ...i.query,
13
+ enabled: a.ready,
14
+ placeholderData: (e) => a.validationError === void 0 ? e : void 0
15
+ }
16
+ }), s = r({
17
+ ...o,
18
+ queryFn: async () => {
19
+ try {
20
+ return await o.queryFn();
21
+ } catch (t) {
22
+ throw e(t);
23
+ }
24
+ }
25
+ });
26
+ return {
27
+ ...s,
28
+ validationError: a.validationError,
29
+ isReady: a.ready && s.isSuccess && !s.isFetching && !s.isPlaceholderData
30
+ };
31
+ }
32
+ //#endregion
33
+ export { i as useInstantOpenFees };
34
+
35
+ //# sourceMappingURL=use-instant-open-fees.js.map
@@ -0,0 +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":";;;;;;AA4EA,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,iBAAiB,EAAO;EACxB,SAAS,EAAO,SAAS,EAAM,aAAa,CAAC,EAAM,cAAc,CAAC,EAAM;CAC1E;AACF"}
@@ -0,0 +1,35 @@
1
+ import { ConfigParameter, GetInstantOpenFeesParameters } from '@symmio/trading-core';
2
+ /** Shared input orchestration for preparation and fee previews; calculations stay in core. */
3
+ export declare function useInstantOpenInputs(parameters: GetInstantOpenFeesParameters & ConfigParameter, purpose: "prepare" | "fees", queryEnabled?: boolean): {
4
+ config: import('@symmio/trading-core').Config;
5
+ validationError: import('../index.js').SymmioRequestError | undefined;
6
+ ready: boolean;
7
+ prefills: {
8
+ chainId: number;
9
+ market: {
10
+ id: number;
11
+ name: string | undefined;
12
+ pricePrecision: number | undefined;
13
+ quantityPrecision: number | undefined;
14
+ minOpenSolverFeeCap: string | undefined;
15
+ minCloseSolverFeeCap: string | undefined;
16
+ hedgerFeeOpen: string | undefined;
17
+ hedgerFeeClose: string | undefined;
18
+ hedgerFeeCloseEarlyRate: string | undefined;
19
+ hedgerFeeCloseEarlyThreshold: number;
20
+ hedgerFeeCloseStandardThreshold: number;
21
+ minAcceptablePortionLf: string | undefined;
22
+ minAcceptableQuoteValue: string | undefined;
23
+ maxNotionalValue: number | undefined;
24
+ minNotionalValue: string | undefined;
25
+ maxQuantity: string | undefined;
26
+ lotSize: string | undefined;
27
+ };
28
+ markPrice: string | undefined;
29
+ feeRates: import('@symmio/trading-core').FeeForUser | undefined;
30
+ lockedParamPercent: import('@symmio/trading-core').SolverLockedParams | undefined;
31
+ solverInfo: import('@symmio/trading-core').EnigmaSolverInfo | undefined;
32
+ estimatedOpenPrice: string | null | undefined;
33
+ };
34
+ };
35
+ //# sourceMappingURL=use-instant-open-inputs.d.ts.map
@@ -0,0 +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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6NpB"}
@@ -0,0 +1,134 @@
1
+ "use client";
2
+ import { useSymmioChainId as e } from "../provider/use-symmio-chain-id.js";
3
+ import { useSymmioConfig as ee } from "../provider/use-symmio-config.js";
4
+ import { useFeeForUser as te } from "../fees/use-fee-for-user.js";
5
+ import { useMarkets as ne } from "../markets/use-markets.js";
6
+ import { usePriceByName as re } from "../price-service/use-price-by-name.js";
7
+ import { useSolverInfo as ie } from "../solvers/use-solver-info.js";
8
+ import { useEstimatedPrice as t } from "../estimated-price/use-estimated-price.js";
9
+ import { useLockedParams as n } from "../locked-params/use-locked-params.js";
10
+ import { getInstantOpenFundingError as r } from "./get-instant-open-funding-error.js";
11
+ import { PositionType as i, calculateTradeParams as a } from "@symmio/trading-core";
12
+ import { useMemo as ae } from "react";
13
+ //#region src/instant-layer/use-instant-open-inputs.ts
14
+ function o(o, s, c = !0) {
15
+ let l = ee(o), u = e(), d = o.chainId ?? u, { subAccountAddress: f, market: p, positionType: m, initialMargin: oe, fund: h, leverage: g, solverId: _ } = o, v = h !== void 0, y = v || o.availableBalance !== void 0, b = s === "prepare" || y, se = s === "prepare" && l.getChainConfig(d).contractsVersion === "0.8.6", x = v ? h.balance : oe ?? "", S = c && x.length > 0, C = l.getSolver({
16
+ chainId: d,
17
+ solverId: _
18
+ }).id === "enigma", w = S ? r({
19
+ ...o,
20
+ isLowcap: C
21
+ }) : void 0, T = S && w === void 0, E = ne({
22
+ config: o.config,
23
+ chainId: d,
24
+ solverId: _,
25
+ query: {
26
+ enabled: T,
27
+ staleTime: 3e5
28
+ }
29
+ }).data?.find((e) => e.symbolId === p.id), D = p.name ?? E?.name, O = p.pricePrecision ?? E?.pricePrecision, k = p.quantityPrecision ?? E?.quantityPrecision, A = p.hedgerFeeOpen ?? E?.hedgerFeeOpen, j = p.hedgerFeeClose ?? E?.hedgerFeeClose, M = p.minOpenSolverFeeCap ?? (E ? E.kind === "enigma" ? E.minOpenSolverFeeCap : "0" : void 0), N = p.minCloseSolverFeeCap ?? (E ? E.kind === "enigma" ? E.minCloseSolverFeeCap : "0" : void 0), ce = !se || M !== void 0 && N !== void 0, P = E?.kind === "enigma" ? E : void 0, le = p.hedgerFeeCloseEarlyRate ?? P?.hedgerFeeCloseEarlyRate ?? j, ue = p.hedgerFeeCloseEarlyThreshold ?? P?.hedgerFeeCloseEarlyThreshold ?? 0, F = p.hedgerFeeCloseStandardThreshold ?? P?.hedgerFeeCloseStandardThreshold ?? 0, I = p.minAcceptablePortionLf ?? E?.minAcceptablePortionLf, L = p.minAcceptableQuoteValue ?? E?.minAcceptableQuoteValue, R = p.maxNotionalValue ?? E?.maxNotionalValue, z = p.minNotionalValue ?? E?.minNotionalValue, B = p.maxQuantity ?? E?.maxQuantity, V = p.lotSize ?? E?.lotSize, H = !y || I !== void 0 && L !== void 0 && R !== void 0 && z !== void 0 && B !== void 0 && V !== void 0, U = o.lockedParamPercent?.cva !== void 0 && o.lockedParamPercent.lf !== void 0 && o.lockedParamPercent.partyAmm !== void 0 && o.lockedParamPercent.partyBmm !== void 0, W = n({
30
+ config: o.config,
31
+ chainId: d,
32
+ solverId: _,
33
+ symbol: D ?? "",
34
+ leverage: g,
35
+ query: {
36
+ enabled: T && b && !U && D !== void 0,
37
+ staleTime: 3e5
38
+ }
39
+ }), G = U ? o.lockedParamPercent : W.data ? {
40
+ cva: W.data.cva ?? "0",
41
+ lf: W.data.lf ?? "0",
42
+ partyAmm: W.data.partyAmm ?? "0",
43
+ partyBmm: W.data.partyBmm ?? "0"
44
+ } : void 0, de = !b || G !== void 0, K = ie({
45
+ config: o.config,
46
+ chainId: d,
47
+ solverId: _,
48
+ query: {
49
+ enabled: T && C && o.solverInfo === void 0,
50
+ staleTime: 3e5,
51
+ retry: !1
52
+ }
53
+ }), q = o.solverInfo ?? K.data ?? (K.isError ? {} : void 0), fe = !C || q !== void 0, pe = te({
54
+ config: o.config,
55
+ chainId: d,
56
+ user: f,
57
+ symbolId: BigInt(p.id),
58
+ query: {
59
+ enabled: T && o.feeRates === void 0,
60
+ staleTime: 3e5
61
+ }
62
+ }), J = o.feeRates ?? pe.data, me = re({
63
+ name: D,
64
+ solverId: _,
65
+ enabled: T && o.markPrice === void 0
66
+ }), Y = o.markPrice ?? me.markPrice ?? void 0, X = ae(() => !T || !C || Y === void 0 || O === void 0 || k === void 0 ? "" : a({
67
+ markPrice: Y,
68
+ slippage: 0,
69
+ positionType: m,
70
+ userInput: x,
71
+ inputField: "PRICE",
72
+ leverage: g,
73
+ pricePrecision: O,
74
+ quantityPrecision: k
75
+ })?.quantity ?? "", [
76
+ T,
77
+ C,
78
+ Y,
79
+ O,
80
+ k,
81
+ m,
82
+ x,
83
+ g
84
+ ]), he = Y === void 0 ? "" : String(Number(Y) * (m === i.SHORT ? .5 : 1.5)), Z = t({
85
+ config: o.config,
86
+ chainId: d,
87
+ solverId: _,
88
+ symbolId: p.id,
89
+ quantity: X,
90
+ positionType: m,
91
+ entry: "open",
92
+ price: he,
93
+ query: {
94
+ enabled: T && C && o.estimatedOpenPrice === void 0 && X.length > 0,
95
+ staleTime: 3e4
96
+ }
97
+ }), ge = C && o.estimatedOpenPrice === void 0 && (Z.isDebouncing || Z.isFetching), Q = !C || o.estimatedOpenPrice !== void 0 || !ge && (Z.isFetched || Z.isError), $ = o.estimatedOpenPrice === void 0 ? Z.data?.estimatedPrice : o.estimatedOpenPrice, _e = !C || !Q ? void 0 : $ && $ !== "0" ? $ : null;
98
+ return {
99
+ config: l,
100
+ validationError: w,
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
+ prefills: {
103
+ chainId: d,
104
+ market: {
105
+ id: p.id,
106
+ name: D,
107
+ pricePrecision: O,
108
+ quantityPrecision: k,
109
+ minOpenSolverFeeCap: M,
110
+ minCloseSolverFeeCap: N,
111
+ hedgerFeeOpen: A,
112
+ hedgerFeeClose: j,
113
+ hedgerFeeCloseEarlyRate: le,
114
+ hedgerFeeCloseEarlyThreshold: ue,
115
+ hedgerFeeCloseStandardThreshold: F,
116
+ minAcceptablePortionLf: I,
117
+ minAcceptableQuoteValue: L,
118
+ maxNotionalValue: R,
119
+ minNotionalValue: z,
120
+ maxQuantity: B,
121
+ lotSize: V
122
+ },
123
+ markPrice: Y,
124
+ feeRates: J,
125
+ lockedParamPercent: G,
126
+ solverInfo: q,
127
+ estimatedOpenPrice: _e
128
+ }
129
+ };
130
+ }
131
+ //#endregion
132
+ export { o as useInstantOpenInputs };
133
+
134
+ //# sourceMappingURL=use-instant-open-inputs.js.map
@@ -0,0 +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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"}
@@ -39,6 +39,12 @@ export type UseInstantOpenWithTpSlReturnType = UseMutationResult<UseInstantOpenW
39
39
  * `tempQuoteId`. Web layer just wires inputs; all mutation logic (both legs +
40
40
  * cache invalidation + confirming-slot write) lives in the SDK.
41
41
  *
42
+ * Funding follows the `PrepareInstantOpenParameters` one-of: a typed
43
+ * `initialMargin`, or `fund: { mode: "full-balance", balance }` (lowcap only)
44
+ * to deploy the whole balance. In full-balance mode the submitted quantity is
45
+ * the SDK-rescaled one — take the TP/SL `quantity` from `useInstantOpenFees`
46
+ * (its `quantity` field) rather than re-deriving it from the typed margin.
47
+ *
42
48
  * @example
43
49
  * ```tsx
44
50
  * const open = useInstantOpenWithTpSl();
@@ -1 +1 @@
1
- {"version":3,"file":"use-instant-open-with-tpsl.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-instant-open-with-tpsl.ts"],"names":[],"mappings":"AAEA,OAAO,EAIL,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,4BAA4B,EACjC,KAAK,sBAAsB,EAC3B,KAAK,sBAAsB,EAC5B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAA+B,KAAK,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAG5F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAMzE;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,+BAAgC,SAAQ,4BAA4B;IACnF,IAAI,CAAC,EAAE,IAAI,CAAC,sBAAsB,EAAE,SAAS,GAAG,SAAS,CAAC,CAAC;CAC5D;AAED,sEAAsE;AACtE,MAAM,WAAW,0BAA0B;IACzC,WAAW,EAAE,qBAAqB,CAAC;IACnC,0DAA0D;IAC1D,IAAI,CAAC,EAAE,sBAAsB,CAAC;IAC9B,mFAAmF;IACnF,SAAS,CAAC,EAAE,kBAAkB,CAAC;CAChC;AAED,kDAAkD;AAClD,MAAM,MAAM,2BAA2B,GAAG,MAAM,GAAG,SAAS,GAAG,gBAAgB,GAAG,SAAS,GAAG,OAAO,CAAC;AAEtG,qDAAqD;AACrD,MAAM,MAAM,gCAAgC,GAAG,eAAe,CAAC;AAE/D,qDAAqD;AACrD,MAAM,MAAM,gCAAgC,GAAG,iBAAiB,CAC9D,0BAA0B,EAC1B,kBAAkB,EAClB,+BAA+B,CAChC,GAAG;IACF,+DAA+D;IAC/D,KAAK,EAAE,2BAA2B,CAAC;CACpC,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,sBAAsB,CACpC,UAAU,GAAE,gCAAqC,GAChD,gCAAgC,CAqFlC"}
1
+ {"version":3,"file":"use-instant-open-with-tpsl.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-instant-open-with-tpsl.ts"],"names":[],"mappings":"AAEA,OAAO,EAIL,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,4BAA4B,EACjC,KAAK,sBAAsB,EAC3B,KAAK,sBAAsB,EAC5B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAA+B,KAAK,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAG5F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAMzE;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,+BAAgC,SAAQ,4BAA4B;IACnF,IAAI,CAAC,EAAE,IAAI,CAAC,sBAAsB,EAAE,SAAS,GAAG,SAAS,CAAC,CAAC;CAC5D;AAED,sEAAsE;AACtE,MAAM,WAAW,0BAA0B;IACzC,WAAW,EAAE,qBAAqB,CAAC;IACnC,0DAA0D;IAC1D,IAAI,CAAC,EAAE,sBAAsB,CAAC;IAC9B,mFAAmF;IACnF,SAAS,CAAC,EAAE,kBAAkB,CAAC;CAChC;AAED,kDAAkD;AAClD,MAAM,MAAM,2BAA2B,GAAG,MAAM,GAAG,SAAS,GAAG,gBAAgB,GAAG,SAAS,GAAG,OAAO,CAAC;AAEtG,qDAAqD;AACrD,MAAM,MAAM,gCAAgC,GAAG,eAAe,CAAC;AAE/D,qDAAqD;AACrD,MAAM,MAAM,gCAAgC,GAAG,iBAAiB,CAC9D,0BAA0B,EAC1B,kBAAkB,EAClB,+BAA+B,CAChC,GAAG;IACF,+DAA+D;IAC/D,KAAK,EAAE,2BAA2B,CAAC;CACpC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,sBAAsB,CACpC,UAAU,GAAE,gCAAqC,GAChD,gCAAgC,CAqFlC"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-instant-open-with-tpsl.js","names":[],"sources":["../../src/instant-layer/use-instant-open-with-tpsl.ts"],"sourcesContent":["\"use client\";\n\nimport {\n getInstantOpensQueryKey,\n instantOpenAutoMutationOptions,\n setQuoteTpSlMutationOptions,\n type ConfigParameter,\n type InstantOpenReturnType,\n type PrepareInstantOpenParameters,\n type SetQuoteTpSlParameters,\n type SetQuoteTpSlReturnType,\n} from \"@symmio/trading-core\";\nimport { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useState } from \"react\";\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 { useTpSlStore } from \"../tpsl/tpsl-store\";\nimport { invalidateAccountBalances, predicateMatch } from \"../utils\";\n\n/**\n * Parameters for {@link useInstantOpenWithTpSl}: the standard instant-open\n * inputs, plus an optional `tpsl` block that mirrors {@link SetQuoteTpSlParameters}\n * minus `quoteId` (derived from the hedger response) and `chainId` (defaulted).\n *\n * When `tpsl` is omitted (or both `tp` and `sl` are empty), the hook behaves\n * exactly like {@link useInstantOpenAuto}. When present, the SDK dispatches\n * `setQuoteTpSl` immediately after the hedger returns a `tempQuoteId` — the\n * message is signed against the (predicted) VA the caller supplies, so no\n * on-chain reconciliation wait is needed. Confirmation still comes through the\n * TP/SL WebSocket picked up by {@link useQuoteTpSl}.\n */\nexport interface UseInstantOpenWithTpSlVariables extends PrepareInstantOpenParameters {\n tpsl?: Omit<SetQuoteTpSlParameters, \"quoteId\" | \"chainId\">;\n}\n\n/** Aggregated success payload from {@link useInstantOpenWithTpSl}. */\nexport interface UseInstantOpenWithTpSlData {\n instantOpen: InstantOpenReturnType;\n /** Set when the TP/SL leg was attempted and succeeded. */\n tpsl?: SetQuoteTpSlReturnType;\n /** Set when the TP/SL leg was attempted and failed — instant open still landed. */\n tpslError?: SymmioRequestError;\n}\n\n/** Which leg the orchestrator is currently on. */\nexport type UseInstantOpenWithTpSlPhase = \"idle\" | \"opening\" | \"attaching-tpsl\" | \"success\" | \"error\";\n\n/** Parameters for {@link useInstantOpenWithTpSl}. */\nexport type UseInstantOpenWithTpSlParameters = ConfigParameter;\n\n/** Return type of {@link useInstantOpenWithTpSl}. */\nexport type UseInstantOpenWithTpSlReturnType = UseMutationResult<\n UseInstantOpenWithTpSlData,\n SymmioRequestError,\n UseInstantOpenWithTpSlVariables\n> & {\n /** Current orchestration phase. Handy for phased status UI. */\n phase: UseInstantOpenWithTpSlPhase;\n};\n\n/**\n * One-shot orchestrator: post an instant open and — if the caller pre-filled\n * a TP/SL block — immediately submit `setQuoteTpSl` using the hedger's returned\n * `tempQuoteId`. Web layer just wires inputs; all mutation logic (both legs +\n * cache invalidation + confirming-slot write) lives in the SDK.\n *\n * @example\n * ```tsx\n * const open = useInstantOpenWithTpSl();\n * open.mutate({\n * ...instantOpenParams,\n * tpsl: hasTpOrSl\n * ? { from: sessionKey, virtualAccount: predictedVa, subAccount,\n * symbolId, positionType, quantity, pricePrecision, tp, sl }\n * : undefined,\n * });\n * ```\n */\nexport function useInstantOpenWithTpSl(\n parameters: UseInstantOpenWithTpSlParameters = {},\n): UseInstantOpenWithTpSlReturnType {\n const config = useSymmioConfig(parameters);\n const chainId = useSymmioChainId();\n const queryClient = useQueryClient();\n const openBase = instantOpenAutoMutationOptions(config);\n const tpslBase = setQuoteTpSlMutationOptions(config);\n const markConfirming = useTpSlStore((state) => state.markConfirming);\n\n const [phase, setPhase] = useState<UseInstantOpenWithTpSlPhase>(\"idle\");\n\n const mutation = useMutation<UseInstantOpenWithTpSlData, SymmioRequestError, UseInstantOpenWithTpSlVariables>({\n mutationKey: [\"useInstantOpenWithTpSl\"] as const,\n mutationFn: async (variables) => {\n const resolvedChainId = variables.chainId ?? chainId;\n setPhase(\"opening\");\n let openResult: InstantOpenReturnType;\n try {\n openResult = await openBase.mutationFn({ ...variables, chainId: resolvedChainId });\n } catch (err) {\n setPhase(\"error\");\n throw normalizeSymmError(err);\n }\n\n // Refresh the instant-opens feed the moment the hedger accepts.\n const configKey = config.getChainConfigKey(resolvedChainId);\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 const wantsTpSl = Boolean(variables.tpsl && (variables.tpsl.tp || variables.tpsl.sl));\n if (!wantsTpSl || !openResult.tempQuoteId) {\n setPhase(\"success\");\n return { instantOpen: openResult };\n }\n\n const tempIdNumber = Number(openResult.tempQuoteId);\n if (!Number.isFinite(tempIdNumber)) {\n setPhase(\"success\");\n return { instantOpen: openResult };\n }\n\n setPhase(\"attaching-tpsl\");\n const quoteId = BigInt(tempIdNumber);\n try {\n const tpslResult = await tpslBase.mutationFn({\n ...(variables.tpsl as Omit<SetQuoteTpSlParameters, \"quoteId\" | \"chainId\">),\n chainId: resolvedChainId,\n quoteId,\n });\n // Mirror useSetQuoteTpSl.onSuccess: seed the confirming slot with the\n // target trigger price/type (not just the state) so useQuoteTpSl renders\n // the levels immediately — e.g. inline on the freshly-opened position row,\n // keyed by the tempQuoteId — instead of blank until the WS report lands.\n const tp = variables.tpsl!.tp;\n const sl = variables.tpsl!.sl;\n if (tp) {\n markConfirming(quoteId, \"tp\", {\n price: tp.triggerPrice,\n pricePrecision: variables.tpsl!.pricePrecision,\n priceType: tp.priceType,\n cohQuoteId: tpslResult.cohQuoteId,\n });\n }\n if (sl) {\n markConfirming(quoteId, \"sl\", {\n price: sl.triggerPrice,\n pricePrecision: variables.tpsl!.pricePrecision,\n priceType: sl.priceType,\n cohQuoteId: tpslResult.cohQuoteId,\n });\n }\n setPhase(\"success\");\n return { instantOpen: openResult, tpsl: tpslResult };\n } catch (err) {\n // Instant open landed; only the TP/SL leg failed. Surface it on the\n // return payload rather than throwing, so callers can render a partial\n // success state without losing the trade.\n setPhase(\"success\");\n return { instantOpen: openResult, tpslError: normalizeSymmError(err) };\n }\n },\n onError: () => setPhase(\"error\"),\n }) as UseMutationResult<UseInstantOpenWithTpSlData, SymmioRequestError, UseInstantOpenWithTpSlVariables>;\n\n return Object.assign(mutation, { phase });\n}\n"],"mappings":";;;;;;;;;;;AAgFA,SAAgB,EACd,IAA+C,CAAC,GACd;CAClC,IAAM,IAAS,EAAgB,CAAU,GACnC,IAAU,EAAiB,GAC3B,IAAc,EAAe,GAC7B,IAAW,EAA+B,CAAM,GAChD,IAAW,EAA4B,CAAM,GAC7C,IAAiB,GAAc,MAAU,EAAM,cAAc,GAE7D,CAAC,GAAO,KAAY,EAAsC,MAAM,GAEhE,IAAW,EAA6F;EAC5G,aAAa,CAAC,wBAAwB;EACtC,YAAY,OAAO,MAAc;GAC/B,IAAM,IAAkB,EAAU,WAAW;GAC7C,EAAS,SAAS;GAClB,IAAI;GACJ,IAAI;IACF,IAAa,MAAM,EAAS,WAAW;KAAE,GAAG;KAAW,SAAS;IAAgB,CAAC;GACnF,SAAS,GAAK;IAEZ,MADA,EAAS,OAAO,GACV,EAAmB,CAAG;GAC9B;GAGA,IAAM,IAAY,EAAO,kBAAkB,CAAe;GAM1D,IALA,EAAiB,kBAAkB,EAAE,WAAW,EAAe,GAAyB,EAAE,aAAU,CAAC,EAAE,CAAC,GAExG,EAA0B,GAAa,EAAE,aAAU,CAAC,GAGhD,EADsB,EAAU,SAAS,EAAU,KAAK,MAAM,EAAU,KAAK,QAC/D,CAAC,EAAW,aAE5B,OADA,EAAS,SAAS,GACX,EAAE,aAAa,EAAW;GAGnC,IAAM,IAAe,OAAO,EAAW,WAAW;GAClD,IAAI,CAAC,OAAO,SAAS,CAAY,GAE/B,OADA,EAAS,SAAS,GACX,EAAE,aAAa,EAAW;GAGnC,EAAS,gBAAgB;GACzB,IAAM,IAAU,OAAO,CAAY;GACnC,IAAI;IACF,IAAM,IAAa,MAAM,EAAS,WAAW;KAC3C,GAAI,EAAU;KACd,SAAS;KACT;IACF,CAAC,GAKK,IAAK,EAAU,KAAM,IACrB,IAAK,EAAU,KAAM;IAkB3B,OAjBI,KACF,EAAe,GAAS,MAAM;KAC5B,OAAO,EAAG;KACV,gBAAgB,EAAU,KAAM;KAChC,WAAW,EAAG;KACd,YAAY,EAAW;IACzB,CAAC,GAEC,KACF,EAAe,GAAS,MAAM;KAC5B,OAAO,EAAG;KACV,gBAAgB,EAAU,KAAM;KAChC,WAAW,EAAG;KACd,YAAY,EAAW;IACzB,CAAC,GAEH,EAAS,SAAS,GACX;KAAE,aAAa;KAAY,MAAM;IAAW;GACrD,SAAS,GAAK;IAKZ,OADA,EAAS,SAAS,GACX;KAAE,aAAa;KAAY,WAAW,EAAmB,CAAG;IAAE;GACvE;EACF;EACA,eAAe,EAAS,OAAO;CACjC,CAAC;CAED,OAAO,OAAO,OAAO,GAAU,EAAE,SAAM,CAAC;AAC1C"}
1
+ {"version":3,"file":"use-instant-open-with-tpsl.js","names":[],"sources":["../../src/instant-layer/use-instant-open-with-tpsl.ts"],"sourcesContent":["\"use client\";\n\nimport {\n getInstantOpensQueryKey,\n instantOpenAutoMutationOptions,\n setQuoteTpSlMutationOptions,\n type ConfigParameter,\n type InstantOpenReturnType,\n type PrepareInstantOpenParameters,\n type SetQuoteTpSlParameters,\n type SetQuoteTpSlReturnType,\n} from \"@symmio/trading-core\";\nimport { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useState } from \"react\";\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 { useTpSlStore } from \"../tpsl/tpsl-store\";\nimport { invalidateAccountBalances, predicateMatch } from \"../utils\";\n\n/**\n * Parameters for {@link useInstantOpenWithTpSl}: the standard instant-open\n * inputs, plus an optional `tpsl` block that mirrors {@link SetQuoteTpSlParameters}\n * minus `quoteId` (derived from the hedger response) and `chainId` (defaulted).\n *\n * When `tpsl` is omitted (or both `tp` and `sl` are empty), the hook behaves\n * exactly like {@link useInstantOpenAuto}. When present, the SDK dispatches\n * `setQuoteTpSl` immediately after the hedger returns a `tempQuoteId` — the\n * message is signed against the (predicted) VA the caller supplies, so no\n * on-chain reconciliation wait is needed. Confirmation still comes through the\n * TP/SL WebSocket picked up by {@link useQuoteTpSl}.\n */\nexport interface UseInstantOpenWithTpSlVariables extends PrepareInstantOpenParameters {\n tpsl?: Omit<SetQuoteTpSlParameters, \"quoteId\" | \"chainId\">;\n}\n\n/** Aggregated success payload from {@link useInstantOpenWithTpSl}. */\nexport interface UseInstantOpenWithTpSlData {\n instantOpen: InstantOpenReturnType;\n /** Set when the TP/SL leg was attempted and succeeded. */\n tpsl?: SetQuoteTpSlReturnType;\n /** Set when the TP/SL leg was attempted and failed — instant open still landed. */\n tpslError?: SymmioRequestError;\n}\n\n/** Which leg the orchestrator is currently on. */\nexport type UseInstantOpenWithTpSlPhase = \"idle\" | \"opening\" | \"attaching-tpsl\" | \"success\" | \"error\";\n\n/** Parameters for {@link useInstantOpenWithTpSl}. */\nexport type UseInstantOpenWithTpSlParameters = ConfigParameter;\n\n/** Return type of {@link useInstantOpenWithTpSl}. */\nexport type UseInstantOpenWithTpSlReturnType = UseMutationResult<\n UseInstantOpenWithTpSlData,\n SymmioRequestError,\n UseInstantOpenWithTpSlVariables\n> & {\n /** Current orchestration phase. Handy for phased status UI. */\n phase: UseInstantOpenWithTpSlPhase;\n};\n\n/**\n * One-shot orchestrator: post an instant open and — if the caller pre-filled\n * a TP/SL block — immediately submit `setQuoteTpSl` using the hedger's returned\n * `tempQuoteId`. Web layer just wires inputs; all mutation logic (both legs +\n * cache invalidation + confirming-slot write) lives in the SDK.\n *\n * Funding follows the `PrepareInstantOpenParameters` one-of: a typed\n * `initialMargin`, or `fund: { mode: \"full-balance\", balance }` (lowcap only)\n * to deploy the whole balance. In full-balance mode the submitted quantity is\n * the SDK-rescaled one — take the TP/SL `quantity` from `useInstantOpenFees`\n * (its `quantity` field) rather than re-deriving it from the typed margin.\n *\n * @example\n * ```tsx\n * const open = useInstantOpenWithTpSl();\n * open.mutate({\n * ...instantOpenParams,\n * tpsl: hasTpOrSl\n * ? { from: sessionKey, virtualAccount: predictedVa, subAccount,\n * symbolId, positionType, quantity, pricePrecision, tp, sl }\n * : undefined,\n * });\n * ```\n */\nexport function useInstantOpenWithTpSl(\n parameters: UseInstantOpenWithTpSlParameters = {},\n): UseInstantOpenWithTpSlReturnType {\n const config = useSymmioConfig(parameters);\n const chainId = useSymmioChainId();\n const queryClient = useQueryClient();\n const openBase = instantOpenAutoMutationOptions(config);\n const tpslBase = setQuoteTpSlMutationOptions(config);\n const markConfirming = useTpSlStore((state) => state.markConfirming);\n\n const [phase, setPhase] = useState<UseInstantOpenWithTpSlPhase>(\"idle\");\n\n const mutation = useMutation<UseInstantOpenWithTpSlData, SymmioRequestError, UseInstantOpenWithTpSlVariables>({\n mutationKey: [\"useInstantOpenWithTpSl\"] as const,\n mutationFn: async (variables) => {\n const resolvedChainId = variables.chainId ?? chainId;\n setPhase(\"opening\");\n let openResult: InstantOpenReturnType;\n try {\n openResult = await openBase.mutationFn({ ...variables, chainId: resolvedChainId });\n } catch (err) {\n setPhase(\"error\");\n throw normalizeSymmError(err);\n }\n\n // Refresh the instant-opens feed the moment the hedger accepts.\n const configKey = config.getChainConfigKey(resolvedChainId);\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 const wantsTpSl = Boolean(variables.tpsl && (variables.tpsl.tp || variables.tpsl.sl));\n if (!wantsTpSl || !openResult.tempQuoteId) {\n setPhase(\"success\");\n return { instantOpen: openResult };\n }\n\n const tempIdNumber = Number(openResult.tempQuoteId);\n if (!Number.isFinite(tempIdNumber)) {\n setPhase(\"success\");\n return { instantOpen: openResult };\n }\n\n setPhase(\"attaching-tpsl\");\n const quoteId = BigInt(tempIdNumber);\n try {\n const tpslResult = await tpslBase.mutationFn({\n ...(variables.tpsl as Omit<SetQuoteTpSlParameters, \"quoteId\" | \"chainId\">),\n chainId: resolvedChainId,\n quoteId,\n });\n // Mirror useSetQuoteTpSl.onSuccess: seed the confirming slot with the\n // target trigger price/type (not just the state) so useQuoteTpSl renders\n // the levels immediately — e.g. inline on the freshly-opened position row,\n // keyed by the tempQuoteId — instead of blank until the WS report lands.\n const tp = variables.tpsl!.tp;\n const sl = variables.tpsl!.sl;\n if (tp) {\n markConfirming(quoteId, \"tp\", {\n price: tp.triggerPrice,\n pricePrecision: variables.tpsl!.pricePrecision,\n priceType: tp.priceType,\n cohQuoteId: tpslResult.cohQuoteId,\n });\n }\n if (sl) {\n markConfirming(quoteId, \"sl\", {\n price: sl.triggerPrice,\n pricePrecision: variables.tpsl!.pricePrecision,\n priceType: sl.priceType,\n cohQuoteId: tpslResult.cohQuoteId,\n });\n }\n setPhase(\"success\");\n return { instantOpen: openResult, tpsl: tpslResult };\n } catch (err) {\n // Instant open landed; only the TP/SL leg failed. Surface it on the\n // return payload rather than throwing, so callers can render a partial\n // success state without losing the trade.\n setPhase(\"success\");\n return { instantOpen: openResult, tpslError: normalizeSymmError(err) };\n }\n },\n onError: () => setPhase(\"error\"),\n }) as UseMutationResult<UseInstantOpenWithTpSlData, SymmioRequestError, UseInstantOpenWithTpSlVariables>;\n\n return Object.assign(mutation, { phase });\n}\n"],"mappings":";;;;;;;;;;;AAsFA,SAAgB,EACd,IAA+C,CAAC,GACd;CAClC,IAAM,IAAS,EAAgB,CAAU,GACnC,IAAU,EAAiB,GAC3B,IAAc,EAAe,GAC7B,IAAW,EAA+B,CAAM,GAChD,IAAW,EAA4B,CAAM,GAC7C,IAAiB,GAAc,MAAU,EAAM,cAAc,GAE7D,CAAC,GAAO,KAAY,EAAsC,MAAM,GAEhE,IAAW,EAA6F;EAC5G,aAAa,CAAC,wBAAwB;EACtC,YAAY,OAAO,MAAc;GAC/B,IAAM,IAAkB,EAAU,WAAW;GAC7C,EAAS,SAAS;GAClB,IAAI;GACJ,IAAI;IACF,IAAa,MAAM,EAAS,WAAW;KAAE,GAAG;KAAW,SAAS;IAAgB,CAAC;GACnF,SAAS,GAAK;IAEZ,MADA,EAAS,OAAO,GACV,EAAmB,CAAG;GAC9B;GAGA,IAAM,IAAY,EAAO,kBAAkB,CAAe;GAM1D,IALA,EAAiB,kBAAkB,EAAE,WAAW,EAAe,GAAyB,EAAE,aAAU,CAAC,EAAE,CAAC,GAExG,EAA0B,GAAa,EAAE,aAAU,CAAC,GAGhD,EADsB,EAAU,SAAS,EAAU,KAAK,MAAM,EAAU,KAAK,QAC/D,CAAC,EAAW,aAE5B,OADA,EAAS,SAAS,GACX,EAAE,aAAa,EAAW;GAGnC,IAAM,IAAe,OAAO,EAAW,WAAW;GAClD,IAAI,CAAC,OAAO,SAAS,CAAY,GAE/B,OADA,EAAS,SAAS,GACX,EAAE,aAAa,EAAW;GAGnC,EAAS,gBAAgB;GACzB,IAAM,IAAU,OAAO,CAAY;GACnC,IAAI;IACF,IAAM,IAAa,MAAM,EAAS,WAAW;KAC3C,GAAI,EAAU;KACd,SAAS;KACT;IACF,CAAC,GAKK,IAAK,EAAU,KAAM,IACrB,IAAK,EAAU,KAAM;IAkB3B,OAjBI,KACF,EAAe,GAAS,MAAM;KAC5B,OAAO,EAAG;KACV,gBAAgB,EAAU,KAAM;KAChC,WAAW,EAAG;KACd,YAAY,EAAW;IACzB,CAAC,GAEC,KACF,EAAe,GAAS,MAAM;KAC5B,OAAO,EAAG;KACV,gBAAgB,EAAU,KAAM;KAChC,WAAW,EAAG;KACd,YAAY,EAAW;IACzB,CAAC,GAEH,EAAS,SAAS,GACX;KAAE,aAAa;KAAY,MAAM;IAAW;GACrD,SAAS,GAAK;IAKZ,OADA,EAAS,SAAS,GACX;KAAE,aAAa;KAAY,WAAW,EAAmB,CAAG;IAAE;GACvE;EACF;EACA,eAAe,EAAS,OAAO;CACjC,CAAC;CAED,OAAO,OAAO,OAAO,GAAU,EAAE,SAAM,CAAC;AAC1C"}
@@ -0,0 +1,25 @@
1
+ import { ConfigParameter, INSTANT_TRADE_REQUIRED_SELECTORS, LEGACY_INSTANT_TRADE_REQUIRED_SELECTORS } from '@symmio/trading-core';
2
+ /** Parameters for {@link useInstantTradeRequiredSelectors}. */
3
+ export interface UseInstantTradeRequiredSelectorsParameters extends ConfigParameter {
4
+ /** Chain to resolve for; defaults to the connected chain. */
5
+ chainId?: number;
6
+ }
7
+ /** Return type of {@link useInstantTradeRequiredSelectors}: the chain's selector set. */
8
+ export type UseInstantTradeRequiredSelectorsReturnType = typeof INSTANT_TRADE_REQUIRED_SELECTORS | typeof LEGACY_INSTANT_TRADE_REQUIRED_SELECTORS;
9
+ /**
10
+ * The session-key delegation selector set for the connected (or given) chain,
11
+ * resolved by its `contractsVersion` — `sendQuote` on a perps-core v0.8.6
12
+ * chain, the legacy `sendQuoteWithAffiliateAndData` on v0.8.5.
13
+ *
14
+ * Use this instead of hardcoding `INSTANT_TRADE_REQUIRED_SELECTORS` in any flow
15
+ * that can point at more than one chain: a hardcoded set grants (and checks)
16
+ * the wrong open-leg selector on the other generation's chains.
17
+ *
18
+ * @example
19
+ * ```tsx
20
+ * const selectors = useInstantTradeRequiredSelectors();
21
+ * grantDelegation.mutate({ account, delegatedSigner, selectors, expiryTimestamp });
22
+ * ```
23
+ */
24
+ export declare function useInstantTradeRequiredSelectors(parameters?: UseInstantTradeRequiredSelectorsParameters): UseInstantTradeRequiredSelectorsReturnType;
25
+ //# sourceMappingURL=use-instant-trade-required-selectors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-instant-trade-required-selectors.d.ts","sourceRoot":"","sources":["../../src/instant-layer/use-instant-trade-required-selectors.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,gCAAgC,EACrC,KAAK,uCAAuC,EAC7C,MAAM,sBAAsB,CAAC;AAI9B,+DAA+D;AAC/D,MAAM,WAAW,0CAA2C,SAAQ,eAAe;IACjF,6DAA6D;IAC7D,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,yFAAyF;AACzF,MAAM,MAAM,0CAA0C,GAClD,OAAO,gCAAgC,GACvC,OAAO,uCAAuC,CAAC;AAEnD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gCAAgC,CAC9C,UAAU,GAAE,0CAA+C,GAC1D,0CAA0C,CAI5C"}
@@ -0,0 +1,13 @@
1
+ "use client";
2
+ import { useSymmioChainId as e } from "../provider/use-symmio-chain-id.js";
3
+ import { useSymmioConfig as t } from "../provider/use-symmio-config.js";
4
+ import { getInstantTradeRequiredSelectors as n } from "@symmio/trading-core";
5
+ //#region src/instant-layer/use-instant-trade-required-selectors.ts
6
+ function r(r = {}) {
7
+ let i = t(r), a = e();
8
+ return n(i, { chainId: r.chainId ?? a });
9
+ }
10
+ //#endregion
11
+ export { r as useInstantTradeRequiredSelectors };
12
+
13
+ //# sourceMappingURL=use-instant-trade-required-selectors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-instant-trade-required-selectors.js","names":[],"sources":["../../src/instant-layer/use-instant-trade-required-selectors.ts"],"sourcesContent":["\"use client\";\n\nimport {\n getInstantTradeRequiredSelectors,\n type ConfigParameter,\n type INSTANT_TRADE_REQUIRED_SELECTORS,\n type LEGACY_INSTANT_TRADE_REQUIRED_SELECTORS,\n} from \"@symmio/trading-core\";\nimport { useSymmioChainId } from \"../provider/use-symmio-chain-id\";\nimport { useSymmioConfig } from \"../provider/use-symmio-config\";\n\n/** Parameters for {@link useInstantTradeRequiredSelectors}. */\nexport interface UseInstantTradeRequiredSelectorsParameters extends ConfigParameter {\n /** Chain to resolve for; defaults to the connected chain. */\n chainId?: number;\n}\n\n/** Return type of {@link useInstantTradeRequiredSelectors}: the chain's selector set. */\nexport type UseInstantTradeRequiredSelectorsReturnType =\n | typeof INSTANT_TRADE_REQUIRED_SELECTORS\n | typeof LEGACY_INSTANT_TRADE_REQUIRED_SELECTORS;\n\n/**\n * The session-key delegation selector set for the connected (or given) chain,\n * resolved by its `contractsVersion` — `sendQuote` on a perps-core v0.8.6\n * chain, the legacy `sendQuoteWithAffiliateAndData` on v0.8.5.\n *\n * Use this instead of hardcoding `INSTANT_TRADE_REQUIRED_SELECTORS` in any flow\n * that can point at more than one chain: a hardcoded set grants (and checks)\n * the wrong open-leg selector on the other generation's chains.\n *\n * @example\n * ```tsx\n * const selectors = useInstantTradeRequiredSelectors();\n * grantDelegation.mutate({ account, delegatedSigner, selectors, expiryTimestamp });\n * ```\n */\nexport function useInstantTradeRequiredSelectors(\n parameters: UseInstantTradeRequiredSelectorsParameters = {},\n): UseInstantTradeRequiredSelectorsReturnType {\n const config = useSymmioConfig(parameters);\n const chainId = useSymmioChainId();\n return getInstantTradeRequiredSelectors(config, { chainId: parameters.chainId ?? chainId });\n}\n"],"mappings":";;;;;AAqCA,SAAgB,EACd,IAAyD,CAAC,GACd;CAC5C,IAAM,IAAS,EAAgB,CAAU,GACnC,IAAU,EAAiB;CACjC,OAAO,EAAiC,GAAQ,EAAE,SAAS,EAAW,WAAW,EAAQ,CAAC;AAC5F"}