@symmio/trading-react 4.2.0 → 4.4.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.
@@ -5,6 +5,7 @@ export declare function useInstantOpenInputs(parameters: GetInstantOpenFeesParam
5
5
  validationError: import('../index.js').SymmioRequestError | undefined;
6
6
  ready: boolean;
7
7
  refetchEstimatedPrice: (options?: import('@tanstack/query-core').RefetchOptions) => Promise<import('@tanstack/query-core').QueryObserverResult<import('@symmio/trading-core').GetEstimatedPriceReturnType, import('../index.js').SymmioRequestError>>;
8
+ estimatedOpenPriceWithoutShadow: string | undefined;
8
9
  estimatedOpenPriceTimestamp: number | undefined;
9
10
  prefills: {
10
11
  chainId: number;
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+NpB"}
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4OpB"}
@@ -12,121 +12,122 @@ import { PositionType as i, calculateTradeParams as a } from "@symmio/trading-co
12
12
  import { useMemo as ae } from "react";
13
13
  //#region src/instant-layer/use-instant-open-inputs.ts
14
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({
15
+ let l = ee(o), u = e(), d = o.chainId ?? u, { subAccountAddress: oe, market: f, positionType: p, initialMargin: se, fund: m, leverage: h, solverId: g } = o, _ = m !== void 0, v = _ || o.availableBalance !== void 0, y = s === "prepare" || v, ce = s === "prepare" && l.getChainConfig(d).contractsVersion === "0.8.6", b = _ ? m.balance : se ?? "", x = c && b.length > 0, S = l.getSolver({
16
16
  chainId: d,
17
- solverId: _
18
- }).id === "enigma", w = S ? r({
17
+ solverId: g
18
+ }).id === "enigma", C = x ? r({
19
19
  ...o,
20
- isLowcap: C
21
- }) : void 0, T = S && w === void 0, E = ne({
20
+ isLowcap: S
21
+ }) : void 0, w = x && C === void 0, T = ne({
22
22
  config: o.config,
23
23
  chainId: d,
24
- solverId: _,
24
+ solverId: g,
25
25
  query: {
26
- enabled: T,
26
+ enabled: w,
27
27
  staleTime: 3e5
28
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({
29
+ }).data?.find((e) => e.symbolId === f.id), E = f.name ?? T?.name, D = f.pricePrecision ?? T?.pricePrecision, O = f.quantityPrecision ?? T?.quantityPrecision, k = f.hedgerFeeOpen ?? T?.hedgerFeeOpen, A = f.hedgerFeeClose ?? T?.hedgerFeeClose, j = f.minOpenSolverFeeCap ?? (T ? T.kind === "enigma" ? T.minOpenSolverFeeCap : "0" : void 0), M = f.minCloseSolverFeeCap ?? (T ? T.kind === "enigma" ? T.minCloseSolverFeeCap : "0" : void 0), le = !ce || j !== void 0 && M !== void 0, N = T?.kind === "enigma" ? T : void 0, ue = f.hedgerFeeCloseEarlyRate ?? N?.hedgerFeeCloseEarlyRate ?? A, de = f.hedgerFeeCloseEarlyThreshold ?? N?.hedgerFeeCloseEarlyThreshold ?? 0, fe = f.hedgerFeeCloseStandardThreshold ?? N?.hedgerFeeCloseStandardThreshold ?? 0, P = f.minAcceptablePortionLf ?? T?.minAcceptablePortionLf, F = f.minAcceptableQuoteValue ?? T?.minAcceptableQuoteValue, I = f.maxNotionalValue ?? T?.maxNotionalValue, L = f.minNotionalValue ?? T?.minNotionalValue, R = f.maxQuantity ?? T?.maxQuantity, z = f.lotSize ?? T?.lotSize, B = !v || P !== void 0 && F !== void 0 && I !== void 0 && L !== void 0 && R !== void 0 && z !== void 0, V = o.lockedParamPercent?.cva !== void 0 && o.lockedParamPercent.lf !== void 0 && o.lockedParamPercent.partyAmm !== void 0 && o.lockedParamPercent.partyBmm !== void 0, H = n({
30
30
  config: o.config,
31
31
  chainId: d,
32
- solverId: _,
33
- symbol: D ?? "",
34
- leverage: g,
32
+ solverId: g,
33
+ symbol: E ?? "",
34
+ leverage: h,
35
35
  query: {
36
- enabled: T && b && !U && D !== void 0,
36
+ enabled: w && y && !V && E !== void 0,
37
37
  staleTime: 3e5
38
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({
39
+ }), U = V ? o.lockedParamPercent : H.data ? {
40
+ cva: H.data.cva ?? "0",
41
+ lf: H.data.lf ?? "0",
42
+ partyAmm: H.data.partyAmm ?? "0",
43
+ partyBmm: H.data.partyBmm ?? "0"
44
+ } : void 0, pe = !y || U !== void 0, W = ie({
45
45
  config: o.config,
46
46
  chainId: d,
47
- solverId: _,
47
+ solverId: g,
48
48
  query: {
49
- enabled: T && C && o.solverInfo === void 0,
49
+ enabled: w && S && o.solverInfo === void 0,
50
50
  staleTime: 3e5,
51
51
  retry: !1
52
52
  }
53
- }), q = o.solverInfo ?? K.data ?? (K.isError ? {} : void 0), fe = !C || q !== void 0, pe = te({
53
+ }), G = o.solverInfo ?? W.data ?? (W.isError ? {} : void 0), me = !S || G !== void 0, he = te({
54
54
  config: o.config,
55
55
  chainId: d,
56
- user: f,
57
- symbolId: BigInt(p.id),
56
+ user: oe,
57
+ symbolId: BigInt(f.id),
58
58
  query: {
59
- enabled: T && o.feeRates === void 0,
59
+ enabled: w && o.feeRates === void 0,
60
60
  staleTime: 3e5
61
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,
62
+ }), K = o.feeRates ?? he.data, ge = re({
63
+ name: E,
64
+ solverId: g,
65
+ enabled: w && o.markPrice === void 0
66
+ }), q = o.markPrice ?? ge.markPrice ?? void 0, J = ae(() => !w || !S || q === void 0 || D === void 0 || O === void 0 ? "" : a({
67
+ markPrice: q,
68
68
  slippage: 0,
69
- positionType: m,
70
- userInput: x,
69
+ positionType: p,
70
+ userInput: b,
71
71
  inputField: "PRICE",
72
- leverage: g,
73
- pricePrecision: O,
74
- quantityPrecision: k
72
+ leverage: h,
73
+ pricePrecision: D,
74
+ quantityPrecision: O
75
75
  })?.quantity ?? "", [
76
- T,
77
- C,
78
- Y,
76
+ w,
77
+ S,
78
+ q,
79
+ D,
79
80
  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({
81
+ p,
82
+ b,
83
+ h
84
+ ]), _e = q === void 0 ? "" : String(Number(q) * (p === i.SHORT ? .5 : 1.5)), Y = t({
85
85
  config: o.config,
86
86
  chainId: d,
87
- solverId: _,
88
- symbolId: p.id,
89
- quantity: X,
90
- positionType: m,
87
+ solverId: g,
88
+ symbolId: f.id,
89
+ quantity: J,
90
+ positionType: p,
91
91
  entry: "open",
92
- price: he,
92
+ price: _e,
93
93
  query: {
94
- enabled: T && C && o.estimatedOpenPrice === void 0 && X.length > 0,
94
+ enabled: w && S && o.estimatedOpenPrice === void 0 && J.length > 0,
95
95
  staleTime: 3e4
96
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;
97
+ }), X = S && o.estimatedOpenPrice === void 0 && (Y.isDebouncing || Y.isFetching), Z = !S || o.estimatedOpenPrice !== void 0 || !X && (Y.isFetched || Y.isError), Q = o.estimatedOpenPrice === void 0 ? Y.data?.estimatedPrice : o.estimatedOpenPrice, $ = !S || !Z ? void 0 : Q && Q !== "0" ? Q : null, ve = w && S && o.estimatedOpenPrice === void 0 && $ != null && !X && !Y.isPlaceholderData && !Y.isError ? Y.data?.estimatedPriceWithoutShadow : void 0;
98
98
  return {
99
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
- refetchEstimatedPrice: Z.refetch,
103
- estimatedOpenPriceTimestamp: Z.isPlaceholderData ? void 0 : Z.dataUpdatedAt || void 0,
100
+ validationError: C,
101
+ ready: w && E !== void 0 && D !== void 0 && O !== void 0 && K !== void 0 && q !== void 0 && pe && (!S || k !== void 0 && A !== void 0) && B && le && me && Z,
102
+ refetchEstimatedPrice: Y.refetch,
103
+ estimatedOpenPriceWithoutShadow: ve,
104
+ estimatedOpenPriceTimestamp: Y.isPlaceholderData ? void 0 : Y.dataUpdatedAt || void 0,
104
105
  prefills: {
105
106
  chainId: d,
106
107
  market: {
107
- id: p.id,
108
- name: D,
109
- pricePrecision: O,
110
- quantityPrecision: k,
111
- minOpenSolverFeeCap: M,
112
- minCloseSolverFeeCap: N,
113
- hedgerFeeOpen: A,
114
- hedgerFeeClose: j,
115
- hedgerFeeCloseEarlyRate: le,
116
- hedgerFeeCloseEarlyThreshold: ue,
117
- hedgerFeeCloseStandardThreshold: F,
118
- minAcceptablePortionLf: I,
119
- minAcceptableQuoteValue: L,
120
- maxNotionalValue: R,
121
- minNotionalValue: z,
122
- maxQuantity: B,
123
- lotSize: V
108
+ id: f.id,
109
+ name: E,
110
+ pricePrecision: D,
111
+ quantityPrecision: O,
112
+ minOpenSolverFeeCap: j,
113
+ minCloseSolverFeeCap: M,
114
+ hedgerFeeOpen: k,
115
+ hedgerFeeClose: A,
116
+ hedgerFeeCloseEarlyRate: ue,
117
+ hedgerFeeCloseEarlyThreshold: de,
118
+ hedgerFeeCloseStandardThreshold: fe,
119
+ minAcceptablePortionLf: P,
120
+ minAcceptableQuoteValue: F,
121
+ maxNotionalValue: I,
122
+ minNotionalValue: L,
123
+ maxQuantity: R,
124
+ lotSize: z
124
125
  },
125
- markPrice: Y,
126
- feeRates: J,
127
- lockedParamPercent: G,
128
- solverInfo: q,
129
- estimatedOpenPrice: _e
126
+ markPrice: q,
127
+ feeRates: K,
128
+ lockedParamPercent: U,
129
+ solverInfo: G,
130
+ estimatedOpenPrice: $
130
131
  }
131
132
  };
132
133
  }
@@ -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 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 lockedParamPercent,\n solverInfo,\n estimatedOpenPrice,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,SAAgB,EACd,GACA,GACA,IAAe,IACf;CACA,IAAM,IAAS,GAAgB,CAAU,GACnC,IAAiB,EAAiB,GAClC,IAAU,EAAW,WAAW,GAChC,EAAE,sBAAmB,WAAQ,iBAAc,mBAAe,SAAM,aAAU,gBAAa,GACvF,IAAgB,MAAS,KAAA,GACzB,IAAqB,KAAiB,EAAW,qBAAqB,KAAA,GACtE,IAAoB,MAAY,aAAa,GAC7C,KAAqB,MAAY,aAAa,EAAO,eAAe,CAAO,EAAE,qBAAqB,SAElG,IAAc,IAAgB,EAAK,UAAW,MAAiB,IAC/D,IAAY,KAAgB,EAAY,SAAS,GAGjD,IAAW,EAAO,UAAU;EAAE;EAAS;CAAS,CAAC,EAAE,OAAO,UAC1D,IAAkB,IAAY,EAA2B;EAAE,GAAG;EAAY;CAAS,CAAC,IAAI,KAAA,GACxF,IAAU,KAAa,MAAoB,KAAA,GAS3C,IANe,GAAW;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,iBA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,KAAY,EAAW,uBAAuB,KAAA,MAAc,EAAc,gBAAgB,EAAc,aACpG,IACJ,CAAC,KACD,EAAW,uBAAuB,KAAA,KACjC,CAAC,OAAqB,EAAc,aAAa,EAAc,UAC5D,IACJ,EAAW,uBAAuB,KAAA,IAA4C,EAAc,MAAM,iBAApD,EAAW,oBACrD,KACJ,CAAC,KAAY,CAAC,IAAkB,KAAA,IAAY,KAAoB,MAAqB,MAAM,IAAmB;CAiBhH,OAAO;EACL;EACA;EACA,OAhBA,KACA,MAAe,KAAA,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
+ {"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 // Only pair diagnostics with the settled SDK-managed estimate, never a\n // caller override or a cached response for inputs that are still changing.\n const estimatedOpenPriceWithoutShadow =\n enabled &&\n isLowcap &&\n parameters.estimatedOpenPrice === undefined &&\n estimatedOpenPrice != null &&\n !estimateUpdating &&\n !estimateQuery.isPlaceholderData &&\n !estimateQuery.isError\n ? estimateQuery.data?.estimatedPriceWithoutShadow\n : undefined;\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 estimatedOpenPriceWithoutShadow,\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 lockedParamPercent,\n solverInfo,\n estimatedOpenPrice,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,SAAgB,EACd,GACA,GACA,IAAe,IACf;CACA,IAAM,IAAS,GAAgB,CAAU,GACnC,IAAiB,EAAiB,GAClC,IAAU,EAAW,WAAW,GAChC,EAAE,uBAAmB,WAAQ,iBAAc,mBAAe,SAAM,aAAU,gBAAa,GACvF,IAAgB,MAAS,KAAA,GACzB,IAAqB,KAAiB,EAAW,qBAAqB,KAAA,GACtE,IAAoB,MAAY,aAAa,GAC7C,KAAqB,MAAY,aAAa,EAAO,eAAe,CAAO,EAAE,qBAAqB,SAElG,IAAc,IAAgB,EAAK,UAAW,MAAiB,IAC/D,IAAY,KAAgB,EAAY,SAAS,GAGjD,IAAW,EAAO,UAAU;EAAE;EAA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ACF;GACA;GACA;GACA;GACA;GACA;EACF;CACF;AACF"}
@@ -10,24 +10,31 @@ import { SymmioRequestError } from '../errors/symmio-request-error.js';
10
10
  * exactly like {@link useInstantOpenAuto}. When present, the SDK dispatches
11
11
  * `setQuoteTpSl` immediately after the hedger returns a `tempQuoteId` — the
12
12
  * message is signed against the (predicted) VA the caller supplies, so no
13
- * on-chain reconciliation wait is needed. Confirmation still comes through the
14
- * TP/SL WebSocket picked up by {@link useQuoteTpSl}.
13
+ * on-chain reconciliation wait is needed. Acceptance is separate from observed
14
+ * order state. Consumers can use the SDK store or own REST reconciliation.
15
15
  */
16
16
  export interface UseInstantOpenWithTpSlVariables extends PrepareInstantOpenParameters {
17
17
  tpsl?: Omit<SetQuoteTpSlParameters, "quoteId" | "chainId">;
18
+ /** Use the exact submitted size for attachment, or retain the provided quantity (default). */
19
+ tpslQuantityMode?: "provided" | "prepared";
18
20
  }
19
21
  /** Aggregated success payload from {@link useInstantOpenWithTpSl}. */
20
22
  export interface UseInstantOpenWithTpSlData {
21
23
  instantOpen: InstantOpenReturnType;
22
24
  /** Set when the TP/SL leg was attempted and succeeded. */
23
25
  tpsl?: SetQuoteTpSlReturnType;
24
- /** Set when the TP/SL leg was attempted and failed — instant open still landed. */
26
+ /** Set when TP/SL attachment could not be submitted or failed — instant open still landed. */
25
27
  tpslError?: SymmioRequestError;
28
+ /** Resolved attachment inputs, including on failure. Contains no signature. */
29
+ tpslParameters?: SetQuoteTpSlParameters;
26
30
  }
27
31
  /** Which leg the orchestrator is currently on. */
28
32
  export type UseInstantOpenWithTpSlPhase = "idle" | "opening" | "attaching-tpsl" | "success" | "error";
29
33
  /** Parameters for {@link useInstantOpenWithTpSl}. */
30
- export type UseInstantOpenWithTpSlParameters = ConfigParameter;
34
+ export type UseInstantOpenWithTpSlParameters = ConfigParameter & {
35
+ /** "external" leaves TP/SL optimism/reconciliation to the consumer. Defaults to "sdk". */
36
+ tpslState?: "sdk" | "external";
37
+ };
31
38
  /** Return type of {@link useInstantOpenWithTpSl}. */
32
39
  export type UseInstantOpenWithTpSlReturnType = UseMutationResult<UseInstantOpenWithTpSlData, SymmioRequestError, UseInstantOpenWithTpSlVariables> & {
33
40
  /** Current orchestration phase. Handy for phased status UI. */
@@ -37,13 +44,13 @@ export type UseInstantOpenWithTpSlReturnType = UseMutationResult<UseInstantOpenW
37
44
  * One-shot orchestrator: post an instant open and — if the caller pre-filled
38
45
  * a TP/SL block — immediately submit `setQuoteTpSl` using the hedger's returned
39
46
  * `tempQuoteId`. Web layer just wires inputs; all mutation logic (both legs +
40
- * cache invalidation + confirming-slot write) lives in the SDK.
47
+ * open/balance invalidation and optional confirming-slot write) lives in the SDK.
41
48
  *
42
49
  * Funding follows the `PrepareInstantOpenParameters` one-of: a typed
43
50
  * `initialMargin`, or `fund: { mode: "full-balance", balance }` (lowcap only)
44
51
  * 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.
52
+ * the SDK-rescaled one. Select `tpslQuantityMode: "prepared"` to use that exact
53
+ * submitted quantity, even when a prior preview differs.
47
54
  *
48
55
  * @example
49
56
  * ```tsx
@@ -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,IA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AC9F,gBAAgB,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;CAC5C;AAED,sEAAsE;AACtE,MAAM,WAAW,0BAA0B;IACzC,WAAW,EAAE,qBAAqB,CAAC;IACnC,0DAA0D;IAC1D,IAAI,CAAC,EAAE,sBAAsB,CAAC;IAC9B,8FAA8F;IAC9F,SAAS,CAAC,EAAE,kBAAkB,CAAC;IAC/B,+EAA+E;IAC/E,cAAc,CAAC,EAAE,sBAAsB,CAAC;CACzC;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,GAAG;IAC/D,0FAA0F;IAC1F,SAAS,CAAC,EAAE,KAAK,GAAG,UAAU,CAAC;CAChC,CAAC;AAEF,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,CA0GlC"}
@@ -5,63 +5,77 @@ import { normalizeSymmError as n } from "../errors/normalize-symm-error.js";
5
5
  import { predicateMatch as r } from "../utils/predicate-match.js";
6
6
  import { invalidateAccountBalances as i } from "../utils/invalidate-account-balances.js";
7
7
  import { useTpSlStore as a } from "../tpsl/tpsl-store.js";
8
- import { getInstantOpensQueryKey as o, instantOpenAutoMutationOptions as s, setQuoteTpSlMutationOptions as c } from "@symmio/trading-core";
9
- import { useState as l } from "react";
10
- import { useMutation as u, useQueryClient as d } from "@tanstack/react-query";
8
+ import { SymmError as o, getInstantOpensQueryKey as s, instantOpen as c, instantOpenAutoMutationOptions as l, prepareInstantOpenParams as u, setQuoteTpSlMutationOptions as d } from "@symmio/trading-core";
9
+ import { formatUnits as f } from "viem";
10
+ import { useState as p } from "react";
11
+ import { useMutation as m, useQueryClient as h } from "@tanstack/react-query";
11
12
  //#region src/instant-layer/use-instant-open-with-tpsl.ts
12
- function f(f = {}) {
13
- let p = t(f), m = e(), h = d(), g = s(p), _ = c(p), v = a((e) => e.markConfirming), [y, b] = l("idle"), x = u({
13
+ function g(g = {}) {
14
+ let _ = t(g), v = e(), y = h(), b = l(_), x = d(_), S = a((e) => e.markConfirming), [C, w] = p("idle"), T = m({
14
15
  mutationKey: ["useInstantOpenWithTpSl"],
16
+ retry: !1,
15
17
  mutationFn: async (e) => {
16
- let t = e.chainId ?? m;
17
- b("opening");
18
- let a;
18
+ let t = e.chainId ?? v;
19
+ w("opening");
20
+ let a, l = e.tpsl?.quantity;
19
21
  try {
20
- a = await g.mutationFn({
22
+ if (e.tpslQuantityMode === "prepared" && e.tpsl) {
23
+ let n = await u(_, {
24
+ ...e,
25
+ chainId: t
26
+ });
27
+ l = f(n.order.quantity, 18), a = await c(_, n);
28
+ } else a = await b.mutationFn({
21
29
  ...e,
22
30
  chainId: t
23
31
  });
24
32
  } catch (e) {
25
- throw b("error"), n(e);
33
+ throw w("error"), n(e);
26
34
  }
27
- let s = p.getChainConfigKey(t);
28
- if (h.invalidateQueries({ predicate: r(o, { configKey: s }) }), i(h, { configKey: s }), !(e.tpsl && (e.tpsl.tp || e.tpsl.sl)) || !a.tempQuoteId) return b("success"), { instantOpen: a };
29
- let c = Number(a.tempQuoteId);
30
- if (!Number.isFinite(c)) return b("success"), { instantOpen: a };
31
- b("attaching-tpsl");
32
- let l = BigInt(c);
35
+ let d = _.getChainConfigKey(t);
36
+ if (y.invalidateQueries({ predicate: r(s, { configKey: d }) }), i(y, { configKey: d }), !(e.tpsl && (e.tpsl.tp || e.tpsl.sl))) return w("success"), { instantOpen: a };
37
+ let p = a.tempQuoteId, m = typeof p == "string" && /^-?\d+$/.test(p) ? Number(p) : NaN;
38
+ if (!Number.isSafeInteger(m) || m === 0) return w("success"), {
39
+ instantOpen: a,
40
+ tpslError: n(new o("validation", "INSTANT_OPEN_TPSL_INVALID_ID", "Open accepted but attachment quote ID is missing or unsafe."))
41
+ };
42
+ w("attaching-tpsl");
43
+ let h = BigInt(m), C = {
44
+ ...e.tpsl,
45
+ quantity: l,
46
+ chainId: t,
47
+ quoteId: h
48
+ };
33
49
  try {
34
- let n = await _.mutationFn({
35
- ...e.tpsl,
36
- chainId: t,
37
- quoteId: l
38
- }), r = e.tpsl.tp, i = e.tpsl.sl;
39
- return r && v(l, "tp", {
50
+ let t = await x.mutationFn(C), n = e.tpsl.tp, r = e.tpsl.sl;
51
+ return n && g.tpslState !== "external" && S(h, "tp", {
52
+ price: n.triggerPrice,
53
+ pricePrecision: e.tpsl.pricePrecision,
54
+ priceType: n.priceType,
55
+ cohQuoteId: t.cohQuoteId
56
+ }), r && g.tpslState !== "external" && S(h, "sl", {
40
57
  price: r.triggerPrice,
41
58
  pricePrecision: e.tpsl.pricePrecision,
42
59
  priceType: r.priceType,
43
- cohQuoteId: n.cohQuoteId
44
- }), i && v(l, "sl", {
45
- price: i.triggerPrice,
46
- pricePrecision: e.tpsl.pricePrecision,
47
- priceType: i.priceType,
48
- cohQuoteId: n.cohQuoteId
49
- }), b("success"), {
60
+ cohQuoteId: t.cohQuoteId
61
+ }), w("success"), {
50
62
  instantOpen: a,
51
- tpsl: n
63
+ tpsl: t,
64
+ tpslParameters: C
52
65
  };
53
66
  } catch (e) {
54
- return b("success"), {
67
+ return w("success"), {
55
68
  instantOpen: a,
56
- tpslError: n(e)
69
+ tpslError: n(e),
70
+ tpslParameters: C
57
71
  };
58
72
  }
59
73
  },
60
- onError: () => b("error")
74
+ onError: () => w("error")
61
75
  });
62
- return Object.assign(x, { phase: y });
76
+ return Object.assign(T, { phase: C });
63
77
  }
64
78
  //#endregion
65
- export { f as useInstantOpenWithTpSl };
79
+ export { g as useInstantOpenWithTpSl };
66
80
 
67
81
  //# sourceMappingURL=use-instant-open-with-tpsl.js.map
@@ -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 * 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"}
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 instantOpen,\n instantOpenAutoMutationOptions,\n prepareInstantOpenParams,\n setQuoteTpSlMutationOptions,\n SymmError,\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 { formatUnits } from \"viem\";\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. Acceptance is separate from observed\n * order state. Consumers can use the SDK store or own REST reconciliation.\n */\nexport interface UseInstantOpenWithTpSlVariables extends PrepareInstantOpenParameters {\n tpsl?: Omit<SetQuoteTpSlParameters, \"quoteId\" | \"chainId\">;\n /** Use the exact submitted size for attachment, or retain the provided quantity (default). */\n tpslQuantityMode?: \"provided\" | \"prepared\";\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 TP/SL attachment could not be submitted or failed — instant open still landed. */\n tpslError?: SymmioRequestError;\n /** Resolved attachment inputs, including on failure. Contains no signature. */\n tpslParameters?: SetQuoteTpSlParameters;\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 /** \"external\" leaves TP/SL optimism/reconciliation to the consumer. Defaults to \"sdk\". */\n tpslState?: \"sdk\" | \"external\";\n};\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 * open/balance invalidation and optional 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. Select `tpslQuantityMode: \"prepared\"` to use that exact\n * submitted quantity, even when a prior preview differs.\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 retry: false,\n mutationFn: async (variables) => {\n const resolvedChainId = variables.chainId ?? chainId;\n setPhase(\"opening\");\n let openResult: InstantOpenReturnType;\n let quantity = variables.tpsl?.quantity;\n try {\n if (variables.tpslQuantityMode === \"prepared\" && variables.tpsl) {\n const prepared = await prepareInstantOpenParams(config, { ...variables, chainId: resolvedChainId });\n quantity = formatUnits(prepared.order.quantity, 18);\n openResult = await instantOpen(config, prepared);\n } else {\n openResult = await openBase.mutationFn({ ...variables, chainId: resolvedChainId });\n }\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) {\n setPhase(\"success\");\n return { instantOpen: openResult };\n }\n\n // Check the original decimal integer syntax before Number can round a fractional ID.\n const tempId = openResult.tempQuoteId;\n const tempIdNumber = typeof tempId === \"string\" && /^-?\\d+$/.test(tempId) ? Number(tempId) : NaN;\n if (!Number.isSafeInteger(tempIdNumber) || tempIdNumber === 0) {\n setPhase(\"success\");\n return {\n instantOpen: openResult,\n tpslError: normalizeSymmError(\n new SymmError(\n \"validation\",\n \"INSTANT_OPEN_TPSL_INVALID_ID\",\n \"Open accepted but attachment quote ID is missing or unsafe.\",\n ),\n ),\n };\n }\n\n setPhase(\"attaching-tpsl\");\n const quoteId = BigInt(tempIdNumber);\n const tpslParameters: SetQuoteTpSlParameters = {\n ...variables.tpsl!,\n quantity: quantity!,\n chainId: resolvedChainId,\n quoteId,\n };\n try {\n const tpslResult = await tpslBase.mutationFn(tpslParameters);\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 && parameters.tpslState !== \"external\") {\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 && parameters.tpslState !== \"external\") {\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, tpslParameters };\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), tpslParameters };\n }\n },\n onError: () => setPhase(\"error\"),\n }) as UseMutationResult<UseInstantOpenWithTpSlData, SymmioRequestError, UseInstantOpenWithTpSlVariables>;\n\n return Object.assign(mutation, { phase });\n}\n"],"mappings":";;;;;;;;;;;;AAiGA,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,OAAO;EACP,YAAY,OAAO,MAAc;GAC/B,IAAM,IAAkB,EAAU,WAAW;GAC7C,EAAS,SAAS;GAClB,IAAI,GACA,IAAW,EAAU,MAAM;GAC/B,IAAI;IACF,IAAI,EAAU,qBAAqB,cAAc,EAAU,MAAM;KAC/D,IAAM,IAAW,MAAM,EAAyB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AW,EAAG;KACd,YAAY,EAAW;IACzB,CAAC,GAEH,EAAS,SAAS,GACX;KAAE,aAAa;KAAY,MAAM;KAAY;IAAe;GACrE,SAAS,GAAK;IAKZ,OADA,EAAS,SAAS,GACX;KAAE,aAAa;KAAY,WAAW,EAAmB,CAAG;KAAG;IAAe;GACvF;EACF;EACA,eAAe,EAAS,OAAO;CACjC,CAAC;CAED,OAAO,OAAO,OAAO,GAAU,EAAE,SAAM,CAAC;AAC1C"}
@@ -23,6 +23,12 @@ export type UsePrepareInstantOpenParamsReturnType = UseQueryResult<PrepareInstan
23
23
  * preview bit-for-bit.
24
24
  */
25
25
  estimatedOpenPrice: string | null | undefined;
26
+ /**
27
+ * Diagnostic no-shadow price from the same settled SDK-managed estimate.
28
+ * Absent for older solvers, pending/failed estimates or caller-supplied
29
+ * estimatedOpenPrice. Never use it for preparation, fees or submission.
30
+ */
31
+ estimatedOpenPriceWithoutShadow?: string;
26
32
  /** Arrival time of the fetched estimate in epoch milliseconds. The frontend decides when to refresh or expire it. */
27
33
  estimatedOpenPriceTimestamp: number | undefined;
28
34
  /**
@@ -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;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"}
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;;;;OAIG;IACH,+BAA+B,CAAC,EAAE,MAAM,CAAC;IACzC,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,CA+BvC"}
@@ -28,6 +28,7 @@ function i(i) {
28
28
  refetchEstimatedPrice: a.refetchEstimatedPrice,
29
29
  validationError: a.validationError,
30
30
  estimatedOpenPrice: a.prefills.estimatedOpenPrice,
31
+ estimatedOpenPriceWithoutShadow: a.estimatedOpenPriceWithoutShadow,
31
32
  estimatedOpenPriceTimestamp: i.estimatedOpenPriceTimestamp ?? a.estimatedOpenPriceTimestamp,
32
33
  isReady: a.ready && s.isSuccess && !s.isFetching && !s.isPlaceholderData
33
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 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"}
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 /**\n * Diagnostic no-shadow price from the same settled SDK-managed estimate.\n * Absent for older solvers, pending/failed estimates or caller-supplied\n * estimatedOpenPrice. Never use it for preparation, fees or submission.\n */\n estimatedOpenPriceWithoutShadow?: string;\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 estimatedOpenPriceWithoutShadow: inputs.estimatedOpenPriceWithoutShadow,\n estimatedOpenPriceTimestamp: parameters.estimatedOpenPriceTimestamp ?? inputs.estimatedOpenPriceTimestamp,\n isReady: inputs.ready && query.isSuccess && !query.isFetching && !query.isPlaceholderData,\n };\n}\n"],"mappings":";;;;;;AAiGA,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,iCAAiC,EAAO;EACxC,6BAA6B,EAAW,+BAA+B,EAAO;EAC9E,SAAS,EAAO,SAAS,EAAM,aAAa,CAAC,EAAM,cAAc,CAAC,EAAM;CAC1E;AACF"}
@@ -30,6 +30,10 @@ export interface UseEnigmaPricesReturnType {
30
30
  * non-stateful sink). The subscription is shared across hook instances via the
31
31
  * SDK socket pool — multiple `useEnigmaPrices()` mounts cost one connection.
32
32
  *
33
+ * Prices, status and errors reset when the Config instance or resolved chain
34
+ * changes. Reconnects and stopping/restarting the same target retain prices.
35
+ * Callbacks from a disposed subscription are ignored.
36
+ *
33
37
  * @example
34
38
  * ```tsx
35
39
  * const { prices, status } = useEnigmaPrices();
@@ -1 +1 @@
1
- {"version":3,"file":"use-enigma-prices.d.ts","sourceRoot":"","sources":["../../src/price-service/use-enigma-prices.ts"],"names":[],"mappings":"AAEA,OAAO,EAAqB,KAAK,eAAe,EAAE,KAAK,eAAe,EAAE,KAAK,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAGxH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAIzE;;GAEG;AACH,MAAM,WAAW,yBAA0B,SAAQ,eAAe;IAChE,2DAA2D;I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;;;;;;;GAiBG;AACH,wBAAgB,eAAe,CAAC,UAAU,GAAE,yBAA8B,GAAG,yBAAyB,CA+DrG"}
@@ -6,39 +6,75 @@ import { watchEnigmaPrices as r } from "@symmio/trading-core";
6
6
  import { useEffect as i, useRef as a, useState as o } from "react";
7
7
  //#region src/price-service/use-enigma-prices.ts
8
8
  function s(s = {}) {
9
- let { chainId: c, enabled: l = !0, onTick: u } = s, d = t(s), f = e(), p = c ?? f, [m, h] = o({}), [g, _] = o("closed"), [v, y] = o(null), b = a(u);
10
- return b.current = u, i(() => {
11
- if (!l) {
12
- _("closed");
9
+ let { chainId: l, enabled: u = !0, onTick: d } = s, f = t(s), p = e(), m = l ?? p, [h, g] = o(() => c(f, m)), _ = h.config === f && h.chainId === m ? h : c(f, m);
10
+ _ !== h && g(_);
11
+ let v = a(d);
12
+ return v.current = d, i(() => {
13
+ let e = !0;
14
+ function t(t) {
15
+ e && g((e) => e.config === f && e.chainId === m ? t(e) : e);
16
+ }
17
+ if (!u) {
18
+ t((e) => ({
19
+ ...e,
20
+ status: "closed"
21
+ }));
13
22
  return;
14
23
  }
15
- y(null);
16
- let e;
24
+ t((e) => ({
25
+ ...e,
26
+ error: null
27
+ }));
28
+ let i;
17
29
  try {
18
- e = r(d, {
19
- chainId: p,
20
- onPrices: (e) => {
21
- h((t) => {
22
- let n = !1, r = { ...t };
23
- for (let t of e) r[t.name] !== t.markPrice && (r[t.name] = t.markPrice, n = !0);
24
- return n ? r : t;
25
- }), b.current?.(e);
30
+ i = r(f, {
31
+ chainId: m,
32
+ onPrices: (n) => {
33
+ e && (t((e) => {
34
+ let t = !1, r = { ...e.prices };
35
+ for (let e of n) r[e.name] !== e.markPrice && (r[e.name] = e.markPrice, t = !0);
36
+ return t ? {
37
+ ...e,
38
+ prices: r
39
+ } : e;
40
+ }), v.current?.(n));
26
41
  },
27
- onStatusChange: _,
28
- onError: (e) => y(n(e))
42
+ onStatusChange: (e) => t((t) => ({
43
+ ...t,
44
+ status: e
45
+ })),
46
+ onError: (e) => t((t) => ({
47
+ ...t,
48
+ error: n(e)
49
+ }))
29
50
  });
30
51
  } catch (e) {
31
- y(n(e)), _("closed");
52
+ t((t) => ({
53
+ ...t,
54
+ error: n(e),
55
+ status: "closed"
56
+ }));
32
57
  }
33
- return () => e?.();
58
+ return () => {
59
+ e = !1, i?.();
60
+ };
34
61
  }, [
35
- l,
36
- d,
37
- p
62
+ u,
63
+ f,
64
+ m
38
65
  ]), {
39
- prices: m,
40
- status: g,
41
- error: v
66
+ prices: _.prices,
67
+ status: _.status,
68
+ error: _.error
69
+ };
70
+ }
71
+ function c(e, t) {
72
+ return {
73
+ config: e,
74
+ chainId: t,
75
+ prices: {},
76
+ status: "closed",
77
+ error: null
42
78
  };
43
79
  }
44
80
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"use-enigma-prices.js","names":[],"sources":["../../src/price-service/use-enigma-prices.ts"],"sourcesContent":["\"use client\";\n\nimport { watchEnigmaPrices, type ConfigParameter, type EnigmaPriceTick, type SocketStatus } from \"@symmio/trading-core\";\nimport { useEffect, useRef, 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\";\n\n/**\n * Parameters for {@link useEnigmaPrices}.\n */\nexport interface UseEnigmaPricesParameters extends ConfigParameter {\n /** Target chain id. Defaults to the SDK's active chain. */\n chainId?: number;\n /** Subscribe only when `true`. Default `true`. */\n enabled?: boolean;\n /** Imperative per-tick callback, invoked in addition to map updates. */\n onTick?: (ticks: EnigmaPriceTick[]) => void;\n}\n\n/**\n * Value returned by {@link useEnigmaPrices}.\n */\nexport interface UseEnigmaPricesReturnType {\n /** Latest mark price keyed by symbol name. */\n prices: Record<string, string>;\n /** Live socket status. */\n status: SocketStatus;\n /** Last transport/parse error, normalized, or `null`. */\n error: SymmioRequestError | null;\n}\n\n/**\n * Subscribe to the chain's Enigma lowcap price-service WebSocket.\n *\n * Accumulates the latest `markPrice` per symbol name; updates whenever a new\n * tick arrives. Pass `onTick` to also react imperatively (e.g. push into a\n * non-stateful sink). The subscription is shared across hook instances via the\n * SDK socket pool — multiple `useEnigmaPrices()` mounts cost one connection.\n *\n * @example\n * ```tsx\n * const { prices, status } = useEnigmaPrices();\n * return <span>BTC: {prices[\"BTCUSDT\"] ?? \"—\"} ({status})</span>;\n * ```\n */\nexport function useEnigmaPrices(parameters: UseEnigmaPricesParameters = {}): UseEnigmaPricesReturnType {\n const { chainId, enabled = true, onTick } = parameters;\n const config = useSymmioConfig(parameters);\n const defaultChainId = useSymmioChainId();\n const resolvedChainId = chainId ?? defaultChainId;\n\n const [prices, setPrices] = useState<Record<string, string>>({});\n const [status, setStatus] = useState<SocketStatus>(\"closed\");\n const [error, setError] = useState<SymmioRequestError | null>(null);\n\n const onTickRef = useRef(onTick);\n onTickRef.current = onTick;\n\n useEffect(() => {\n if (!enabled) {\n setStatus(\"closed\");\n return;\n }\n\n setError(null);\n\n let unwatch: (() => void) | undefined;\n try {\n unwatch = watchEnigmaPrices(config, {\n chainId: resolvedChainId,\n onPrices: (ticks) => {\n setPrices((prev) => {\n let mutated = false;\n const next = { ...prev };\n for (const tick of ticks) {\n if (next[tick.name] !== tick.markPrice) {\n next[tick.name] = tick.markPrice;\n mutated = true;\n }\n }\n return mutated ? next : prev;\n });\n onTickRef.current?.(ticks);\n },\n onStatusChange: setStatus,\n onError: (err) => setError(normalizeSymmError(err)),\n });\n } catch (err) {\n setError(normalizeSymmError(err));\n setStatus(\"closed\");\n }\n\n return () => unwatch?.();\n }, [enabled, config, resolvedChainId]);\n\n return { prices, status, error };\n}\n"],"mappings":";;;;;;;AA+CA,SAAgB,EAAgB,IAAwC,CAAC,GAA8B;CACrG,IAAM,EAAE,YAAS,aAAU,IAAM,cAAW,GACtC,IAAS,EAAgB,CAAU,GACnC,IAAiB,EAAiB,GAClC,IAAkB,KAAW,GAE7B,CAAC,GAAQ,KAAa,EAAiC,CAAC,CAAC,GACzD,CAAC,GAAQ,KAAa,EAAuB,QAAQ,GACrD,CAAC,GAAO,KAAY,EAAoC,IAAI,GAE5D,IAAY,EAAO,CAAM;CAwC/B,OAvCA,EAAU,UAAU,GAEpB,QAAgB;EACd,IAAI,CAAC,GAAS;GACZ,EAAU,QAAQ;GAClB;EACF;EAEA,EAAS,IAAI;EAEb,IAAI;EACJ,IAAI;GACF,IAAU,EAAkB,GAAQ;IAClC,SAAS;IACT,WAAW,MAAU;KAYnB,AAXA,GAAW,MAAS;MAClB,IAAI,IAAU,IACR,IAAO,EAAE,GAAG,EAAK;MACvB,KAAK,IAAM,KAAQ,GACjB,AAAI,EAAK,EAAK,UAAU,EAAK,cAC3B,EAAK,EAAK,QAAQ,EAAK,WACvB,IAAU;MAGd,OAAO,IAAU,IAAO;KAC1B,CAAC,GACD,EAAU,UAAU,CAAK;IAC3B;IACA,gBAAgB;IAChB,UAAU,MAAQ,EAAS,EAAmB,CAAG,CAAC;GACpD,CAAC;EACH,SAAS,GAAK;GAEZ,AADA,EAAS,EAAmB,CAAG,CAAC,GAChC,EAAU,QAAQ;EACpB;EAEA,aAAa,IAAU;CACzB,GAAG;EAAC;EAAS;EAAQ;CAAe,CAAC,GAE9B;EAAE;EAAQ;EAAQ;CAAM;AACjC"}
1
+ {"version":3,"file":"use-enigma-prices.js","names":[],"sources":["../../src/price-service/use-enigma-prices.ts"],"sourcesContent":["\"use client\";\n\nimport {\n watchEnigmaPrices,\n type Config,\n type ConfigParameter,\n type EnigmaPriceTick,\n type SocketStatus,\n} from \"@symmio/trading-core\";\nimport { useEffect, useRef, 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\";\n\n/**\n * Parameters for {@link useEnigmaPrices}.\n */\nexport interface UseEnigmaPricesParameters extends ConfigParameter {\n /** Target chain id. Defaults to the SDK's active chain. */\n chainId?: number;\n /** Subscribe only when `true`. Default `true`. */\n enabled?: boolean;\n /** Imperative per-tick callback, invoked in addition to map updates. */\n onTick?: (ticks: EnigmaPriceTick[]) => void;\n}\n\n/**\n * Value returned by {@link useEnigmaPrices}.\n */\nexport interface UseEnigmaPricesReturnType {\n /** Latest mark price keyed by symbol name. */\n prices: Record<string, string>;\n /** Live socket status. */\n status: SocketStatus;\n /** Last transport/parse error, normalized, or `null`. */\n error: SymmioRequestError | null;\n}\n\n/**\n * Subscribe to the chain's Enigma lowcap price-service WebSocket.\n *\n * Accumulates the latest `markPrice` per symbol name; updates whenever a new\n * tick arrives. Pass `onTick` to also react imperatively (e.g. push into a\n * non-stateful sink). The subscription is shared across hook instances via the\n * SDK socket pool — multiple `useEnigmaPrices()` mounts cost one connection.\n *\n * Prices, status and errors reset when the Config instance or resolved chain\n * changes. Reconnects and stopping/restarting the same target retain prices.\n * Callbacks from a disposed subscription are ignored.\n *\n * @example\n * ```tsx\n * const { prices, status } = useEnigmaPrices();\n * return <span>BTC: {prices[\"BTCUSDT\"] ?? \"—\"} ({status})</span>;\n * ```\n */\nexport function useEnigmaPrices(parameters: UseEnigmaPricesParameters = {}): UseEnigmaPricesReturnType {\n const { chainId, enabled = true, onTick } = parameters;\n const config = useSymmioConfig(parameters);\n const defaultChainId = useSymmioChainId();\n const resolvedChainId = chainId ?? defaultChainId;\n\n const [state, setState] = useState<PriceState>(() => emptyPriceState(config, resolvedChainId));\n // Reset during render so consumers never commit a previous deployment's prices.\n const current =\n state.config === config && state.chainId === resolvedChainId ? state : emptyPriceState(config, resolvedChainId);\n if (current !== state) setState(current);\n\n const onTickRef = useRef(onTick);\n onTickRef.current = onTick;\n\n useEffect(() => {\n let active = true;\n function update(updater: (previous: PriceState) => PriceState) {\n if (!active) return;\n setState((previous) =>\n previous.config === config && previous.chainId === resolvedChainId ? updater(previous) : previous,\n );\n }\n\n if (!enabled) {\n update((previous) => ({ ...previous, status: \"closed\" }));\n return;\n }\n\n update((previous) => ({ ...previous, error: null }));\n let unwatch: (() => void) | undefined;\n try {\n unwatch = watchEnigmaPrices(config, {\n chainId: resolvedChainId,\n onPrices: (ticks) => {\n if (!active) return;\n update((previous) => {\n let mutated = false;\n const prices = { ...previous.prices };\n for (const tick of ticks) {\n if (prices[tick.name] !== tick.markPrice) {\n prices[tick.name] = tick.markPrice;\n mutated = true;\n }\n }\n return mutated ? { ...previous, prices } : previous;\n });\n onTickRef.current?.(ticks);\n },\n onStatusChange: (status) => update((previous) => ({ ...previous, status })),\n onError: (error) => update((previous) => ({ ...previous, error: normalizeSymmError(error) })),\n });\n } catch (error) {\n update((previous) => ({ ...previous, error: normalizeSymmError(error), status: \"closed\" }));\n }\n\n return () => {\n active = false;\n unwatch?.();\n };\n }, [enabled, config, resolvedChainId]);\n\n return { prices: current.prices, status: current.status, error: current.error };\n}\n\ninterface PriceState extends UseEnigmaPricesReturnType {\n config: Config;\n chainId: number;\n}\n\nfunction emptyPriceState(config: Config, chainId: number): PriceState {\n return { config, chainId, prices: {}, status: \"closed\", error: null };\n}\n"],"mappings":";;;;;;;AAyDA,SAAgB,EAAgB,IAAwC,CAAC,GAA8B;CACrG,IAAM,EAAE,YAAS,aAAU,IAAM,cAAW,GACtC,IAAS,EAAgB,CAAU,GACnC,IAAiB,EAAiB,GAClC,IAAkB,KAAW,GAE7B,CAAC,GAAO,KAAY,QAA2B,EAAgB,GAAQ,CAAe,CAAC,GAEvF,IACJ,EAAM,WAAW,KAAU,EAAM,YAAY,IAAkB,IAAQ,EAAgB,GAAQ,CAAe;CAChH,AAAI,MAAY,KAAO,EAAS,CAAO;CAEvC,IAAM,IAAY,EAAO,CAAM;CAkD/B,OAjDA,EAAU,UAAU,GAEpB,QAAgB;EACd,IAAI,IAAS;EACb,SAAS,EAAO,GAA+C;GACxD,KACL,GAAU,MACR,EAAS,WAAW,KAAU,EAAS,YAAY,IAAkB,EAAQ,CAAQ,IAAI,CAC3F;EACF;EAEA,IAAI,CAAC,GAAS;GACZ,GAAQ,OAAc;IAAE,GAAG;IAAU,QAAQ;GAAS,EAAE;GACxD;EACF;EAEA,GAAQ,OAAc;GAAE,GAAG;GAAU,OAAO;EAAK,EAAE;EACnD,IAAI;EACJ,IAAI;GACF,IAAU,EAAkB,GAAQ;IAClC,SAAS;IACT,WAAW,MAAU;KACd,MACL,GAAQ,MAAa;MACnB,IAAI,IAAU,IACR,IAAS,EAAE,GAAG,EAAS,OAAO;MACpC,KAAK,IAAM,KAAQ,GACjB,AAAI,EAAO,EAAK,UAAU,EAAK,cAC7B,EAAO,EAAK,QAAQ,EAAK,WACzB,IAAU;MAGd,OAAO,IAAU;OAAE,GAAG;OAAU;MAAO,IAAI;KAC7C,CAAC,GACD,EAAU,UAAU,CAAK;IAC3B;IACA,iBAAiB,MAAW,GAAQ,OAAc;KAAE,GAAG;KAAU;IAAO,EAAE;IAC1E,UAAU,MAAU,GAAQ,OAAc;KAAE,GAAG;KAAU,OAAO,EAAmB,CAAK;IAAE,EAAE;GAC9F,CAAC;EACH,SAAS,GAAO;GACd,GAAQ,OAAc;IAAE,GAAG;IAAU,OAAO,EAAmB,CAAK;IAAG,QAAQ;GAAS,EAAE;EAC5F;EAEA,aAAa;GAEX,AADA,IAAS,IACT,IAAU;EACZ;CACF,GAAG;EAAC;EAAS;EAAQ;CAAe,CAAC,GAE9B;EAAE,QAAQ,EAAQ;EAAQ,QAAQ,EAAQ;EAAQ,OAAO,EAAQ;CAAM;AAChF;AAOA,SAAS,EAAgB,GAAgB,GAA6B;CACpE,OAAO;EAAE;EAAQ;EAAS,QAAQ,CAAC;EAAG,QAAQ;EAAU,OAAO;CAAK;AACtE"}
@@ -10,7 +10,7 @@ import { useMutation as o, useQueryClient as s } from "@tanstack/react-query";
10
10
  function c(c = {}) {
11
11
  let l = t(c), u = e(), d = s(), f = a(l), p = r((e) => e.markConfirming);
12
12
  return o({
13
- mutationKey: f.mutationKey,
13
+ ...f,
14
14
  mutationFn: async (e) => {
15
15
  try {
16
16
  return await f.mutationFn({
@@ -1 +1 @@
1
- {"version":3,"file":"use-delete-quote-tpsl.js","names":[],"sources":["../../src/tpsl/use-delete-quote-tpsl.ts"],"sourcesContent":["\"use client\";\n\nimport {\n deleteQuoteTpSlMutationOptions,\n type ConfigParameter,\n type DeleteQuoteTpSlParameters,\n type DeleteQuoteTpSlReturnType,\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 { invalidateTpSlReads } from \"./invalidate-tpsl\";\nimport { useTpSlStore } from \"./tpsl-store\";\n\n/** Parameters for {@link useDeleteQuoteTpSl}. */\nexport type UseDeleteQuoteTpSlParameters = ConfigParameter;\n\n/** Return type of {@link useDeleteQuoteTpSl}. */\nexport type UseDeleteQuoteTpSlReturnType = UseMutationResult<\n DeleteQuoteTpSlReturnType,\n SymmioRequestError,\n DeleteQuoteTpSlParameters\n>;\n\n/**\n * Cancel a live TP or SL by its `cohQuoteId`. Signs an EIP-712 delete message\n * with the session-key wallet and calls `DELETE /api/v5/`. On 200 the target\n * side is marked `\"confirming\"` in the shared TP/SL store; the WS `cancel`\n * report flips it to `\"canceled\"` via `applyNotification`.\n */\nexport function useDeleteQuoteTpSl(parameters: UseDeleteQuoteTpSlParameters = {}): UseDeleteQuoteTpSlReturnType {\n const config = useSymmioConfig(parameters);\n const chainId = useSymmioChainId();\n const queryClient = useQueryClient();\n const base = deleteQuoteTpSlMutationOptions(config);\n const markConfirming = useTpSlStore((state) => state.markConfirming);\n\n return useMutation<DeleteQuoteTpSlReturnType, SymmioRequestError, DeleteQuoteTpSlParameters>({\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 // `intent: \"cancel\"` — this side is waiting to disappear, so an empty\n // refetch confirms it instead of being held off as a pending write.\n if (variables.conditionalOrderType === \"take_profit\") {\n markConfirming(variables.quoteId, \"tp\", { intent: \"cancel\" });\n }\n if (variables.conditionalOrderType === \"stop_loss\") {\n markConfirming(variables.quoteId, \"sl\", { intent: \"cancel\" });\n }\n void invalidateTpSlReads(queryClient, [variables.quoteId]);\n },\n });\n}\n"],"mappings":";;;;;;;;;AAgCA,SAAgB,EAAmB,IAA2C,CAAC,GAAiC;CAC9G,IAAM,IAAS,EAAgB,CAAU,GACnC,IAAU,EAAiB,GAC3B,IAAc,EAAe,GAC7B,IAAO,EAA+B,CAAM,GAC5C,IAAiB,GAAc,MAAU,EAAM,cAAc;CAEnE,OAAO,EAAsF;EAC3F,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;GASjC,AANI,EAAU,yBAAyB,iBACrC,EAAe,EAAU,SAAS,MAAM,EAAE,QAAQ,SAAS,CAAC,GAE1D,EAAU,yBAAyB,eACrC,EAAe,EAAU,SAAS,MAAM,EAAE,QAAQ,SAAS,CAAC,GAE9D,EAAyB,GAAa,CAAC,EAAU,OAAO,CAAC;EAC3D;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"use-delete-quote-tpsl.js","names":[],"sources":["../../src/tpsl/use-delete-quote-tpsl.ts"],"sourcesContent":["\"use client\";\n\nimport {\n deleteQuoteTpSlMutationOptions,\n type ConfigParameter,\n type DeleteQuoteTpSlParameters,\n type DeleteQuoteTpSlReturnType,\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 { invalidateTpSlReads } from \"./invalidate-tpsl\";\nimport { useTpSlStore } from \"./tpsl-store\";\n\n/** Parameters for {@link useDeleteQuoteTpSl}. */\nexport type UseDeleteQuoteTpSlParameters = ConfigParameter;\n\n/** Return type of {@link useDeleteQuoteTpSl}. */\nexport type UseDeleteQuoteTpSlReturnType = UseMutationResult<\n DeleteQuoteTpSlReturnType,\n SymmioRequestError,\n DeleteQuoteTpSlParameters\n>;\n\n/**\n * Cancel a live TP or SL by its `cohQuoteId`. Signs an EIP-712 delete message\n * with the session-key wallet and calls `DELETE /api/v5/`. On 200 the target\n * side is marked `\"confirming\"` in the shared TP/SL store; the WS `cancel`\n * report flips it to `\"canceled\"` via `applyNotification`.\n */\nexport function useDeleteQuoteTpSl(parameters: UseDeleteQuoteTpSlParameters = {}): UseDeleteQuoteTpSlReturnType {\n const config = useSymmioConfig(parameters);\n const chainId = useSymmioChainId();\n const queryClient = useQueryClient();\n const base = deleteQuoteTpSlMutationOptions(config);\n const markConfirming = useTpSlStore((state) => state.markConfirming);\n\n return useMutation<DeleteQuoteTpSlReturnType, SymmioRequestError, DeleteQuoteTpSlParameters>({\n ...base,\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 // `intent: \"cancel\"` — this side is waiting to disappear, so an empty\n // refetch confirms it instead of being held off as a pending write.\n if (variables.conditionalOrderType === \"take_profit\") {\n markConfirming(variables.quoteId, \"tp\", { intent: \"cancel\" });\n }\n if (variables.conditionalOrderType === \"stop_loss\") {\n markConfirming(variables.quoteId, \"sl\", { intent: \"cancel\" });\n }\n void invalidateTpSlReads(queryClient, [variables.quoteId]);\n },\n });\n}\n"],"mappings":";;;;;;;;;AAgCA,SAAgB,EAAmB,IAA2C,CAAC,GAAiC;CAC9G,IAAM,IAAS,EAAgB,CAAU,GACnC,IAAU,EAAiB,GAC3B,IAAc,EAAe,GAC7B,IAAO,EAA+B,CAAM,GAC5C,IAAiB,GAAc,MAAU,EAAM,cAAc;CAEnE,OAAO,EAAsF;EAC3F,GAAG;EACH,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;GASjC,AANI,EAAU,yBAAyB,iBACrC,EAAe,EAAU,SAAS,MAAM,EAAE,QAAQ,SAAS,CAAC,GAE1D,EAAU,yBAAyB,eACrC,EAAe,EAAU,SAAS,MAAM,EAAE,QAAQ,SAAS,CAAC,GAE9D,EAAyB,GAAa,CAAC,EAAU,OAAO,CAAC;EAC3D;CACF,CAAC;AACH"}
@@ -10,7 +10,7 @@ import { useMutation as o, useQueryClient as s } from "@tanstack/react-query";
10
10
  function c(c = {}) {
11
11
  let l = t(c), u = e(), d = s(), f = a(l), p = r((e) => e.markConfirming);
12
12
  return o({
13
- mutationKey: f.mutationKey,
13
+ ...f,
14
14
  mutationFn: async (e) => {
15
15
  try {
16
16
  return await f.mutationFn({
@@ -1 +1 @@
1
- {"version":3,"file":"use-set-quote-tpsl.js","names":[],"sources":["../../src/tpsl/use-set-quote-tpsl.ts"],"sourcesContent":["\"use client\";\n\nimport {\n setQuoteTpSlMutationOptions,\n type ConfigParameter,\n type SetQuoteTpSlParameters,\n type SetQuoteTpSlReturnType,\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 { invalidateTpSlReads } from \"./invalidate-tpsl\";\nimport { useTpSlStore } from \"./tpsl-store\";\n\n/** Parameters for {@link useSetQuoteTpSl}. */\nexport type UseSetQuoteTpSlParameters = ConfigParameter;\n\n/** Return type of {@link useSetQuoteTpSl}. */\nexport type UseSetQuoteTpSlReturnType = UseMutationResult<\n SetQuoteTpSlReturnType,\n SymmioRequestError,\n SetQuoteTpSlParameters\n>;\n\n/**\n * Submit a TP/SL order for one quote. Signs an EIP-712 message with the\n * session-key wallet and POSTs to the handler.\n *\n * State machine (per side):\n * 1. `pending` — POST in flight (`mutation.isPending`).\n * 2. `confirming` — POST returned 200; the store's `markConfirming` sets\n * `tp/slState` to `\"confirming\"` and seeds the target trigger price so\n * the UI can render it immediately.\n * 3. `new` — Confirmed. The handler's live `report` (`applyNotification`)\n * resolves the side first when the socket is connected; a refetch of the\n * quote's TP/SL read on success is the authoritative backstop, so the box\n * resolves out of `confirming` even when that frame is missed.\n */\nexport function useSetQuoteTpSl(parameters: UseSetQuoteTpSlParameters = {}): UseSetQuoteTpSlReturnType {\n const config = useSymmioConfig(parameters);\n const chainId = useSymmioChainId();\n const queryClient = useQueryClient();\n const base = setQuoteTpSlMutationOptions(config);\n const markConfirming = useTpSlStore((state) => state.markConfirming);\n\n return useMutation<SetQuoteTpSlReturnType, SymmioRequestError, SetQuoteTpSlParameters>({\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 if (variables.tp) {\n markConfirming(variables.quoteId, \"tp\", {\n price: variables.tp.triggerPrice,\n pricePrecision: variables.pricePrecision,\n priceType: variables.tp.priceType,\n cohQuoteId: result.cohQuoteId,\n });\n }\n if (variables.sl) {\n markConfirming(variables.quoteId, \"sl\", {\n price: variables.sl.triggerPrice,\n pricePrecision: variables.pricePrecision,\n priceType: variables.sl.priceType,\n cohQuoteId: result.cohQuoteId,\n });\n }\n void invalidateTpSlReads(queryClient, [variables.quoteId]);\n },\n });\n}\n"],"mappings":";;;;;;;;;AAwCA,SAAgB,EAAgB,IAAwC,CAAC,GAA8B;CACrG,IAAM,IAAS,EAAgB,CAAU,GACnC,IAAU,EAAiB,GAC3B,IAAc,EAAe,GAC7B,IAAO,EAA4B,CAAM,GACzC,IAAiB,GAAc,MAAU,EAAM,cAAc;CAEnE,OAAO,EAAgF;EACrF,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,GAAQ,MAAc;GAiBhC,AAhBI,EAAU,MACZ,EAAe,EAAU,SAAS,MAAM;IACtC,OAAO,EAAU,GAAG;IACpB,gBAAgB,EAAU;IAC1B,WAAW,EAAU,GAAG;IACxB,YAAY,EAAO;GACrB,CAAC,GAEC,EAAU,MACZ,EAAe,EAAU,SAAS,MAAM;IACtC,OAAO,EAAU,GAAG;IACpB,gBAAgB,EAAU;IAC1B,WAAW,EAAU,GAAG;IACxB,YAAY,EAAO;GACrB,CAAC,GAEH,EAAyB,GAAa,CAAC,EAAU,OAAO,CAAC;EAC3D;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"use-set-quote-tpsl.js","names":[],"sources":["../../src/tpsl/use-set-quote-tpsl.ts"],"sourcesContent":["\"use client\";\n\nimport {\n setQuoteTpSlMutationOptions,\n type ConfigParameter,\n type SetQuoteTpSlParameters,\n type SetQuoteTpSlReturnType,\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 { invalidateTpSlReads } from \"./invalidate-tpsl\";\nimport { useTpSlStore } from \"./tpsl-store\";\n\n/** Parameters for {@link useSetQuoteTpSl}. */\nexport type UseSetQuoteTpSlParameters = ConfigParameter;\n\n/** Return type of {@link useSetQuoteTpSl}. */\nexport type UseSetQuoteTpSlReturnType = UseMutationResult<\n SetQuoteTpSlReturnType,\n SymmioRequestError,\n SetQuoteTpSlParameters\n>;\n\n/**\n * Submit a TP/SL order for one quote. Signs an EIP-712 message with the\n * session-key wallet and POSTs to the handler.\n *\n * State machine (per side):\n * 1. `pending` — POST in flight (`mutation.isPending`).\n * 2. `confirming` — POST returned 200; the store's `markConfirming` sets\n * `tp/slState` to `\"confirming\"` and seeds the target trigger price so\n * the UI can render it immediately.\n * 3. `new` — Confirmed. The handler's live `report` (`applyNotification`)\n * resolves the side first when the socket is connected; a refetch of the\n * quote's TP/SL read on success is the authoritative backstop, so the box\n * resolves out of `confirming` even when that frame is missed.\n */\nexport function useSetQuoteTpSl(parameters: UseSetQuoteTpSlParameters = {}): UseSetQuoteTpSlReturnType {\n const config = useSymmioConfig(parameters);\n const chainId = useSymmioChainId();\n const queryClient = useQueryClient();\n const base = setQuoteTpSlMutationOptions(config);\n const markConfirming = useTpSlStore((state) => state.markConfirming);\n\n return useMutation<SetQuoteTpSlReturnType, SymmioRequestError, SetQuoteTpSlParameters>({\n ...base,\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 if (variables.tp) {\n markConfirming(variables.quoteId, \"tp\", {\n price: variables.tp.triggerPrice,\n pricePrecision: variables.pricePrecision,\n priceType: variables.tp.priceType,\n cohQuoteId: result.cohQuoteId,\n });\n }\n if (variables.sl) {\n markConfirming(variables.quoteId, \"sl\", {\n price: variables.sl.triggerPrice,\n pricePrecision: variables.pricePrecision,\n priceType: variables.sl.priceType,\n cohQuoteId: result.cohQuoteId,\n });\n }\n void invalidateTpSlReads(queryClient, [variables.quoteId]);\n },\n });\n}\n"],"mappings":";;;;;;;;;AAwCA,SAAgB,EAAgB,IAAwC,CAAC,GAA8B;CACrG,IAAM,IAAS,EAAgB,CAAU,GACnC,IAAU,EAAiB,GAC3B,IAAc,EAAe,GAC7B,IAAO,EAA4B,CAAM,GACzC,IAAiB,GAAc,MAAU,EAAM,cAAc;CAEnE,OAAO,EAAgF;EACrF,GAAG;EACH,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,GAAQ,MAAc;GAiBhC,AAhBI,EAAU,MACZ,EAAe,EAAU,SAAS,MAAM;IACtC,OAAO,EAAU,GAAG;IACpB,gBAAgB,EAAU;IAC1B,WAAW,EAAU,GAAG;IACxB,YAAY,EAAO;GACrB,CAAC,GAEC,EAAU,MACZ,EAAe,EAAU,SAAS,MAAM;IACtC,OAAO,EAAU,GAAG;IACpB,gBAAgB,EAAU;IAC1B,WAAW,EAAU,GAAG;IACxB,YAAY,EAAO;GACrB,CAAC,GAEH,EAAyB,GAAa,CAAC,EAAU,OAAO,CAAC;EAC3D;CACF,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@symmio/trading-react",
3
- "version": "4.2.0",
3
+ "version": "4.4.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": "^4.2.0"
94
+ "@symmio/trading-core": "^4.3.0"
95
95
  },
96
96
  "peerDependencies": {
97
97
  "react": "^19.0.0",
@@ -117,8 +117,8 @@
117
117
  "vite-plugin-dts": "^5.0.0",
118
118
  "vitest": "^4.1.10",
119
119
  "wagmi": "^3.4.2",
120
- "@symmio/typescript-config": "^1.0.0",
121
- "@symmio/eslint-config": "^1.0.0"
120
+ "@symmio/eslint-config": "^1.0.0",
121
+ "@symmio/typescript-config": "^1.0.0"
122
122
  },
123
123
  "scripts": {
124
124
  "build": "vite build && node ../../scripts/fix-dts-extensions.mjs dist",