@metamask-previews/perps-controller 24.1.0-preview-4ba073b3a → 25.0.0-preview-e1d02b2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -3
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +44 -6
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.ts +1 -0
- package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
- package/dist/constants/hyperLiquidConfig.js +3 -0
- package/dist/constants/hyperLiquidConfig.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +3 -6
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +404 -196
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +38 -6
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/services/HyperLiquidClientService.d.ts +3 -1
- package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
- package/dist/services/HyperLiquidClientService.js +3 -2
- package/dist/services/HyperLiquidClientService.js.map +1 -1
- package/dist/services/TradingService.d.ts +4 -0
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +7 -2
- package/dist/services/TradingService.js.map +1 -1
- package/dist/types/index.d.ts +5 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/cancelOrders.d.ts.map +1 -1
- package/dist/utils/cancelOrders.js +30 -0
- package/dist/utils/cancelOrders.js.map +1 -1
- package/dist/utils/errorUtils.d.ts +10 -0
- package/dist/utils/errorUtils.d.ts.map +1 -1
- package/dist/utils/errorUtils.js +33 -3
- package/dist/utils/errorUtils.js.map +1 -1
- package/dist/utils/guardedHyperLiquidClient.d.ts +10 -1
- package/dist/utils/guardedHyperLiquidClient.d.ts.map +1 -1
- package/dist/utils/guardedHyperLiquidClient.js +37 -3
- package/dist/utils/guardedHyperLiquidClient.js.map +1 -1
- package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
- package/dist/utils/hyperLiquidValidation.js +4 -2
- package/dist/utils/hyperLiquidValidation.js.map +1 -1
- package/docs/tpsl.md +2 -2
- package/package.json +6 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cancelOrders.d.ts","sourceRoot":"","sources":["../../src/utils/cancelOrders.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"cancelOrders.d.ts","sourceRoot":"","sources":["../../src/utils/cancelOrders.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,kBAAkB,EAClB,kBAAkB,EAClB,aAAa,EACd,MAAM,mBAAmB,CAAC;AAE3B,yEAAyE;AACzE,MAAM,MAAM,eAAe,GACvB;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,GACf;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAChB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,WAAW,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC,CAAA;CAAE,GACrE;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,GACxC;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAoC3C;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,kBAAkB,GACzB,eAAe,CAqBjB;AAED;;;;;;GAMG;AACH,wBAAgB,8BAA8B,CAC5C,QAAQ,EAAE,aAAa,EACvB,SAAS,EAAE,eAAe,GACzB,kBAAkB,GAAG,SAAS,CAiBhC"}
|
|
@@ -1,4 +1,33 @@
|
|
|
1
1
|
import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
|
|
2
|
+
import { isPerpsProviderType } from '../routing/isPerpsProviderType.js';
|
|
3
|
+
/**
|
|
4
|
+
* Reject malformed batch filters at the runtime API boundary.
|
|
5
|
+
*
|
|
6
|
+
* @param params - Batch cancellation request.
|
|
7
|
+
*/
|
|
8
|
+
function assertCancelOrderFilters(params) {
|
|
9
|
+
for (const key of ['orders', 'orderIds', 'symbols']) {
|
|
10
|
+
if (params[key] !== undefined && !Array.isArray(params[key])) {
|
|
11
|
+
throw new Error(PERPS_ERROR_CODES.BATCH_CANCEL_FAILED, {
|
|
12
|
+
cause: new TypeError(`${key} must be an array`),
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const selection = params.orders ?? [];
|
|
17
|
+
for (const order of selection) {
|
|
18
|
+
if (typeof order !== 'object' ||
|
|
19
|
+
order === null ||
|
|
20
|
+
!('providerId' in order) ||
|
|
21
|
+
!isPerpsProviderType(order.providerId) ||
|
|
22
|
+
!('orderId' in order) ||
|
|
23
|
+
typeof order.orderId !== 'string' ||
|
|
24
|
+
!order.orderId.trim()) {
|
|
25
|
+
throw new Error(PERPS_ERROR_CODES.BATCH_CANCEL_FAILED, {
|
|
26
|
+
cause: new TypeError('Each qualified order requires a venue and order ID'),
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
2
31
|
/**
|
|
3
32
|
* Resolve cancel-all > scoped orders > bare IDs > symbols in one place.
|
|
4
33
|
*
|
|
@@ -6,6 +35,7 @@ import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
|
|
|
6
35
|
* @returns The winning selector, including explicit empty selections.
|
|
7
36
|
*/
|
|
8
37
|
export function resolveCancelSelection(params) {
|
|
38
|
+
assertCancelOrderFilters(params);
|
|
9
39
|
if (params.cancelAll === true) {
|
|
10
40
|
return { kind: 'all' };
|
|
11
41
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cancelOrders.js","sourceRoot":"","sources":["../../src/utils/cancelOrders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBA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ACD,MAAM,UAAU,GACd,QAAQ,CAAC,cAAc,EAAE,EAAE,CAAC,MAAM;QAClC,CAAC,QAAQ,CAAC,UAAU,KAAK,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjD,IAAI,UAAU,IAAI,CAAC,EAAE,CAAC;QACpB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO;QACL,OAAO,EAAE,KAAK;QACd,YAAY,EAAE,CAAC;QACf,YAAY,EAAE,CAAC;QACf,OAAO,EAAE,EAAE;QACX,KAAK,EAAE,iBAAiB,CAAC,uBAAuB;KACjD,CAAC;AACJ,CAAC","sourcesContent":["import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport { isPerpsProviderType } from '../routing/isPerpsProviderType.js';\nimport type {\n CancelOrdersParams,\n CancelOrdersResult,\n PerpsProvider,\n} from '../types/index.js';\n\n/** Normalized cancel selector; empty filters never become cancel-all. */\nexport type CancelSelection =\n | { kind: 'all' }\n | { kind: 'none' }\n | { kind: 'orders'; orders: NonNullable<CancelOrdersParams['orders']> }\n | { kind: 'orderIds'; orderIds: string[] }\n | { kind: 'symbols'; symbols: string[] };\n\n/**\n * Reject malformed batch filters at the runtime API boundary.\n *\n * @param params - Batch cancellation request.\n */\nfunction assertCancelOrderFilters(params: CancelOrdersParams): void {\n for (const key of ['orders', 'orderIds', 'symbols'] as const) {\n if (params[key] !== undefined && !Array.isArray(params[key])) {\n throw new Error(PERPS_ERROR_CODES.BATCH_CANCEL_FAILED, {\n cause: new TypeError(`${key} must be an array`),\n });\n }\n }\n\n const selection: readonly unknown[] = params.orders ?? [];\n for (const order of selection) {\n if (\n typeof order !== 'object' ||\n order === null ||\n !('providerId' in order) ||\n !isPerpsProviderType(order.providerId) ||\n !('orderId' in order) ||\n typeof order.orderId !== 'string' ||\n !order.orderId.trim()\n ) {\n throw new Error(PERPS_ERROR_CODES.BATCH_CANCEL_FAILED, {\n cause: new TypeError(\n 'Each qualified order requires a venue and order ID',\n ),\n });\n }\n }\n}\n\n/**\n * Resolve cancel-all > scoped orders > bare IDs > symbols in one place.\n *\n * @param params - The caller's cancellation selectors.\n * @returns The winning selector, including explicit empty selections.\n */\nexport function resolveCancelSelection(\n params: CancelOrdersParams,\n): CancelSelection {\n assertCancelOrderFilters(params);\n if (params.cancelAll === true) {\n return { kind: 'all' };\n }\n if (params.orders !== undefined) {\n return params.orders.length === 0\n ? { kind: 'none' }\n : { kind: 'orders', orders: params.orders };\n }\n if (params.orderIds !== undefined) {\n return params.orderIds.length === 0\n ? { kind: 'none' }\n : { kind: 'orderIds', orderIds: params.orderIds };\n }\n if (params.symbols !== undefined) {\n return params.symbols.length === 0\n ? { kind: 'none' }\n : { kind: 'symbols', symbols: params.symbols };\n }\n return { kind: 'all' };\n}\n\n/**\n * Refuse legacy selectors that cannot identify one execution venue.\n *\n * @param provider - The resolved execution provider.\n * @param selection - The normalized cancel selection.\n * @returns A stable refusal, or undefined for an unambiguous selection.\n */\nexport function getUnroutedCancelOrdersRefusal(\n provider: PerpsProvider,\n selection: CancelSelection,\n): CancelOrdersResult | undefined {\n if (selection.kind !== 'orderIds' && selection.kind !== 'symbols') {\n return undefined;\n }\n const venueCount =\n provider.getProviderIds?.().length ??\n (provider.protocolId === 'aggregated' ? 2 : 1);\n if (venueCount <= 1) {\n return undefined;\n }\n return {\n success: false,\n successCount: 0,\n failureCount: 0,\n results: [],\n error: PERPS_ERROR_CODES.PROVIDER_ROUTE_REQUIRED,\n };\n}\n"]}
|
|
@@ -48,6 +48,15 @@ export declare function isHyperLiquidUserNotFoundError(error: unknown): boolean;
|
|
|
48
48
|
* @returns True if the error indicates multi-sig signing is required.
|
|
49
49
|
*/
|
|
50
50
|
export declare function isHyperLiquidMultiSigRequiredError(error: unknown): boolean;
|
|
51
|
+
declare const HYPERLIQUID_WRITE_GUARD_CODES: readonly ["EXCHANGE_MULTI_SIG_REQUIRED", "PROVIDER_LIFECYCLE_STALE", "PROVIDER_NOT_AVAILABLE", "TPSL_UPDATE_FAILED"];
|
|
52
|
+
type HyperLiquidWriteGuardCode = (typeof HYPERLIQUID_WRITE_GUARD_CODES)[number];
|
|
53
|
+
/**
|
|
54
|
+
* Read a local write refusal, including one the SDK wrapped while signing.
|
|
55
|
+
*
|
|
56
|
+
* @param error - The caught failure.
|
|
57
|
+
* @returns The local refusal code, when present.
|
|
58
|
+
*/
|
|
59
|
+
export declare function getHyperLiquidWriteGuardCode(error: unknown): HyperLiquidWriteGuardCode | undefined;
|
|
51
60
|
/**
|
|
52
61
|
* Normalize a Hyperliquid failure into the stable error contract exposed to
|
|
53
62
|
* clients.
|
|
@@ -65,4 +74,5 @@ export declare function isHyperLiquidMultiSigRequiredError(error: unknown): bool
|
|
|
65
74
|
* @returns A structured error safe to expose through provider results.
|
|
66
75
|
*/
|
|
67
76
|
export declare function normalizeHyperLiquidError(error: unknown): PerpsControllerError;
|
|
77
|
+
export {};
|
|
68
78
|
//# sourceMappingURL=errorUtils.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errorUtils.d.ts","sourceRoot":"","sources":["../../src/utils/errorUtils.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAqGpD;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CASpD;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAK5D;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,KAAK,CAkBnE;AAED;;;;;;;;GAQG;AACH,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAKtE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,kCAAkC,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,
|
|
1
|
+
{"version":3,"file":"errorUtils.d.ts","sourceRoot":"","sources":["../../src/utils/errorUtils.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAqGpD;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CASpD;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAK5D;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,KAAK,CAkBnE;AAED;;;;;;;;GAQG;AACH,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAKtE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,kCAAkC,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAS1E;AAED,QAAA,MAAM,6BAA6B,sHAOzB,CAAC;AAEX,KAAK,yBAAyB,GAAG,CAAC,OAAO,6BAA6B,CAAC,CAAC,MAAM,CAAC,CAAC;AAEhF;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC1C,KAAK,EAAE,OAAO,GACb,yBAAyB,GAAG,SAAS,CAQvC;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,OAAO,GACb,oBAAoB,CA8CtB"}
|
package/dist/utils/errorUtils.js
CHANGED
|
@@ -171,8 +171,34 @@ export function isHyperLiquidUserNotFoundError(error) {
|
|
|
171
171
|
* @returns True if the error indicates multi-sig signing is required.
|
|
172
172
|
*/
|
|
173
173
|
export function isHyperLiquidMultiSigRequiredError(error) {
|
|
174
|
-
const
|
|
175
|
-
|
|
174
|
+
const cause = ensureError(error);
|
|
175
|
+
const lower = cause.message.toLowerCase();
|
|
176
|
+
return (getHyperLiquidWriteGuardCode(cause) ===
|
|
177
|
+
PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED ||
|
|
178
|
+
lower.includes('multi-sig required') ||
|
|
179
|
+
lower.includes('multisig required'));
|
|
180
|
+
}
|
|
181
|
+
const HYPERLIQUID_WRITE_GUARD_CODES = [
|
|
182
|
+
PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED,
|
|
183
|
+
PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE,
|
|
184
|
+
// Thrown inside signing for a TP/SL replacement. The SDK wraps them, and
|
|
185
|
+
// the public result still has to name the refusal after restoration.
|
|
186
|
+
PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE,
|
|
187
|
+
PERPS_ERROR_CODES.TPSL_UPDATE_FAILED,
|
|
188
|
+
];
|
|
189
|
+
/**
|
|
190
|
+
* Read a local write refusal, including one the SDK wrapped while signing.
|
|
191
|
+
*
|
|
192
|
+
* @param error - The caught failure.
|
|
193
|
+
* @returns The local refusal code, when present.
|
|
194
|
+
*/
|
|
195
|
+
export function getHyperLiquidWriteGuardCode(error) {
|
|
196
|
+
const sdkError = ensureError(error);
|
|
197
|
+
const refusal = sdkError.name === 'AbstractWalletError' ? sdkError.cause : sdkError;
|
|
198
|
+
if (!(refusal instanceof Error)) {
|
|
199
|
+
return undefined;
|
|
200
|
+
}
|
|
201
|
+
return HYPERLIQUID_WRITE_GUARD_CODES.find((code) => code === refusal.message);
|
|
176
202
|
}
|
|
177
203
|
/**
|
|
178
204
|
* Normalize a Hyperliquid failure into the stable error contract exposed to
|
|
@@ -201,7 +227,11 @@ export function normalizeHyperLiquidError(error) {
|
|
|
201
227
|
}
|
|
202
228
|
const cause = ensureError(error, 'normalizeHyperLiquidError');
|
|
203
229
|
let errorCode;
|
|
204
|
-
|
|
230
|
+
const guardCode = getHyperLiquidWriteGuardCode(cause);
|
|
231
|
+
if (guardCode) {
|
|
232
|
+
errorCode = guardCode;
|
|
233
|
+
}
|
|
234
|
+
else if (isHyperLiquidUserNotFoundError(cause)) {
|
|
205
235
|
errorCode = PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND;
|
|
206
236
|
}
|
|
207
237
|
else if (isPerpsErrorCode(cause.message) &&
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errorUtils.js","sourceRoot":"","sources":["../../src/utils/errorUtils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEjE,MAAM,0BAA0B,GAG1B;IACJ,wEAAwE;IACxE;QACE,OAAO,EAAE,kDAAkD;QAC3D,IAAI,EAAE,iBAAiB,CAAC,2BAA2B;KACpD;IACD;QACE,OAAO,EACL,mEAAmE;QACrE,IAAI,EAAE,iBAAiB,CAAC,sBAAsB;KAC/C;IACD;QACE,6EAA6E;QAC7E,0EAA0E;QAC1E,mEAAmE;QACnE,OAAO,EAAE,kEAAkE;QAC3E,IAAI,EAAE,iBAAiB,CAAC,oBAAoB;KAC7C;IACD;QACE,OAAO,EACL,+HAA+H;QACjI,IAAI,EAAE,iBAAiB,CAAC,+BAA+B;KACxD;IACD;QACE,OAAO,EAAE,wCAAwC;QACjD,IAAI,EAAE,iBAAiB,CAAC,2BAA2B;KACpD;IACD;QACE,OAAO,EAAE,0CAA0C;QACnD,IAAI,EAAE,iBAAiB,CAAC,0BAA0B;KACnD;IACD;QACE,OAAO,EAAE,iBAAiB;QAC1B,IAAI,EAAE,iBAAiB,CAAC,sBAAsB;KAC/C;IACD;QACE,OAAO,EAAE,iCAAiC;QAC1C,IAAI,EAAE,iBAAiB,CAAC,cAAc;KACvC;IACD;QACE,OAAO,EAAE,qBAAqB;QAC9B,IAAI,EAAE,iBAAiB,CAAC,kBAAkB;KA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,OAAO,CAAC,CAC5B,EAAE,IAAI,CAAC;IACV,CAAC;IAED,MAAM,cAAc,GAAG,SAAS,IAAI,iBAAiB,CAAC,aAAa,CAAC;IACpE,OAAO,IAAI,oBAAoB,CAC7B,cAAc,EACd,cAAc,EACd;QACE,IAAI,EAAE,cAAc;QACpB,QAAQ,EAAE,aAAa;KACxB,EACD,EAAE,KAAK,EAAE,CACV,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Utility functions for error handling across Perps controller code.\n * Includes generic error helpers and Perps error classification helpers.\n */\nimport { hasProperty } from '@metamask/utils';\n\nimport { PerpsControllerError } from '../errors.js';\nimport type { HyperLiquidErrorDetails } from '../errors.js';\nimport { isPerpsErrorCode, PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport { hasErrorInCauseChain } from '../services/causeChain.js';\n\nconst HYPERLIQUID_ERROR_MAPPINGS: readonly {\n pattern: RegExp;\n code: HyperLiquidErrorDetails['code'];\n}[] = [\n // Keep specific post-only rejections ahead of generic failure patterns.\n {\n pattern: /post only order would have immediately matched/iu,\n code: PERPS_ERROR_CODES.ORDER_POST_ONLY_WOULD_CROSS,\n },\n {\n pattern:\n /only post-only orders allowed immediately after network upgrade/iu,\n code: PERPS_ERROR_CODES.ORDER_POST_ONLY_WINDOW,\n },\n {\n // Hyperliquid cannot distinguish never placed, already cancelled, and filled\n // here. Share this classification with strategy cancels, and do not match\n // \"filled\" alone: a partial fill can still leave an order resting.\n pattern: /never placed|already cancel(?:ed|led)|(?:order|twap) not found/iu,\n code: PERPS_ERROR_CODES.ORDER_NO_LONGER_OPEN,\n },\n {\n pattern:\n /isolated position does not have sufficient margin available to decrease leverage|cannot reduce.*leverage|leverage reduction/iu,\n code: PERPS_ERROR_CODES.ORDER_LEVERAGE_REDUCTION_FAILED,\n },\n {\n pattern: /multi-sig required|multisig required/iu,\n code: PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED,\n },\n {\n pattern: /must deposit before performing actions/iu,\n code: PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND,\n },\n {\n pattern: /invalid nonce/iu,\n code: PERPS_ERROR_CODES.EXCHANGE_INVALID_NONCE,\n },\n {\n pattern: /order must have minimum value/iu,\n code: PERPS_ERROR_CODES.ORDER_SIZE_MIN,\n },\n {\n pattern: /timeout|timed out/iu,\n code: PERPS_ERROR_CODES.CONNECTION_TIMEOUT,\n },\n {\n pattern:\n /service unavailable|temporarily unavailable|\\bstatus(?: code)?\\s*[:=]?\\s*503\\b|\\bhttp(?:\\/\\d(?:\\.\\d)?)?\\s+503\\b/iu,\n code: PERPS_ERROR_CODES.SERVICE_UNAVAILABLE,\n },\n {\n pattern: /network error|fetch failed|connection failed/iu,\n code: PERPS_ERROR_CODES.NETWORK_ERROR,\n },\n {\n pattern: /rate limit|too many .*requests|throttl/iu,\n code: PERPS_ERROR_CODES.RATE_LIMIT_EXCEEDED,\n },\n {\n pattern: /margin available|not enough margin|insufficient margin/iu,\n code: PERPS_ERROR_CODES.INSUFFICIENT_MARGIN,\n },\n {\n // \"builder has insufficient balance\" is the venue's builder-fee refusal,\n // not the user's balance. It stays UNKNOWN_ERROR.\n pattern: /(?<!builder has )insufficient balance|not enough balance/iu,\n code: PERPS_ERROR_CODES.INSUFFICIENT_BALANCE,\n },\n {\n pattern: /reduce only|reduce-only|reduceOnly/iu,\n code: PERPS_ERROR_CODES.REDUCE_ONLY_VIOLATION,\n },\n {\n pattern: /position would flip|would flip position/iu,\n code: PERPS_ERROR_CODES.POSITION_WOULD_FLIP,\n },\n {\n pattern: /no position found/iu,\n code: PERPS_ERROR_CODES.POSITION_NOT_FOUND,\n },\n {\n pattern: /slippage|price moved too much/iu,\n code: PERPS_ERROR_CODES.SLIPPAGE_EXCEEDED,\n },\n {\n pattern:\n /could not immediately match|insufficient liquidity|no liquidity|IOC.*cancel/iu,\n code: PERPS_ERROR_CODES.IOC_CANCEL,\n },\n {\n pattern: /order rejected|rejected order/iu,\n code: PERPS_ERROR_CODES.ORDER_REJECTED,\n },\n];\n\n/**\n * Detects expected cancellation/abort errors that should not be reported to Sentry.\n * These occur during normal navigation or view teardown when in-flight fetch requests\n * are cancelled via AbortController.\n *\n * @param error - The error to check.\n * @returns True if the error is an expected abort/cancellation.\n */\nexport function isAbortError(error: unknown): boolean {\n if (error instanceof Error) {\n return (\n error.name === 'AbortError' ||\n error.message.includes('signal is aborted') ||\n error.message.includes('The operation was aborted')\n );\n }\n return false;\n}\n\n/**\n * Detects keyring-locked errors, including SDK-wrapped errors that preserve the\n * original error in `cause`.\n *\n * @param error - The error to check.\n * @returns True if any error in the cause chain is KEYRING_LOCKED.\n */\nexport function isKeyringLockedError(error: unknown): boolean {\n return hasErrorInCauseChain(\n error,\n (current) => current.message === PERPS_ERROR_CODES.KEYRING_LOCKED,\n );\n}\n\n/**\n * Ensures we have a proper Error object for logging.\n * Converts unknown/string errors to proper Error instances.\n * Handles undefined/null specially for better Sentry context.\n *\n * @param error - The caught error (could be Error, string, or unknown)\n * @param context - Optional context string to help identify the source of the error\n * @returns A proper Error instance\n */\nexport function ensureError(error: unknown, context?: string): Error {\n if (error instanceof Error) {\n return error;\n }\n // Handle undefined/null specifically for better error context\n // e.g. Hyperliquid SDK may reject with undefined when AbortSignal.reason is not set\n if (error === undefined || error === null) {\n const baseMessage = 'Unknown error (no details provided)';\n return new Error(context ? `${baseMessage} [${context}]` : baseMessage);\n }\n if (typeof error === 'string') {\n return new Error(error);\n }\n return new Error(\n typeof error === 'object' && error !== null && hasProperty(error, 'message')\n ? String(error.message)\n : 'Unknown error',\n );\n}\n\n/**\n * Hyperliquid rejects user-scoped exchange writes (`agentSetAbstraction`,\n * `setReferrer`, ...) with this exact message when the\n * wallet has never funded a Hyperliquid account. It is a benign pre-account\n * state, not an error we should forward to Sentry.\n *\n * @param error - The caught error.\n * @returns True if the error matches the Hyperliquid \"user not on chain yet\" rejection.\n */\nexport function isHyperLiquidUserNotFoundError(error: unknown): boolean {\n const lower = ensureError(error).message.toLowerCase();\n return (\n lower.includes('user or api wallet') && lower.includes('does not exist')\n );\n}\n\n/**\n * Hyperliquid rejects every single-signer exchange write for an account that\n * has been converted to multi-sig (`ApiRequestError: Multi-sig required`).\n * MetaMask signs Perps actions with a single agent/user wallet, so this is a\n * permanent account-shape condition rather than a failure we should retry or\n * forward to Sentry. Only the hyphenated spelling has been observed from the\n * venue; the unhyphenated variant is matched defensively.\n *\n * @param error - The caught error.\n * @returns True if the error indicates multi-sig signing is required.\n */\nexport function isHyperLiquidMultiSigRequiredError(error: unknown): boolean {\n const lower = ensureError(error).message.toLowerCase();\n return (\n lower.includes('multi-sig required') || lower.includes('multisig required')\n );\n}\n\n/**\n * Normalize a Hyperliquid failure into the stable error contract exposed to\n * clients.\n *\n * Known venue messages receive actionable codes. Unknown messages are replaced\n * by `UNKNOWN_ERROR`, while every newly normalized error keeps the original\n * failure in `cause` for telemetry and debugging.\n *\n * A `PerpsControllerError` that already carries details is returned as is, as\n * is `PRICE_MOVED`, whose numeric payload is computed locally. Any other\n * structured error without details is tagged with the provider so every\n * Hyperliquid result exposes the same details contract.\n *\n * @param error - Failure thrown by Hyperliquid or its SDK.\n * @returns A structured error safe to expose through provider results.\n */\nexport function normalizeHyperLiquidError(\n error: unknown,\n): PerpsControllerError {\n if (error instanceof PerpsControllerError) {\n const { errorCode: structuredCode } = error;\n if (\n error.errorDetails !== undefined ||\n structuredCode === PERPS_ERROR_CODES.PRICE_MOVED\n ) {\n return error;\n }\n return new PerpsControllerError(\n structuredCode,\n structuredCode,\n { code: structuredCode, provider: 'hyperliquid' },\n { cause: error.cause ?? error },\n );\n }\n\n const cause = ensureError(error, 'normalizeHyperLiquidError');\n let errorCode: HyperLiquidErrorDetails['code'] | undefined;\n\n if (isHyperLiquidUserNotFoundError(cause)) {\n errorCode = PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND;\n } else if (\n isPerpsErrorCode(cause.message) &&\n cause.message !== PERPS_ERROR_CODES.PRICE_MOVED\n ) {\n errorCode = cause.message;\n } else {\n errorCode = HYPERLIQUID_ERROR_MAPPINGS.find(({ pattern }) =>\n pattern.test(cause.message),\n )?.code;\n }\n\n const normalizedCode = errorCode ?? PERPS_ERROR_CODES.UNKNOWN_ERROR;\n return new PerpsControllerError(\n normalizedCode,\n normalizedCode,\n {\n code: normalizedCode,\n provider: 'hyperliquid',\n },\n { cause },\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"errorUtils.js","sourceRoot":"","sources":["../../src/utils/errorUtils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEjE,MAAM,0BAA0B,GAG1B;IACJ,wEAAwE;IACxE;QACE,OAAO,EAAE,kDAAkD;QAC3D,IAAI,EAAE,iBAAiB,CAAC,2BAA2B;KACpD;IACD;QACE,OAAO,EACL,mEAAmE;QACrE,IAAI,EAAE,iBAAiB,CAAC,sBAAsB;KAC/C;IACD;QACE,6EAA6E;QAC7E,0EAA0E;QAC1E,mEAAmE;QACnE,OAAO,EAAE,kEAAkE;QAC3E,IAAI,EAAE,iBAAiB,CAAC,oBAAoB;KAC7C;IACD;QACE,OAAO,EACL,+HAA+H;QACjI,IAAI,EAAE,iBAAiB,CAAC,+BAA+B;KACxD;IACD;QACE,OAAO,EAAE,wCAAwC;QACjD,IAAI,EAAE,iBAAiB,CAAC,2BAA2B;KACpD;IACD;QACE,OAAO,EAAE,0CAA0C;QACnD,IAAI,EAAE,iBAAiB,CAAC,0BAA0B;KACnD;IACD;QACE,OAAO,EAAE,iBAAiB;QAC1B,IAAI,EAAE,iBAAiB,CAAC,sBAAsB;KAC/C;IACD;QACE,OAAO,EAAE,iCAAi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V,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Utility functions for error handling across Perps controller code.\n * Includes generic error helpers and Perps error classification helpers.\n */\nimport { hasProperty } from '@metamask/utils';\n\nimport { PerpsControllerError } from '../errors.js';\nimport type { HyperLiquidErrorDetails } from '../errors.js';\nimport { isPerpsErrorCode, PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport { hasErrorInCauseChain } from '../services/causeChain.js';\n\nconst HYPERLIQUID_ERROR_MAPPINGS: readonly {\n pattern: RegExp;\n code: HyperLiquidErrorDetails['code'];\n}[] = [\n // Keep specific post-only rejections ahead of generic failure patterns.\n {\n pattern: /post only order would have immediately matched/iu,\n code: PERPS_ERROR_CODES.ORDER_POST_ONLY_WOULD_CROSS,\n },\n {\n pattern:\n /only post-only orders allowed immediately after network upgrade/iu,\n code: PERPS_ERROR_CODES.ORDER_POST_ONLY_WINDOW,\n },\n {\n // Hyperliquid cannot distinguish never placed, already cancelled, and filled\n // here. Share this classification with strategy cancels, and do not match\n // \"filled\" alone: a partial fill can still leave an order resting.\n pattern: /never placed|already cancel(?:ed|led)|(?:order|twap) not found/iu,\n code: PERPS_ERROR_CODES.ORDER_NO_LONGER_OPEN,\n },\n {\n pattern:\n /isolated position does not have sufficient margin available to decrease leverage|cannot reduce.*leverage|leverage reduction/iu,\n code: PERPS_ERROR_CODES.ORDER_LEVERAGE_REDUCTION_FAILED,\n },\n {\n pattern: /multi-sig required|multisig required/iu,\n code: PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED,\n },\n {\n pattern: /must deposit before performing actions/iu,\n code: PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND,\n },\n {\n pattern: /invalid nonce/iu,\n code: PERPS_ERROR_CODES.EXCHANGE_INVALID_NONCE,\n },\n {\n pattern: /order must have minimum value/iu,\n code: PERPS_ERROR_CODES.ORDER_SIZE_MIN,\n },\n {\n pattern: /timeout|timed out/iu,\n code: PERPS_ERROR_CODES.CONNECTION_TIMEOUT,\n },\n {\n pattern:\n /service unavailable|temporarily unavailable|\\bstatus(?: code)?\\s*[:=]?\\s*503\\b|\\bhttp(?:\\/\\d(?:\\.\\d)?)?\\s+503\\b/iu,\n code: PERPS_ERROR_CODES.SERVICE_UNAVAILABLE,\n },\n {\n pattern: /network error|fetch failed|connection failed/iu,\n code: PERPS_ERROR_CODES.NETWORK_ERROR,\n },\n {\n pattern: /rate limit|too many .*requests|throttl/iu,\n code: PERPS_ERROR_CODES.RATE_LIMIT_EXCEEDED,\n },\n {\n pattern: /margin available|not enough margin|insufficient margin/iu,\n code: PERPS_ERROR_CODES.INSUFFICIENT_MARGIN,\n },\n {\n // \"builder has insufficient balance\" is the venue's builder-fee refusal,\n // not the user's balance. It stays UNKNOWN_ERROR.\n pattern: /(?<!builder has )insufficient balance|not enough balance/iu,\n code: PERPS_ERROR_CODES.INSUFFICIENT_BALANCE,\n },\n {\n pattern: /reduce only|reduce-only|reduceOnly/iu,\n code: PERPS_ERROR_CODES.REDUCE_ONLY_VIOLATION,\n },\n {\n pattern: /position would flip|would flip position/iu,\n code: PERPS_ERROR_CODES.POSITION_WOULD_FLIP,\n },\n {\n pattern: /no position found/iu,\n code: PERPS_ERROR_CODES.POSITION_NOT_FOUND,\n },\n {\n pattern: /slippage|price moved too much/iu,\n code: PERPS_ERROR_CODES.SLIPPAGE_EXCEEDED,\n },\n {\n pattern:\n /could not immediately match|insufficient liquidity|no liquidity|IOC.*cancel/iu,\n code: PERPS_ERROR_CODES.IOC_CANCEL,\n },\n {\n pattern: /order rejected|rejected order/iu,\n code: PERPS_ERROR_CODES.ORDER_REJECTED,\n },\n];\n\n/**\n * Detects expected cancellation/abort errors that should not be reported to Sentry.\n * These occur during normal navigation or view teardown when in-flight fetch requests\n * are cancelled via AbortController.\n *\n * @param error - The error to check.\n * @returns True if the error is an expected abort/cancellation.\n */\nexport function isAbortError(error: unknown): boolean {\n if (error instanceof Error) {\n return (\n error.name === 'AbortError' ||\n error.message.includes('signal is aborted') ||\n error.message.includes('The operation was aborted')\n );\n }\n return false;\n}\n\n/**\n * Detects keyring-locked errors, including SDK-wrapped errors that preserve the\n * original error in `cause`.\n *\n * @param error - The error to check.\n * @returns True if any error in the cause chain is KEYRING_LOCKED.\n */\nexport function isKeyringLockedError(error: unknown): boolean {\n return hasErrorInCauseChain(\n error,\n (current) => current.message === PERPS_ERROR_CODES.KEYRING_LOCKED,\n );\n}\n\n/**\n * Ensures we have a proper Error object for logging.\n * Converts unknown/string errors to proper Error instances.\n * Handles undefined/null specially for better Sentry context.\n *\n * @param error - The caught error (could be Error, string, or unknown)\n * @param context - Optional context string to help identify the source of the error\n * @returns A proper Error instance\n */\nexport function ensureError(error: unknown, context?: string): Error {\n if (error instanceof Error) {\n return error;\n }\n // Handle undefined/null specifically for better error context\n // e.g. Hyperliquid SDK may reject with undefined when AbortSignal.reason is not set\n if (error === undefined || error === null) {\n const baseMessage = 'Unknown error (no details provided)';\n return new Error(context ? `${baseMessage} [${context}]` : baseMessage);\n }\n if (typeof error === 'string') {\n return new Error(error);\n }\n return new Error(\n typeof error === 'object' && error !== null && hasProperty(error, 'message')\n ? String(error.message)\n : 'Unknown error',\n );\n}\n\n/**\n * Hyperliquid rejects user-scoped exchange writes (`agentSetAbstraction`,\n * `setReferrer`, ...) with this exact message when the\n * wallet has never funded a Hyperliquid account. It is a benign pre-account\n * state, not an error we should forward to Sentry.\n *\n * @param error - The caught error.\n * @returns True if the error matches the Hyperliquid \"user not on chain yet\" rejection.\n */\nexport function isHyperLiquidUserNotFoundError(error: unknown): boolean {\n const lower = ensureError(error).message.toLowerCase();\n return (\n lower.includes('user or api wallet') && lower.includes('does not exist')\n );\n}\n\n/**\n * Hyperliquid rejects every single-signer exchange write for an account that\n * has been converted to multi-sig (`ApiRequestError: Multi-sig required`).\n * MetaMask signs Perps actions with a single agent/user wallet, so this is a\n * permanent account-shape condition rather than a failure we should retry or\n * forward to Sentry. Only the hyphenated spelling has been observed from the\n * venue; the unhyphenated variant is matched defensively.\n *\n * @param error - The caught error.\n * @returns True if the error indicates multi-sig signing is required.\n */\nexport function isHyperLiquidMultiSigRequiredError(error: unknown): boolean {\n const cause = ensureError(error);\n const lower = cause.message.toLowerCase();\n return (\n getHyperLiquidWriteGuardCode(cause) ===\n PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED ||\n lower.includes('multi-sig required') ||\n lower.includes('multisig required')\n );\n}\n\nconst HYPERLIQUID_WRITE_GUARD_CODES = [\n PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED,\n PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE,\n // Thrown inside signing for a TP/SL replacement. The SDK wraps them, and\n // the public result still has to name the refusal after restoration.\n PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE,\n PERPS_ERROR_CODES.TPSL_UPDATE_FAILED,\n] as const;\n\ntype HyperLiquidWriteGuardCode = (typeof HYPERLIQUID_WRITE_GUARD_CODES)[number];\n\n/**\n * Read a local write refusal, including one the SDK wrapped while signing.\n *\n * @param error - The caught failure.\n * @returns The local refusal code, when present.\n */\nexport function getHyperLiquidWriteGuardCode(\n error: unknown,\n): HyperLiquidWriteGuardCode | undefined {\n const sdkError = ensureError(error);\n const refusal =\n sdkError.name === 'AbstractWalletError' ? sdkError.cause : sdkError;\n if (!(refusal instanceof Error)) {\n return undefined;\n }\n return HYPERLIQUID_WRITE_GUARD_CODES.find((code) => code === refusal.message);\n}\n\n/**\n * Normalize a Hyperliquid failure into the stable error contract exposed to\n * clients.\n *\n * Known venue messages receive actionable codes. Unknown messages are replaced\n * by `UNKNOWN_ERROR`, while every newly normalized error keeps the original\n * failure in `cause` for telemetry and debugging.\n *\n * A `PerpsControllerError` that already carries details is returned as is, as\n * is `PRICE_MOVED`, whose numeric payload is computed locally. Any other\n * structured error without details is tagged with the provider so every\n * Hyperliquid result exposes the same details contract.\n *\n * @param error - Failure thrown by Hyperliquid or its SDK.\n * @returns A structured error safe to expose through provider results.\n */\nexport function normalizeHyperLiquidError(\n error: unknown,\n): PerpsControllerError {\n if (error instanceof PerpsControllerError) {\n const { errorCode: structuredCode } = error;\n if (\n error.errorDetails !== undefined ||\n structuredCode === PERPS_ERROR_CODES.PRICE_MOVED\n ) {\n return error;\n }\n return new PerpsControllerError(\n structuredCode,\n structuredCode,\n { code: structuredCode, provider: 'hyperliquid' },\n { cause: error.cause ?? error },\n );\n }\n\n const cause = ensureError(error, 'normalizeHyperLiquidError');\n let errorCode: HyperLiquidErrorDetails['code'] | undefined;\n\n const guardCode = getHyperLiquidWriteGuardCode(cause);\n if (guardCode) {\n errorCode = guardCode;\n } else if (isHyperLiquidUserNotFoundError(cause)) {\n errorCode = PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND;\n } else if (\n isPerpsErrorCode(cause.message) &&\n cause.message !== PERPS_ERROR_CODES.PRICE_MOVED\n ) {\n errorCode = cause.message;\n } else {\n errorCode = HYPERLIQUID_ERROR_MAPPINGS.find(({ pattern }) =>\n pattern.test(cause.message),\n )?.code;\n }\n\n const normalizedCode = errorCode ?? PERPS_ERROR_CODES.UNKNOWN_ERROR;\n return new PerpsControllerError(\n normalizedCode,\n normalizedCode,\n {\n code: normalizedCode,\n provider: 'hyperliquid',\n },\n { cause },\n );\n}\n"]}
|
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import { ExchangeClient } from '@nktkas/hyperliquid';
|
|
2
|
+
export type GuardedExchangeHooks = {
|
|
3
|
+
beforeSign?: () => Promise<void>;
|
|
4
|
+
onExchangeResult?: (outcome: {
|
|
5
|
+
answer: unknown;
|
|
6
|
+
} | {
|
|
7
|
+
error: unknown;
|
|
8
|
+
}) => void;
|
|
9
|
+
};
|
|
2
10
|
/**
|
|
3
11
|
* Create an operation-local SDK client with a fence after signing and before
|
|
4
12
|
* transport dispatch. The shared client and transport remain unchanged.
|
|
@@ -7,7 +15,8 @@ import { ExchangeClient } from '@nktkas/hyperliquid';
|
|
|
7
15
|
* @param beforeDispatch - Authoritative operation precondition.
|
|
8
16
|
* @param onDispatchRefused - Reports the exact signed exchange payload when
|
|
9
17
|
* the precondition refuses dispatch.
|
|
18
|
+
* @param hooks - Optional signer fence and observer for actual venue results.
|
|
10
19
|
* @returns A client whose writes are fenced at the transport boundary.
|
|
11
20
|
*/
|
|
12
|
-
export declare function createGuardedHyperLiquidClient(client: ExchangeClient, beforeDispatch: () => Promise<void>, onDispatchRefused?: (payload: unknown) => void): ExchangeClient;
|
|
21
|
+
export declare function createGuardedHyperLiquidClient(client: ExchangeClient, beforeDispatch: () => Promise<void>, onDispatchRefused?: (payload: unknown) => void, hooks?: GuardedExchangeHooks): ExchangeClient;
|
|
13
22
|
//# sourceMappingURL=guardedHyperLiquidClient.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guardedHyperLiquidClient.d.ts","sourceRoot":"","sources":["../../src/utils/guardedHyperLiquidClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD
|
|
1
|
+
{"version":3,"file":"guardedHyperLiquidClient.d.ts","sourceRoot":"","sources":["../../src/utils/guardedHyperLiquidClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,MAAM,MAAM,oBAAoB,GAAG;IACjC,UAAU,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACjC,gBAAgB,CAAC,EAAE,CACjB,OAAO,EAAE;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,GAAG;QAAE,KAAK,EAAE,OAAO,CAAA;KAAE,KAC9C,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,8BAA8B,CAC5C,MAAM,EAAE,cAAc,EACtB,cAAc,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,EACnC,iBAAiB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,EAC9C,KAAK,CAAC,EAAE,oBAAoB,GAC3B,cAAc,CAgEhB"}
|
|
@@ -7,12 +7,36 @@ import { ExchangeClient } from '@nktkas/hyperliquid';
|
|
|
7
7
|
* @param beforeDispatch - Authoritative operation precondition.
|
|
8
8
|
* @param onDispatchRefused - Reports the exact signed exchange payload when
|
|
9
9
|
* the precondition refuses dispatch.
|
|
10
|
+
* @param hooks - Optional signer fence and observer for actual venue results.
|
|
10
11
|
* @returns A client whose writes are fenced at the transport boundary.
|
|
11
12
|
*/
|
|
12
|
-
export function createGuardedHyperLiquidClient(client, beforeDispatch, onDispatchRefused) {
|
|
13
|
-
const { transport } = client.config_;
|
|
13
|
+
export function createGuardedHyperLiquidClient(client, beforeDispatch, onDispatchRefused, hooks) {
|
|
14
|
+
const { transport, wallet } = client.config_;
|
|
15
|
+
const { beforeSign, onExchangeResult } = hooks ?? {};
|
|
16
|
+
const guardedWallet = beforeSign
|
|
17
|
+
? new Proxy(wallet, {
|
|
18
|
+
get(target, property) {
|
|
19
|
+
const member = Reflect.get(target, property, target);
|
|
20
|
+
if (typeof member !== 'function') {
|
|
21
|
+
return member;
|
|
22
|
+
}
|
|
23
|
+
if (property === 'signTypedData' || property === '_signTypedData') {
|
|
24
|
+
// The SDK uses the signer function's arity to identify the wallet.
|
|
25
|
+
return new Proxy(member, {
|
|
26
|
+
async apply(signer, _receiver, args) {
|
|
27
|
+
await beforeSign();
|
|
28
|
+
return await Reflect.apply(signer, target, args);
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
const bound = member.bind(target);
|
|
33
|
+
return bound;
|
|
34
|
+
},
|
|
35
|
+
})
|
|
36
|
+
: wallet;
|
|
14
37
|
return new ExchangeClient({
|
|
15
38
|
...client.config_,
|
|
39
|
+
wallet: guardedWallet,
|
|
16
40
|
transport: {
|
|
17
41
|
isTestnet: transport.isTestnet,
|
|
18
42
|
async request(endpoint, payload, signal) {
|
|
@@ -30,7 +54,17 @@ export function createGuardedHyperLiquidClient(client, beforeDispatch, onDispatc
|
|
|
30
54
|
}
|
|
31
55
|
throw error;
|
|
32
56
|
}
|
|
33
|
-
|
|
57
|
+
if (endpoint !== 'exchange' || !onExchangeResult) {
|
|
58
|
+
return transport.request(endpoint, payload, signal);
|
|
59
|
+
}
|
|
60
|
+
const answer = await transport
|
|
61
|
+
.request(endpoint, payload, signal)
|
|
62
|
+
.catch((error) => {
|
|
63
|
+
onExchangeResult({ error });
|
|
64
|
+
throw error;
|
|
65
|
+
});
|
|
66
|
+
onExchangeResult({ answer });
|
|
67
|
+
return answer;
|
|
34
68
|
},
|
|
35
69
|
},
|
|
36
70
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guardedHyperLiquidClient.js","sourceRoot":"","sources":["../../src/utils/guardedHyperLiquidClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"guardedHyperLiquidClient.js","sourceRoot":"","sources":["../../src/utils/guardedHyperLiquidClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AASrD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,8BAA8B,CAC5C,MAAsB,EACtB,cAAmC,EACnC,iBAA8C,EAC9C,KAA4B;IAE5B,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC;IAC7C,MAAM,EAAE,UAAU,EAAE,gBAAgB,EAAE,GAAG,KAAK,IAAI,EAAE,CAAC;IACrD,MAAM,aAAa,GAAG,UAAU;QAC9B,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,EAAE;YAChB,GAAG,CAAC,MAAM,EAAE,QAAQ;gBAClB,MAAM,MAAM,GAAY,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;gBAC9D,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE,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G,MAAM,SAAS;qBAC3B,OAAO,CAAS,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC;qBAC1C,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;oBACxB,gBAAgB,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;oBAC5B,MAAM,KAAK,CAAC;gBACd,CAAC,CAAC,CAAC;gBACL,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;gBAC7B,OAAO,MAAM,CAAC;YAChB,CAAC;SACF;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { ExchangeClient } from '@nktkas/hyperliquid';\n\nexport type GuardedExchangeHooks = {\n beforeSign?: () => Promise<void>;\n onExchangeResult?: (\n outcome: { answer: unknown } | { error: unknown },\n ) => void;\n};\n\n/**\n * Create an operation-local SDK client with a fence after signing and before\n * transport dispatch. The shared client and transport remain unchanged.\n *\n * @param client - Captured SDK client, including wallet and nonce configuration.\n * @param beforeDispatch - Authoritative operation precondition.\n * @param onDispatchRefused - Reports the exact signed exchange payload when\n * the precondition refuses dispatch.\n * @param hooks - Optional signer fence and observer for actual venue results.\n * @returns A client whose writes are fenced at the transport boundary.\n */\nexport function createGuardedHyperLiquidClient(\n client: ExchangeClient,\n beforeDispatch: () => Promise<void>,\n onDispatchRefused?: (payload: unknown) => void,\n hooks?: GuardedExchangeHooks,\n): ExchangeClient {\n const { transport, wallet } = client.config_;\n const { beforeSign, onExchangeResult } = hooks ?? {};\n const guardedWallet = beforeSign\n ? new Proxy(wallet, {\n get(target, property): unknown {\n const member: unknown = Reflect.get(target, property, target);\n if (typeof member !== 'function') {\n return member;\n }\n if (property === 'signTypedData' || property === '_signTypedData') {\n // The SDK uses the signer function's arity to identify the wallet.\n return new Proxy(member, {\n async apply(\n signer,\n _receiver,\n args: unknown[],\n ): Promise<unknown> {\n await beforeSign();\n return await Reflect.apply(signer, target, args);\n },\n });\n }\n const bound: unknown = member.bind(target);\n return bound;\n },\n })\n : wallet;\n return new ExchangeClient({\n ...client.config_,\n wallet: guardedWallet,\n transport: {\n isTestnet: transport.isTestnet,\n async request<Result>(\n endpoint: 'info' | 'exchange',\n payload: unknown,\n signal?: AbortSignal,\n ): Promise<Result> {\n try {\n await beforeDispatch();\n } catch (error) {\n if (endpoint === 'exchange') {\n try {\n onDispatchRefused?.(payload);\n } catch {\n // Reporting must preserve the authoritative refusal error.\n }\n }\n throw error;\n }\n if (endpoint !== 'exchange' || !onExchangeResult) {\n return transport.request<Result>(endpoint, payload, signal);\n }\n const answer = await transport\n .request<Result>(endpoint, payload, signal)\n .catch((error: unknown) => {\n onExchangeResult({ error });\n throw error;\n });\n onExchangeResult({ answer });\n return answer;\n },\n },\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hyperLiquidValidation.d.ts","sourceRoot":"","sources":["../../src/utils/hyperLiquidValidation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAaxD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAE3D,OAAO,KAAK,EACV,uBAAuB,EACvB,gBAAgB,EACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAWtE;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG,gBAAgB,GAAG,SAAS,CAAC;AAEjE;;GAEG;AAEH;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,SAAS;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,EACnD,KAAK,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,GAAG,MAAM,GAAG,sBAAsB,CAe1E;AAED;;;;;;;;;GASG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE;IACN,OAAO,CAAC,EAAE,WAAW,CAAC;IAC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5B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B,CAAC;AAuNF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,6BAA6B,GAAG;IACtC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,QAAQ,CAAC,EAAE,IAAI,GAAG,YAAY,GAAG,cAAc,CAAC;IAChD,WAAW,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC;IACpC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,GACA;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CA8ItC;AA2DD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GACjC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAStC"}
|
|
@@ -608,7 +608,9 @@ export function validateOrderParams(params) {
|
|
|
608
608
|
error: PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED,
|
|
609
609
|
};
|
|
610
610
|
}
|
|
611
|
-
|
|
611
|
+
// NaN and Infinity slip past a bare `<= 0` check.
|
|
612
|
+
const price = params.price ? parseFloat(params.price) : undefined;
|
|
613
|
+
if (price !== undefined && !(Number.isFinite(price) && price > 0)) {
|
|
612
614
|
return {
|
|
613
615
|
isValid: false,
|
|
614
616
|
error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,
|
|
@@ -622,7 +624,7 @@ export function validateOrderParams(params) {
|
|
|
622
624
|
};
|
|
623
625
|
}
|
|
624
626
|
const triggerPrice = parseFloat(params.triggerPrice);
|
|
625
|
-
if (
|
|
627
|
+
if (!(Number.isFinite(triggerPrice) && triggerPrice > 0)) {
|
|
626
628
|
return {
|
|
627
629
|
isValid: false,
|
|
628
630
|
error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE,
|