@metamask-previews/perps-controller 26.0.0-preview-203750488 → 26.1.0-preview-037c8a905
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 +21 -1
- package/dist/PerpsController.d.ts +7 -3
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +23 -5
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/lighterConfig.d.ts +5 -0
- package/dist/constants/lighterConfig.d.ts.map +1 -1
- package/dist/constants/lighterConfig.js +5 -0
- package/dist/constants/lighterConfig.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +9 -0
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +11 -0
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +7 -0
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +13 -0
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +7 -0
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +25 -5
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/services/DataLakeService.d.ts.map +1 -1
- package/dist/services/DataLakeService.js +7 -28
- package/dist/services/DataLakeService.js.map +1 -1
- package/dist/services/LighterNotificationEnrollmentService.d.ts +40 -0
- package/dist/services/LighterNotificationEnrollmentService.d.ts.map +1 -0
- package/dist/services/LighterNotificationEnrollmentService.js +102 -0
- package/dist/services/LighterNotificationEnrollmentService.js.map +1 -0
- package/dist/services/TradingService.d.ts +2 -0
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +11 -3
- package/dist/services/TradingService.js.map +1 -1
- package/dist/services/getOptionalBearerToken.d.ts +12 -0
- package/dist/services/getOptionalBearerToken.d.ts.map +1 -0
- package/dist/services/getOptionalBearerToken.js +22 -0
- package/dist/services/getOptionalBearerToken.js.map +1 -0
- package/dist/types/index.d.ts +15 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/lighterClientOrderTag.d.ts +23 -0
- package/dist/utils/lighterClientOrderTag.d.ts.map +1 -0
- package/dist/utils/lighterClientOrderTag.js +43 -0
- package/dist/utils/lighterClientOrderTag.js.map +1 -0
- package/docs/architecture.md +33 -31
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataLakeService.d.ts","sourceRoot":"","sources":["../../src/services/DataLakeService.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"DataLakeService.d.ts","sourceRoot":"","sources":["../../src/services/DataLakeService.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAI1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;;;;;;;GAQG;AACH,qBAAa,eAAe;;IAK1B;;;;;OAKG;IACH,YACE,IAAI,EAAE,yBAAyB,EAC/B,SAAS,EAAE,4BAA4B,EAIxC;IAED;;;;;;;;;;;;;;OAcG;IACG,WAAW,CAAC,OAAO,EAAE;QACzB,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;QACzB,MAAM,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,SAAS,EAAE,OAAO,CAAC;QACnB,OAAO,EAAE,cAAc,CAAC;QACxB,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAkNhD;CACF"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { v4 as uuidv4 } from 'uuid';
|
|
2
2
|
import { PerpsMeasurementName } from '../constants/performanceMetrics.js';
|
|
3
|
-
import { DATA_LAKE_API_CONFIG, PERPS_CONSTANTS, } from '../constants/perpsConfig.js';
|
|
3
|
+
import { DATA_LAKE_API_CONFIG, NOTIFY_PERPS_API_CONFIG, PERPS_CONSTANTS, } from '../constants/perpsConfig.js';
|
|
4
4
|
import { PerpsTraceNames, PerpsTraceOperations } from '../types/index.js';
|
|
5
5
|
import { getSelectedEvmAccountFromMessenger } from '../utils/accountUtils.js';
|
|
6
6
|
import { ensureError } from '../utils/errorUtils.js';
|
|
7
|
-
import {
|
|
7
|
+
import { getOptionalBearerToken } from './getOptionalBearerToken.js';
|
|
8
8
|
/**
|
|
9
9
|
* DataLakeService
|
|
10
10
|
*
|
|
@@ -27,25 +27,6 @@ export class DataLakeService {
|
|
|
27
27
|
this.#deps = deps;
|
|
28
28
|
this.#messenger = messenger;
|
|
29
29
|
}
|
|
30
|
-
/**
|
|
31
|
-
* Get bearer token via DI authentication controller
|
|
32
|
-
*
|
|
33
|
-
* @returns The bearer token string for API authentication, or undefined when
|
|
34
|
-
* the host does not provide `AuthenticationController:getBearerToken`.
|
|
35
|
-
*/
|
|
36
|
-
async #getBearerToken() {
|
|
37
|
-
try {
|
|
38
|
-
return await this.#messenger.call('AuthenticationController:getBearerToken');
|
|
39
|
-
}
|
|
40
|
-
catch (error) {
|
|
41
|
-
// Reporting is optional: a host without authentication skips it rather
|
|
42
|
-
// than logging and retrying a call that can never succeed.
|
|
43
|
-
if (isMissingActionHandlerError(error, 'AuthenticationController:getBearerToken')) {
|
|
44
|
-
return undefined;
|
|
45
|
-
}
|
|
46
|
-
throw error;
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
30
|
/**
|
|
50
31
|
* Report order events to data lake API with retry (non-blocking)
|
|
51
32
|
* Implements exponential backoff retry logic (max 3 retries)
|
|
@@ -72,8 +53,6 @@ export class DataLakeService {
|
|
|
72
53
|
});
|
|
73
54
|
return { success: true, error: 'Skipped for testnet' };
|
|
74
55
|
}
|
|
75
|
-
const MAX_RETRIES = 3;
|
|
76
|
-
const RETRY_DELAY_MS = 1000;
|
|
77
56
|
// Generate trace ID once on first call
|
|
78
57
|
const traceId = _traceId ?? uuidv4();
|
|
79
58
|
// Start trace only on first attempt
|
|
@@ -95,14 +74,14 @@ export class DataLakeService {
|
|
|
95
74
|
action,
|
|
96
75
|
symbol,
|
|
97
76
|
attempt: retryCount + 1,
|
|
98
|
-
maxAttempts:
|
|
77
|
+
maxAttempts: NOTIFY_PERPS_API_CONFIG.MaxRetries + 1,
|
|
99
78
|
hasStopLoss: Boolean(slPrice),
|
|
100
79
|
hasTakeProfit: Boolean(tpPrice),
|
|
101
80
|
timestamp: new Date().toISOString(),
|
|
102
81
|
});
|
|
103
82
|
const apiCallStartTime = this.#deps.performance.now();
|
|
104
83
|
try {
|
|
105
|
-
const token = await this.#
|
|
84
|
+
const token = await getOptionalBearerToken(this.#messenger);
|
|
106
85
|
const evmAccount = getSelectedEvmAccountFromMessenger(this.#messenger);
|
|
107
86
|
if (!evmAccount || !token) {
|
|
108
87
|
this.#deps.debugLogger.log('DataLake API: Missing requirements', {
|
|
@@ -170,13 +149,13 @@ export class DataLakeService {
|
|
|
170
149
|
action,
|
|
171
150
|
symbol,
|
|
172
151
|
retryCount,
|
|
173
|
-
willRetry: retryCount <
|
|
152
|
+
willRetry: retryCount < NOTIFY_PERPS_API_CONFIG.MaxRetries,
|
|
174
153
|
},
|
|
175
154
|
},
|
|
176
155
|
});
|
|
177
156
|
// Retry logic
|
|
178
|
-
if (retryCount <
|
|
179
|
-
const retryDelay =
|
|
157
|
+
if (retryCount < NOTIFY_PERPS_API_CONFIG.MaxRetries) {
|
|
158
|
+
const retryDelay = NOTIFY_PERPS_API_CONFIG.RetryDelayMs * Math.pow(2, retryCount);
|
|
180
159
|
this.#deps.debugLogger.log('DataLake API: Scheduling retry', {
|
|
181
160
|
retryIn: `${retryDelay}ms`,
|
|
182
161
|
nextAttempt: retryCount + 2,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataLakeService.js","sourceRoot":"","sources":["../../src/services/DataLakeService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EACL,oBAAoB,EACpB,eAAe,GAChB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAG1E,OAAO,EAAE,kCAAkC,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AAGxE;;;;;;;;GAQG;AACH,MAAM,OAAO,eAAe;IACjB,KAAK,CAA4B;IAEjC,UAAU,CAA+B;IAElD;;;;;OAKG;IACH,YACE,IAA+B,EAC/B,SAAuC;QAEvC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,eAAe;QACnB,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAC/B,yCAAyC,CAC1C,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,uEAAuE;YACvE,2DAA2D;YAC3D,IACE,2BAA2B,CACzB,KAAK,EACL,yCAAyC,CAC1C,EACD,CAAC;gBACD,OAAO,SAAS,CAAC;YACnB,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CA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CACP;6BACF;yBACF,CACF,CAAC;oBACJ,CAAC,CAAC,CAAC;gBACL,CAAC,EAAE,UAAU,CAAC,CAAC;gBAEf,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;YACjD,CAAC;YAED,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC;gBACzB,IAAI,EAAE,eAAe,CAAC,cAAc;gBACpC,EAAE,EAAE,OAAO;gBACX,IAAI,EAAE;oBACJ,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,YAAY;oBACnB,YAAY,EAAE,UAAU;iBACzB;aACF,CAAC,CAAC;YAEH,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CACrB,WAAW,CAAC,KAAK,EAAE,6BAA6B,CAAC,EACjD;gBACE,IAAI,EAAE,EAAE,OAAO,EAAE,eAAe,CAAC,WAAW,EAAE;gBAC9C,OAAO,EAAE;oBACP,IAAI,EAAE,6BAA6B;oBACnC,IAAI,EAAE,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE;iBAChE;aACF,CACF,CAAC;YAEF,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;QACjD,CAAC;IACH,CAAC;CACF","sourcesContent":["import { v4 as uuidv4 } from 'uuid';\n\nimport { PerpsMeasurementName } from '../constants/performanceMetrics.js';\nimport {\n DATA_LAKE_API_CONFIG,\n PERPS_CONSTANTS,\n} from '../constants/perpsConfig.js';\nimport { PerpsTraceNames, PerpsTraceOperations } from '../types/index.js';\nimport type { PerpsPlatformDependencies } from '../types/index.js';\nimport type { PerpsControllerMessengerBase } from '../types/messenger.js';\nimport { getSelectedEvmAccountFromMessenger } from '../utils/accountUtils.js';\nimport { ensureError } from '../utils/errorUtils.js';\nimport { isMissingActionHandlerError } from './missingActionHandler.js';\nimport type { ServiceContext } from './ServiceContext.js';\n\n/**\n * DataLakeService\n *\n * Handles reporting order events to external Data Lake API.\n * Implements exponential backoff retry logic and performance tracing.\n * Stateless service that operates purely on external API calls.\n *\n * Instance-based service with constructor injection of platform dependencies.\n */\nexport class DataLakeService {\n readonly #deps: PerpsPlatformDependencies;\n\n readonly #messenger: PerpsControllerMessengerBase;\n\n /**\n * Create a new DataLakeService instance\n *\n * @param deps - Platform dependencies for logging, metrics, etc.\n * @param messenger - Controller messenger for cross-controller communication.\n */\n constructor(\n deps: PerpsPlatformDependencies,\n messenger: PerpsControllerMessengerBase,\n ) {\n this.#deps = deps;\n this.#messenger = messenger;\n }\n\n /**\n * Get bearer token via DI authentication controller\n *\n * @returns The bearer token string for API authentication, or undefined when\n * the host does not provide `AuthenticationController:getBearerToken`.\n */\n async #getBearerToken(): Promise<string | undefined> {\n try {\n return await this.#messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n } catch (error) {\n // Reporting is optional: a host without authentication skips it rather\n // than logging and retrying a call that can never succeed.\n if (\n isMissingActionHandlerError(\n error,\n 'AuthenticationController:getBearerToken',\n )\n ) {\n return undefined;\n }\n throw error;\n }\n }\n\n /**\n * Report order events to data lake API with retry (non-blocking)\n * Implements exponential backoff retry logic (max 3 retries)\n *\n * @param options - Configuration object\n * @param options.action - Order action ('open' or 'close')\n * @param options.symbol - Market symbol\n * @param options.slPrice - Optional stop loss price.\n * @param options.tpPrice - Optional take profit price.\n * @param options.isTestnet - Whether this is a testnet operation (skips API call)\n * @param options.context - ServiceContext for dependencies (messenger, tracing)\n * @param options.retryCount - Internal retry counter (managed by service)\n * @param options._traceId - Internal trace ID (managed by service)\n * @returns Result object with success flag and optional error message\n */\n async reportOrder(options: {\n action: 'open' | 'close';\n symbol: string;\n slPrice?: number;\n tpPrice?: number;\n isTestnet: boolean;\n context: ServiceContext;\n retryCount?: number;\n _traceId?: string;\n }): Promise<{ success: boolean; error?: string }> {\n const {\n action,\n symbol,\n slPrice,\n tpPrice,\n isTestnet,\n context,\n retryCount = 0,\n _traceId,\n } = options;\n\n // Skip data lake reporting for testnet as the API doesn't handle testnet data\n if (isTestnet) {\n this.#deps.debugLogger.log('DataLake API: Skipping for testnet', {\n action,\n symbol,\n network: 'testnet',\n });\n return { success: true, error: 'Skipped for testnet' };\n }\n\n const MAX_RETRIES = 3;\n const RETRY_DELAY_MS = 1000;\n\n // Generate trace ID once on first call\n const traceId = _traceId ?? uuidv4();\n\n // Start trace only on first attempt\n if (retryCount === 0) {\n this.#deps.tracer.trace({\n name: PerpsTraceNames.DataLakeReport,\n op: PerpsTraceOperations.Operation,\n id: traceId,\n tags: {\n action,\n symbol,\n provider: context.tracingContext.provider,\n isTestnet: String(context.tracingContext.isTestnet),\n },\n });\n }\n\n // Log the attempt\n this.#deps.debugLogger.log('DataLake API: Starting order report', {\n action,\n symbol,\n attempt: retryCount + 1,\n maxAttempts: MAX_RETRIES + 1,\n hasStopLoss: Boolean(slPrice),\n hasTakeProfit: Boolean(tpPrice),\n timestamp: new Date().toISOString(),\n });\n\n const apiCallStartTime = this.#deps.performance.now();\n\n try {\n const token = await this.#getBearerToken();\n const evmAccount = getSelectedEvmAccountFromMessenger(this.#messenger);\n\n if (!evmAccount || !token) {\n this.#deps.debugLogger.log('DataLake API: Missing requirements', {\n hasAccount: Boolean(evmAccount),\n hasToken: Boolean(token),\n action,\n symbol,\n });\n // Not retried, so close the trace opened on the first attempt.\n this.#deps.tracer.endTrace({\n name: PerpsTraceNames.DataLakeReport,\n id: traceId,\n data: { success: false, error: 'No account or token available' },\n });\n return { success: false, error: 'No account or token available' };\n }\n\n const response = await fetch(DATA_LAKE_API_CONFIG.OrdersEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n user_id: evmAccount.address,\n symbol,\n sl_price: slPrice,\n tp_price: tpPrice,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`DataLake API error: ${response.status}`);\n }\n\n // Consume response body (might be empty for 201, but good to check)\n const responseBody = await response.text();\n\n const apiCallDuration = this.#deps.performance.now() - apiCallStartTime;\n\n // Record measurement\n this.#deps.tracer.setMeasurement(\n PerpsMeasurementName.PerpsDataLakeApiCall,\n apiCallDuration,\n 'millisecond',\n );\n\n // Success logging\n this.#deps.debugLogger.log('DataLake API: Order reported successfully', {\n action,\n symbol,\n status: response.status,\n attempt: retryCount + 1,\n responseBody: responseBody || 'empty',\n duration: `${apiCallDuration.toFixed(0)}ms`,\n });\n\n // End trace on success\n this.#deps.tracer.endTrace({\n name: PerpsTraceNames.DataLakeReport,\n id: traceId,\n data: {\n success: true,\n retries: retryCount,\n },\n });\n\n return { success: true };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n\n this.#deps.logger.error(\n ensureError(error, 'DataLakeService.reportOrder'),\n {\n tags: { feature: PERPS_CONSTANTS.FeatureName },\n context: {\n name: 'DataLakeService.reportOrder',\n data: {\n action,\n symbol,\n retryCount,\n willRetry: retryCount < MAX_RETRIES,\n },\n },\n },\n );\n\n // Retry logic\n if (retryCount < MAX_RETRIES) {\n const retryDelay = RETRY_DELAY_MS * Math.pow(2, retryCount);\n this.#deps.debugLogger.log('DataLake API: Scheduling retry', {\n retryIn: `${retryDelay}ms`,\n nextAttempt: retryCount + 2,\n action,\n symbol,\n });\n\n setTimeout(() => {\n this.reportOrder({\n action,\n symbol,\n slPrice,\n tpPrice,\n isTestnet,\n context,\n retryCount: retryCount + 1,\n _traceId: traceId,\n }).catch((_retryError) => {\n this.#deps.logger.error(\n ensureError(_retryError, 'DataLakeService.reportOrder'),\n {\n tags: { feature: PERPS_CONSTANTS.FeatureName },\n context: {\n name: 'DataLakeService.reportOrder',\n data: {\n operation: 'retry',\n retryCount: retryCount + 1,\n action,\n symbol,\n },\n },\n },\n );\n });\n }, retryDelay);\n\n return { success: false, error: errorMessage };\n }\n\n this.#deps.tracer.endTrace({\n name: PerpsTraceNames.DataLakeReport,\n id: traceId,\n data: {\n success: false,\n error: errorMessage,\n totalRetries: retryCount,\n },\n });\n\n this.#deps.logger.error(\n ensureError(error, 'DataLakeService.reportOrder'),\n {\n tags: { feature: PERPS_CONSTANTS.FeatureName },\n context: {\n name: 'DataLakeService.reportOrder',\n data: { operation: 'finalFailure', action, symbol, retryCount },\n },\n },\n );\n\n return { success: false, error: errorMessage };\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"DataLakeService.js","sourceRoot":"","sources":["../../src/services/DataLakeService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EACL,oBAAoB,EACpB,uBAAuB,EACvB,eAAe,GAChB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAG1E,OAAO,EAAE,kCAAkC,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAGrE;;;;;;;;GAQG;AACH,MAAM,OAAO,eAAe;IACjB,KAAK,CAA4B;IAEjC,UAAU,CAA+B;IAElD;;;;;OAKG;IACH,YACE,IAA+B,EAC/B,SAAuC;QAEvC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,KAAK,CAAC,WAAW,CAAC,OASjB;QACC,MAAM,EACJ,MAAM,EACN,MAAM,EACN,OAAO,EACP,OAAO,EACP,SAAS,EACT,OAAO,EACP,UAAU,GAAG,CAAC,EACd,QAAQ,GACT,GAAG,OAAO,CAAC;QAEZ,8EAA8E;QAC9E,IAAI,SAAS,EAAE,CAAC;YACd,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG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;oBACJ,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,YAAY;oBACnB,YAAY,EAAE,UAAU;iBACzB;aACF,CAAC,CAAC;YAEH,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CACrB,WAAW,CAAC,KAAK,EAAE,6BAA6B,CAAC,EACjD;gBACE,IAAI,EAAE,EAAE,OAAO,EAAE,eAAe,CAAC,WAAW,EAAE;gBAC9C,OAAO,EAAE;oBACP,IAAI,EAAE,6BAA6B;oBACnC,IAAI,EAAE,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE;iBAChE;aACF,CACF,CAAC;YAEF,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;QACjD,CAAC;IACH,CAAC;CACF","sourcesContent":["import { v4 as uuidv4 } from 'uuid';\n\nimport { PerpsMeasurementName } from '../constants/performanceMetrics.js';\nimport {\n DATA_LAKE_API_CONFIG,\n NOTIFY_PERPS_API_CONFIG,\n PERPS_CONSTANTS,\n} from '../constants/perpsConfig.js';\nimport { PerpsTraceNames, PerpsTraceOperations } from '../types/index.js';\nimport type { PerpsPlatformDependencies } from '../types/index.js';\nimport type { PerpsControllerMessengerBase } from '../types/messenger.js';\nimport { getSelectedEvmAccountFromMessenger } from '../utils/accountUtils.js';\nimport { ensureError } from '../utils/errorUtils.js';\nimport { getOptionalBearerToken } from './getOptionalBearerToken.js';\nimport type { ServiceContext } from './ServiceContext.js';\n\n/**\n * DataLakeService\n *\n * Handles reporting order events to external Data Lake API.\n * Implements exponential backoff retry logic and performance tracing.\n * Stateless service that operates purely on external API calls.\n *\n * Instance-based service with constructor injection of platform dependencies.\n */\nexport class DataLakeService {\n readonly #deps: PerpsPlatformDependencies;\n\n readonly #messenger: PerpsControllerMessengerBase;\n\n /**\n * Create a new DataLakeService instance\n *\n * @param deps - Platform dependencies for logging, metrics, etc.\n * @param messenger - Controller messenger for cross-controller communication.\n */\n constructor(\n deps: PerpsPlatformDependencies,\n messenger: PerpsControllerMessengerBase,\n ) {\n this.#deps = deps;\n this.#messenger = messenger;\n }\n\n /**\n * Report order events to data lake API with retry (non-blocking)\n * Implements exponential backoff retry logic (max 3 retries)\n *\n * @param options - Configuration object\n * @param options.action - Order action ('open' or 'close')\n * @param options.symbol - Market symbol\n * @param options.slPrice - Optional stop loss price.\n * @param options.tpPrice - Optional take profit price.\n * @param options.isTestnet - Whether this is a testnet operation (skips API call)\n * @param options.context - ServiceContext for dependencies (messenger, tracing)\n * @param options.retryCount - Internal retry counter (managed by service)\n * @param options._traceId - Internal trace ID (managed by service)\n * @returns Result object with success flag and optional error message\n */\n async reportOrder(options: {\n action: 'open' | 'close';\n symbol: string;\n slPrice?: number;\n tpPrice?: number;\n isTestnet: boolean;\n context: ServiceContext;\n retryCount?: number;\n _traceId?: string;\n }): Promise<{ success: boolean; error?: string }> {\n const {\n action,\n symbol,\n slPrice,\n tpPrice,\n isTestnet,\n context,\n retryCount = 0,\n _traceId,\n } = options;\n\n // Skip data lake reporting for testnet as the API doesn't handle testnet data\n if (isTestnet) {\n this.#deps.debugLogger.log('DataLake API: Skipping for testnet', {\n action,\n symbol,\n network: 'testnet',\n });\n return { success: true, error: 'Skipped for testnet' };\n }\n\n // Generate trace ID once on first call\n const traceId = _traceId ?? uuidv4();\n\n // Start trace only on first attempt\n if (retryCount === 0) {\n this.#deps.tracer.trace({\n name: PerpsTraceNames.DataLakeReport,\n op: PerpsTraceOperations.Operation,\n id: traceId,\n tags: {\n action,\n symbol,\n provider: context.tracingContext.provider,\n isTestnet: String(context.tracingContext.isTestnet),\n },\n });\n }\n\n // Log the attempt\n this.#deps.debugLogger.log('DataLake API: Starting order report', {\n action,\n symbol,\n attempt: retryCount + 1,\n maxAttempts: NOTIFY_PERPS_API_CONFIG.MaxRetries + 1,\n hasStopLoss: Boolean(slPrice),\n hasTakeProfit: Boolean(tpPrice),\n timestamp: new Date().toISOString(),\n });\n\n const apiCallStartTime = this.#deps.performance.now();\n\n try {\n const token = await getOptionalBearerToken(this.#messenger);\n const evmAccount = getSelectedEvmAccountFromMessenger(this.#messenger);\n\n if (!evmAccount || !token) {\n this.#deps.debugLogger.log('DataLake API: Missing requirements', {\n hasAccount: Boolean(evmAccount),\n hasToken: Boolean(token),\n action,\n symbol,\n });\n // Not retried, so close the trace opened on the first attempt.\n this.#deps.tracer.endTrace({\n name: PerpsTraceNames.DataLakeReport,\n id: traceId,\n data: { success: false, error: 'No account or token available' },\n });\n return { success: false, error: 'No account or token available' };\n }\n\n const response = await fetch(DATA_LAKE_API_CONFIG.OrdersEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n user_id: evmAccount.address,\n symbol,\n sl_price: slPrice,\n tp_price: tpPrice,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`DataLake API error: ${response.status}`);\n }\n\n // Consume response body (might be empty for 201, but good to check)\n const responseBody = await response.text();\n\n const apiCallDuration = this.#deps.performance.now() - apiCallStartTime;\n\n // Record measurement\n this.#deps.tracer.setMeasurement(\n PerpsMeasurementName.PerpsDataLakeApiCall,\n apiCallDuration,\n 'millisecond',\n );\n\n // Success logging\n this.#deps.debugLogger.log('DataLake API: Order reported successfully', {\n action,\n symbol,\n status: response.status,\n attempt: retryCount + 1,\n responseBody: responseBody || 'empty',\n duration: `${apiCallDuration.toFixed(0)}ms`,\n });\n\n // End trace on success\n this.#deps.tracer.endTrace({\n name: PerpsTraceNames.DataLakeReport,\n id: traceId,\n data: {\n success: true,\n retries: retryCount,\n },\n });\n\n return { success: true };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n\n this.#deps.logger.error(\n ensureError(error, 'DataLakeService.reportOrder'),\n {\n tags: { feature: PERPS_CONSTANTS.FeatureName },\n context: {\n name: 'DataLakeService.reportOrder',\n data: {\n action,\n symbol,\n retryCount,\n willRetry: retryCount < NOTIFY_PERPS_API_CONFIG.MaxRetries,\n },\n },\n },\n );\n\n // Retry logic\n if (retryCount < NOTIFY_PERPS_API_CONFIG.MaxRetries) {\n const retryDelay =\n NOTIFY_PERPS_API_CONFIG.RetryDelayMs * Math.pow(2, retryCount);\n this.#deps.debugLogger.log('DataLake API: Scheduling retry', {\n retryIn: `${retryDelay}ms`,\n nextAttempt: retryCount + 2,\n action,\n symbol,\n });\n\n setTimeout(() => {\n this.reportOrder({\n action,\n symbol,\n slPrice,\n tpPrice,\n isTestnet,\n context,\n retryCount: retryCount + 1,\n _traceId: traceId,\n }).catch((_retryError) => {\n this.#deps.logger.error(\n ensureError(_retryError, 'DataLakeService.reportOrder'),\n {\n tags: { feature: PERPS_CONSTANTS.FeatureName },\n context: {\n name: 'DataLakeService.reportOrder',\n data: {\n operation: 'retry',\n retryCount: retryCount + 1,\n action,\n symbol,\n },\n },\n },\n );\n });\n }, retryDelay);\n\n return { success: false, error: errorMessage };\n }\n\n this.#deps.tracer.endTrace({\n name: PerpsTraceNames.DataLakeReport,\n id: traceId,\n data: {\n success: false,\n error: errorMessage,\n totalRetries: retryCount,\n },\n });\n\n this.#deps.logger.error(\n ensureError(error, 'DataLakeService.reportOrder'),\n {\n tags: { feature: PERPS_CONSTANTS.FeatureName },\n context: {\n name: 'DataLakeService.reportOrder',\n data: { operation: 'finalFailure', action, symbol, retryCount },\n },\n },\n );\n\n return { success: false, error: errorMessage };\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { PerpsPlatformDependencies } from '../types/index.js';
|
|
2
|
+
import type { PerpsControllerMessengerBase } from '../types/messenger.js';
|
|
3
|
+
/**
|
|
4
|
+
* LighterNotificationEnrollmentService
|
|
5
|
+
*
|
|
6
|
+
* Tells notify-perps which Lighter account to watch for the signed-in profile.
|
|
7
|
+
* Mirrors the order reporting done for Hyperliquid (`DataLakeService`): meant
|
|
8
|
+
* to be fired without awaiting, retries with exponential backoff, never
|
|
9
|
+
* throws, and only logs failures.
|
|
10
|
+
*/
|
|
11
|
+
export declare class LighterNotificationEnrollmentService {
|
|
12
|
+
#private;
|
|
13
|
+
/**
|
|
14
|
+
* Create a new LighterNotificationEnrollmentService instance
|
|
15
|
+
*
|
|
16
|
+
* @param deps - Platform dependencies for logging.
|
|
17
|
+
* @param messenger - Controller messenger for cross-controller communication.
|
|
18
|
+
*/
|
|
19
|
+
constructor(deps: PerpsPlatformDependencies, messenger: PerpsControllerMessengerBase);
|
|
20
|
+
/**
|
|
21
|
+
* Enroll the Lighter account with notify-perps.
|
|
22
|
+
*
|
|
23
|
+
* The profile comes from the bearer token, so the body is only the account
|
|
24
|
+
* index. The call is idempotent on the server.
|
|
25
|
+
*
|
|
26
|
+
* @param options - Configuration object
|
|
27
|
+
* @param options.isTestnet - Whether Lighter runs on testnet (skips the call)
|
|
28
|
+
* @param options.getAccountIndex - Resolves the Lighter account index. Called
|
|
29
|
+
* before the first await so it reads the account that placed the order.
|
|
30
|
+
* @returns Result object with success flag and optional error message
|
|
31
|
+
*/
|
|
32
|
+
enroll(options: {
|
|
33
|
+
isTestnet: boolean;
|
|
34
|
+
getAccountIndex: () => Promise<number>;
|
|
35
|
+
}): Promise<{
|
|
36
|
+
success: boolean;
|
|
37
|
+
error?: string;
|
|
38
|
+
}>;
|
|
39
|
+
}
|
|
40
|
+
//# sourceMappingURL=LighterNotificationEnrollmentService.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"LighterNotificationEnrollmentService.d.ts","sourceRoot":"","sources":["../../src/services/LighterNotificationEnrollmentService.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAO1E;;;;;;;GAOG;AACH,qBAAa,oCAAoC;;IAK/C;;;;;OAKG;IACH,YACE,IAAI,EAAE,yBAAyB,EAC/B,SAAS,EAAE,4BAA4B,EAIxC;IAED;;;;;;;;;;;OAWG;IACG,MAAM,CAAC,OAAO,EAAE;QACpB,SAAS,EAAE,OAAO,CAAC;QACnB,eAAe,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;KACxC,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CA2EhD;CAcF"}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { NOTIFY_PERPS_API_CONFIG, PERPS_CONSTANTS, } from '../constants/perpsConfig.js';
|
|
2
|
+
import { ensureError } from '../utils/errorUtils.js';
|
|
3
|
+
import { getOptionalBearerToken } from './getOptionalBearerToken.js';
|
|
4
|
+
const delay = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
5
|
+
/**
|
|
6
|
+
* LighterNotificationEnrollmentService
|
|
7
|
+
*
|
|
8
|
+
* Tells notify-perps which Lighter account to watch for the signed-in profile.
|
|
9
|
+
* Mirrors the order reporting done for Hyperliquid (`DataLakeService`): meant
|
|
10
|
+
* to be fired without awaiting, retries with exponential backoff, never
|
|
11
|
+
* throws, and only logs failures.
|
|
12
|
+
*/
|
|
13
|
+
export class LighterNotificationEnrollmentService {
|
|
14
|
+
#deps;
|
|
15
|
+
#messenger;
|
|
16
|
+
/**
|
|
17
|
+
* Create a new LighterNotificationEnrollmentService instance
|
|
18
|
+
*
|
|
19
|
+
* @param deps - Platform dependencies for logging.
|
|
20
|
+
* @param messenger - Controller messenger for cross-controller communication.
|
|
21
|
+
*/
|
|
22
|
+
constructor(deps, messenger) {
|
|
23
|
+
this.#deps = deps;
|
|
24
|
+
this.#messenger = messenger;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Enroll the Lighter account with notify-perps.
|
|
28
|
+
*
|
|
29
|
+
* The profile comes from the bearer token, so the body is only the account
|
|
30
|
+
* index. The call is idempotent on the server.
|
|
31
|
+
*
|
|
32
|
+
* @param options - Configuration object
|
|
33
|
+
* @param options.isTestnet - Whether Lighter runs on testnet (skips the call)
|
|
34
|
+
* @param options.getAccountIndex - Resolves the Lighter account index. Called
|
|
35
|
+
* before the first await so it reads the account that placed the order.
|
|
36
|
+
* @returns Result object with success flag and optional error message
|
|
37
|
+
*/
|
|
38
|
+
async enroll(options) {
|
|
39
|
+
const { isTestnet, getAccountIndex } = options;
|
|
40
|
+
if (isTestnet) {
|
|
41
|
+
this.#deps.debugLogger.log('Lighter notification enrollment: Skipping for testnet');
|
|
42
|
+
return { success: true, error: 'Skipped for testnet' };
|
|
43
|
+
}
|
|
44
|
+
const baseUrl = this.#deps.notifyPerpsApi?.baseUrl;
|
|
45
|
+
if (!baseUrl) {
|
|
46
|
+
this.#deps.debugLogger.log('Lighter notification enrollment: No base URL configured');
|
|
47
|
+
return { success: false, error: 'No base URL configured' };
|
|
48
|
+
}
|
|
49
|
+
let attempt = 0;
|
|
50
|
+
let lastError = 'Unknown error';
|
|
51
|
+
try {
|
|
52
|
+
const [token, accountIndex] = await Promise.all([
|
|
53
|
+
getOptionalBearerToken(this.#messenger),
|
|
54
|
+
getAccountIndex(),
|
|
55
|
+
]);
|
|
56
|
+
if (!token) {
|
|
57
|
+
this.#deps.debugLogger.log('Lighter notification enrollment: No token available');
|
|
58
|
+
return { success: false, error: 'No token available' };
|
|
59
|
+
}
|
|
60
|
+
const body = JSON.stringify({ account_index: accountIndex });
|
|
61
|
+
const url = `${baseUrl.replace(/\/$/u, '')}${NOTIFY_PERPS_API_CONFIG.LighterNotificationAccountsPath}`;
|
|
62
|
+
for (; attempt <= NOTIFY_PERPS_API_CONFIG.MaxRetries; attempt++) {
|
|
63
|
+
if (attempt > 0) {
|
|
64
|
+
await delay(NOTIFY_PERPS_API_CONFIG.RetryDelayMs * 2 ** (attempt - 1));
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
const response = await fetch(url, {
|
|
68
|
+
method: 'POST',
|
|
69
|
+
headers: {
|
|
70
|
+
'Content-Type': 'application/json',
|
|
71
|
+
Authorization: `Bearer ${token}`,
|
|
72
|
+
},
|
|
73
|
+
body,
|
|
74
|
+
});
|
|
75
|
+
if (!response.ok) {
|
|
76
|
+
throw new Error(`Lighter notification enrollment API error: ${response.status}`);
|
|
77
|
+
}
|
|
78
|
+
return { success: true };
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
lastError = ensureError(error, 'LighterNotificationEnrollmentService.enroll').message;
|
|
82
|
+
this.#logError(error, attempt, attempt < NOTIFY_PERPS_API_CONFIG.MaxRetries);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
lastError = ensureError(error, 'LighterNotificationEnrollmentService.enroll').message;
|
|
88
|
+
this.#logError(error, attempt, false);
|
|
89
|
+
}
|
|
90
|
+
return { success: false, error: lastError };
|
|
91
|
+
}
|
|
92
|
+
#logError(error, retryCount, willRetry) {
|
|
93
|
+
this.#deps.logger.error(ensureError(error, 'LighterNotificationEnrollmentService.enroll'), {
|
|
94
|
+
tags: { feature: PERPS_CONSTANTS.FeatureName },
|
|
95
|
+
context: {
|
|
96
|
+
name: 'LighterNotificationEnrollmentService.enroll',
|
|
97
|
+
data: { retryCount, willRetry },
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
//# sourceMappingURL=LighterNotificationEnrollmentService.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"LighterNotificationEnrollmentService.js","sourceRoot":"","sources":["../../src/services/LighterNotificationEnrollmentService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,eAAe,GAChB,MAAM,6BAA6B,CAAC;AAGrC,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAErE,MAAM,KAAK,GAAG,KAAK,EAAE,EAAU,EAAiB,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AC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,SAAS,GAAG,WAAW,CACrB,KAAK,EACL,6CAA6C,CAC9C,CAAC,OAAO,CAAC;YACV,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;QACxC,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;IAC9C,CAAC;IAED,SAAS,CAAC,KAAc,EAAE,UAAkB,EAAE,SAAkB;QAC9D,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CACrB,WAAW,CAAC,KAAK,EAAE,6CAA6C,CAAC,EACjE;YACE,IAAI,EAAE,EAAE,OAAO,EAAE,eAAe,CAAC,WAAW,EAAE;YAC9C,OAAO,EAAE;gBACP,IAAI,EAAE,6CAA6C;gBACnD,IAAI,EAAE,EAAE,UAAU,EAAE,SAAS,EAAE;aAChC;SACF,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n NOTIFY_PERPS_API_CONFIG,\n PERPS_CONSTANTS,\n} from '../constants/perpsConfig.js';\nimport type { PerpsPlatformDependencies } from '../types/index.js';\nimport type { PerpsControllerMessengerBase } from '../types/messenger.js';\nimport { ensureError } from '../utils/errorUtils.js';\nimport { getOptionalBearerToken } from './getOptionalBearerToken.js';\n\nconst delay = async (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * LighterNotificationEnrollmentService\n *\n * Tells notify-perps which Lighter account to watch for the signed-in profile.\n * Mirrors the order reporting done for Hyperliquid (`DataLakeService`): meant\n * to be fired without awaiting, retries with exponential backoff, never\n * throws, and only logs failures.\n */\nexport class LighterNotificationEnrollmentService {\n readonly #deps: PerpsPlatformDependencies;\n\n readonly #messenger: PerpsControllerMessengerBase;\n\n /**\n * Create a new LighterNotificationEnrollmentService instance\n *\n * @param deps - Platform dependencies for logging.\n * @param messenger - Controller messenger for cross-controller communication.\n */\n constructor(\n deps: PerpsPlatformDependencies,\n messenger: PerpsControllerMessengerBase,\n ) {\n this.#deps = deps;\n this.#messenger = messenger;\n }\n\n /**\n * Enroll the Lighter account with notify-perps.\n *\n * The profile comes from the bearer token, so the body is only the account\n * index. The call is idempotent on the server.\n *\n * @param options - Configuration object\n * @param options.isTestnet - Whether Lighter runs on testnet (skips the call)\n * @param options.getAccountIndex - Resolves the Lighter account index. Called\n * before the first await so it reads the account that placed the order.\n * @returns Result object with success flag and optional error message\n */\n async enroll(options: {\n isTestnet: boolean;\n getAccountIndex: () => Promise<number>;\n }): Promise<{ success: boolean; error?: string }> {\n const { isTestnet, getAccountIndex } = options;\n\n if (isTestnet) {\n this.#deps.debugLogger.log(\n 'Lighter notification enrollment: Skipping for testnet',\n );\n return { success: true, error: 'Skipped for testnet' };\n }\n\n const baseUrl = this.#deps.notifyPerpsApi?.baseUrl;\n if (!baseUrl) {\n this.#deps.debugLogger.log(\n 'Lighter notification enrollment: No base URL configured',\n );\n return { success: false, error: 'No base URL configured' };\n }\n\n let attempt = 0;\n let lastError = 'Unknown error';\n try {\n const [token, accountIndex] = await Promise.all([\n getOptionalBearerToken(this.#messenger),\n getAccountIndex(),\n ]);\n if (!token) {\n this.#deps.debugLogger.log(\n 'Lighter notification enrollment: No token available',\n );\n return { success: false, error: 'No token available' };\n }\n const body = JSON.stringify({ account_index: accountIndex });\n const url = `${baseUrl.replace(/\\/$/u, '')}${NOTIFY_PERPS_API_CONFIG.LighterNotificationAccountsPath}`;\n\n for (; attempt <= NOTIFY_PERPS_API_CONFIG.MaxRetries; attempt++) {\n if (attempt > 0) {\n await delay(\n NOTIFY_PERPS_API_CONFIG.RetryDelayMs * 2 ** (attempt - 1),\n );\n }\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body,\n });\n if (!response.ok) {\n throw new Error(\n `Lighter notification enrollment API error: ${response.status}`,\n );\n }\n return { success: true };\n } catch (error) {\n lastError = ensureError(\n error,\n 'LighterNotificationEnrollmentService.enroll',\n ).message;\n this.#logError(\n error,\n attempt,\n attempt < NOTIFY_PERPS_API_CONFIG.MaxRetries,\n );\n }\n }\n } catch (error) {\n lastError = ensureError(\n error,\n 'LighterNotificationEnrollmentService.enroll',\n ).message;\n this.#logError(error, attempt, false);\n }\n return { success: false, error: lastError };\n }\n\n #logError(error: unknown, retryCount: number, willRetry: boolean): void {\n this.#deps.logger.error(\n ensureError(error, 'LighterNotificationEnrollmentService.enroll'),\n {\n tags: { feature: PERPS_CONSTANTS.FeatureName },\n context: {\n name: 'LighterNotificationEnrollmentService.enroll',\n data: { retryCount, willRetry },\n },\n },\n );\n }\n}\n"]}
|
|
@@ -51,6 +51,7 @@ export declare class TradingService {
|
|
|
51
51
|
reportOrderToDataLake: (params: {
|
|
52
52
|
action: 'open' | 'close';
|
|
53
53
|
symbol: string;
|
|
54
|
+
providerId?: PerpsProviderType;
|
|
54
55
|
slPrice?: number;
|
|
55
56
|
tpPrice?: number;
|
|
56
57
|
}) => Promise<{
|
|
@@ -128,6 +129,7 @@ export declare class TradingService {
|
|
|
128
129
|
reportOrderToDataLake: (params: {
|
|
129
130
|
action: 'open' | 'close';
|
|
130
131
|
symbol: string;
|
|
132
|
+
providerId?: PerpsProviderType;
|
|
131
133
|
}) => Promise<{
|
|
132
134
|
success: boolean;
|
|
133
135
|
error?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TradingService.d.ts","sourceRoot":"","sources":["../../src/services/TradingService.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAEV,aAAa,EACb,iBAAiB,EACjB,WAAW,EACX,WAAW,EACX,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,oBAAoB,EACpB,QAAQ,EACR,YAAY,EACZ,wBAAwB,EACxB,4BAA4B,EAE5B,yBAAyB,EAG1B,MAAM,mBAAmB,CAAC;AA2B3B,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAChF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;;GAGG;AACH,MAAM,MAAM,4BAA4B,GAAG;IACzC,yBAAyB,EAAE,yBAAyB,CAAC;CACtD,CAAC;AAyDF;;;;;;;;;GASG;AACH,qBAAa,cAAc;;IAezB;;;;OAIG;IACH,YAAY,IAAI,EAAE,yBAAyB,EAE1C;IAED;;;;;OAKG;IACH,yBAAyB,CACvB,cAAc,EAAE,4BAA4B,GAC3C,IAAI,CAEN;
|
|
1
|
+
{"version":3,"file":"TradingService.d.ts","sourceRoot":"","sources":["../../src/services/TradingService.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAEV,aAAa,EACb,iBAAiB,EACjB,WAAW,EACX,WAAW,EACX,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,oBAAoB,EACpB,QAAQ,EACR,YAAY,EACZ,wBAAwB,EACxB,4BAA4B,EAE5B,yBAAyB,EAG1B,MAAM,mBAAmB,CAAC;AA2B3B,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAChF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;;GAGG;AACH,MAAM,MAAM,4BAA4B,GAAG;IACzC,yBAAyB,EAAE,yBAAyB,CAAC;CACtD,CAAC;AAyDF;;;;;;;;;GASG;AACH,qBAAa,cAAc;;IAezB;;;;OAIG;IACH,YAAY,IAAI,EAAE,yBAAyB,EAE1C;IAED;;;;;OAKG;IACH,yBAAyB,CACvB,cAAc,EAAE,4BAA4B,GAC3C,IAAI,CAEN;IA+hBD;;;;;;;;;;OAUG;IACG,UAAU,CAAC,OAAO,EAAE;QACxB,QAAQ,EAAE,aAAa,CAAC;QACxB,MAAM,EA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AAC;QAC/B,OAAO,EAAE,cAAc,CAAC;KACzB,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAiHhD;IAED;;;;;;;;;OASG;IACG,YAAY,CAAC,OAAO,EAAE;QAC1B,QAAQ,EAAE,aAAa,CAAC;QACxB,QAAQ,EAAE,QAAQ,CAAC;QACnB,YAAY,CAAC,EAAE,YAAY,CAAC;QAC5B,qEAAqE;QACrE,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,OAAO,EAAE,cAAc,CAAC;KACzB,GAAG,OAAO,CAAC,WAAW,CAAC,CAkPvB;CACF"}
|
|
@@ -398,7 +398,7 @@ export class TradingService {
|
|
|
398
398
|
* @param options.reportOrderToDataLake - The report order to data lake value.
|
|
399
399
|
*/
|
|
400
400
|
async #handleOrderSuccess(options) {
|
|
401
|
-
const { params, context, reportOrderToDataLake } = options;
|
|
401
|
+
const { params, providerId, context, reportOrderToDataLake } = options;
|
|
402
402
|
// Update state on success
|
|
403
403
|
if (context.stateManager) {
|
|
404
404
|
context.stateManager.update((state) => {
|
|
@@ -414,6 +414,7 @@ export class TradingService {
|
|
|
414
414
|
reportOrderToDataLake({
|
|
415
415
|
action: 'open',
|
|
416
416
|
symbol: params.symbol,
|
|
417
|
+
...(providerId === undefined ? {} : { providerId }),
|
|
417
418
|
slPrice: params.stopLossPrice
|
|
418
419
|
? parseFloat(params.stopLossPrice)
|
|
419
420
|
: undefined,
|
|
@@ -650,8 +651,12 @@ export class TradingService {
|
|
|
650
651
|
const completionDuration = this.#deps.performance.now() - startTime;
|
|
651
652
|
if (result.success) {
|
|
652
653
|
// Handle success: state updates, data lake reporting
|
|
654
|
+
const executedVenue = result.providerId ?? params.providerId ?? provider.protocolId;
|
|
653
655
|
await this.#handleOrderSuccess({
|
|
654
656
|
params,
|
|
657
|
+
providerId: isPerpsProviderType(executedVenue)
|
|
658
|
+
? executedVenue
|
|
659
|
+
: undefined,
|
|
655
660
|
context,
|
|
656
661
|
reportOrderToDataLake,
|
|
657
662
|
});
|
|
@@ -976,11 +981,13 @@ export class TradingService {
|
|
|
976
981
|
* @param reportOrderToDataLake - The report order to data lake value.
|
|
977
982
|
* @param symbol - The trading pair symbol.
|
|
978
983
|
* @param context - The service context for dependencies.
|
|
984
|
+
* @param providerId - The venue that executed the order, when known.
|
|
979
985
|
*/
|
|
980
|
-
#handleDataLakeReporting(reportOrderToDataLake, symbol, context) {
|
|
986
|
+
#handleDataLakeReporting(reportOrderToDataLake, symbol, context, providerId) {
|
|
981
987
|
reportOrderToDataLake({
|
|
982
988
|
action: 'close',
|
|
983
989
|
symbol,
|
|
990
|
+
...(providerId === undefined ? {} : { providerId }),
|
|
984
991
|
}).catch((error) => {
|
|
985
992
|
this.#deps.logger.error(ensureError(error, 'TradingService.handleDataLakeReporting'), this.#getErrorContext(context, context.errorContext.method, {
|
|
986
993
|
operation: PERPS_ERROR_OPERATION.PositionManagement,
|
|
@@ -1859,7 +1866,8 @@ export class TradingService {
|
|
|
1859
1866
|
});
|
|
1860
1867
|
}
|
|
1861
1868
|
// Report to data lake (fire-and-forget)
|
|
1862
|
-
|
|
1869
|
+
const executedVenue = result.providerId ?? params.providerId ?? provider.protocolId;
|
|
1870
|
+
this.#handleDataLakeReporting(reportOrderToDataLake, params.symbol, context, isPerpsProviderType(executedVenue) ? executedVenue : undefined);
|
|
1863
1871
|
traceData = { success: true, filledSize: result.filledSize ?? '' };
|
|
1864
1872
|
// Invalidate standalone caches so external hooks (e.g., usePerpsPositionForAsset) refresh
|
|
1865
1873
|
this.#deps.cacheInvalidator.invalidate({ cacheType: 'positions' });
|