@metamask-previews/perps-controller 20.0.0-preview-44b7ded21 → 20.0.0-preview-2750df1dc
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 +8 -0
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +82 -52
- package/dist/PerpsController.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +3 -2
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +89 -29
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +1 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +113 -24
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/services/AccountService.d.ts.map +1 -1
- package/dist/services/AccountService.js +26 -19
- package/dist/services/AccountService.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +13 -14
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +143 -92
- package/dist/services/TradingService.js.map +1 -1
- package/dist/types/index.d.ts +13 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/errorContext.d.ts +78 -0
- package/dist/utils/errorContext.d.ts.map +1 -0
- package/dist/utils/errorContext.js +92 -0
- package/dist/utils/errorContext.js.map +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AccountService.d.ts","sourceRoot":"","sources":["../../src/services/AccountService.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"AccountService.d.ts","sourceRoot":"","sources":["../../src/services/AccountService.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EACd,cAAc,EACd,yBAAyB,EAC1B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAS1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;;;;;;;;GASG;AACH,qBAAa,cAAc;;IAKzB;;;;;OAKG;IACH,YACE,IAAI,EAAE,yBAAyB,EAC/B,SAAS,EAAE,4BAA4B,EAIxC;IAED;;;;;;;;;;OAUG;IACG,QAAQ,CAAC,OAAO,EAAE;QACtB,QAAQ,EAAE,aAAa,CAAC;QACxB,MAAM,EAAE,cAAc,CAAC;QACvB,OAAO,EAAE,cAAc,CAAC;QACxB,mBAAmB,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;KAC1C,GAAG,OAAO,CAAC,cAAc,CAAC,CA6T1B;IAED;;;;;;;OAOG;IACG,kBAAkB,CAAC,OAAO,EAAE;QAChC,QAAQ,EAAE,aAAa,CAAC;QACxB,MAAM,EAAE,cAAc,CAAC;KACxB,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAoBhD;CACF"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { v4 as uuidv4 } from 'uuid';
|
|
2
2
|
import { PERPS_EVENT_PROPERTY, PERPS_EVENT_VALUE, } from '../constants/eventNames.js';
|
|
3
3
|
import { USDC_SYMBOL } from '../constants/hyperLiquidConfig.js';
|
|
4
|
-
import {
|
|
4
|
+
import { WITHDRAWAL_CONSTANTS } from '../constants/perpsConfig.js';
|
|
5
5
|
import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
|
|
6
6
|
import { PerpsAnalyticsEvent, PerpsTraceNames, PerpsTraceOperations, } from '../types/index.js';
|
|
7
7
|
import { getSelectedEvmAccountFromMessenger } from '../utils/accountUtils.js';
|
|
8
|
+
import { PERPS_ERROR_ACTION, PERPS_ERROR_OPERATION, createPerpsErrorContext, } from '../utils/errorContext.js';
|
|
8
9
|
import { ensureError } from '../utils/errorUtils.js';
|
|
9
10
|
/**
|
|
10
11
|
* AccountService
|
|
@@ -172,13 +173,15 @@ export class AccountService {
|
|
|
172
173
|
});
|
|
173
174
|
// Trigger account state refresh after withdrawal
|
|
174
175
|
refreshAccountState().catch((refreshError) => {
|
|
175
|
-
this.#deps.logger.error(ensureError(refreshError, 'AccountService.withdraw'), {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
176
|
+
this.#deps.logger.error(ensureError(refreshError, 'AccountService.withdraw'), createPerpsErrorContext({
|
|
177
|
+
contextName: 'AccountService.withdraw',
|
|
178
|
+
method: 'withdraw',
|
|
179
|
+
errorTags: {
|
|
180
|
+
operation: PERPS_ERROR_OPERATION.FinancialOperations,
|
|
181
|
+
action: PERPS_ERROR_ACTION.FinancialWithdrawal,
|
|
180
182
|
},
|
|
181
|
-
|
|
183
|
+
data: { operation: 'refreshAccountState' },
|
|
184
|
+
}));
|
|
182
185
|
});
|
|
183
186
|
// Invalidate standalone caches so external hooks (e.g., usePerpsPositionForAsset) refresh
|
|
184
187
|
this.#deps.cacheInvalidator.invalidate({ cacheType: 'accountState' });
|
|
@@ -231,13 +234,15 @@ export class AccountService {
|
|
|
231
234
|
const errorMessage = error instanceof Error
|
|
232
235
|
? error.message
|
|
233
236
|
: PERPS_ERROR_CODES.WITHDRAW_FAILED;
|
|
234
|
-
this.#deps.logger.error(ensureError(error, 'AccountService.withdraw'), {
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
237
|
+
this.#deps.logger.error(ensureError(error, 'AccountService.withdraw'), createPerpsErrorContext({
|
|
238
|
+
contextName: 'AccountService.withdraw',
|
|
239
|
+
method: 'withdraw',
|
|
240
|
+
errorTags: {
|
|
241
|
+
operation: PERPS_ERROR_OPERATION.FinancialOperations,
|
|
242
|
+
action: PERPS_ERROR_ACTION.FinancialWithdrawal,
|
|
239
243
|
},
|
|
240
|
-
|
|
244
|
+
data: { assetId: params.assetId, amount: params.amount },
|
|
245
|
+
}));
|
|
241
246
|
if (context.stateManager) {
|
|
242
247
|
context.stateManager.update((state) => {
|
|
243
248
|
state.lastError = errorMessage;
|
|
@@ -293,13 +298,15 @@ export class AccountService {
|
|
|
293
298
|
return await provider.validateWithdrawal(params);
|
|
294
299
|
}
|
|
295
300
|
catch (error) {
|
|
296
|
-
this.#deps.logger.error(ensureError(error, 'AccountService.validateWithdrawal'), {
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
+
this.#deps.logger.error(ensureError(error, 'AccountService.validateWithdrawal'), createPerpsErrorContext({
|
|
302
|
+
contextName: 'AccountService.validateWithdrawal',
|
|
303
|
+
method: 'validateWithdrawal',
|
|
304
|
+
errorTags: {
|
|
305
|
+
operation: PERPS_ERROR_OPERATION.FinancialOperations,
|
|
306
|
+
action: PERPS_ERROR_ACTION.FinancialWithdrawal,
|
|
301
307
|
},
|
|
302
|
-
|
|
308
|
+
data: { params },
|
|
309
|
+
}));
|
|
303
310
|
throw error;
|
|
304
311
|
}
|
|
305
312
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AccountService.js","sourceRoot":"","sources":["../../src/services/AccountService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EACL,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,mCAAmC,CAAC;AAChE,OAAO,EACL,eAAe,EACf,oBAAoB,GACrB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAS3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,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,\n PERPS_EVENT_VALUE,\n} from '../constants/eventNames.js';\nimport { USDC_SYMBOL } from '../constants/hyperLiquidConfig.js';\nimport {\n PERPS_CONSTANTS,\n WITHDRAWAL_CONSTANTS,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport {\n PerpsAnalyticsEvent,\n PerpsTraceNames,\n PerpsTraceOperations,\n} from '../types/index.js';\nimport type {\n PerpsProvider,\n WithdrawParams,\n WithdrawResult,\n PerpsPlatformDependencies,\n} from '../types/index.js';\nimport type { PerpsControllerMessengerBase } from '../types/messenger.js';\nimport type { TransactionStatus } from '../types/transactionTypes.js';\nimport { getSelectedEvmAccountFromMessenger } from '../utils/accountUtils.js';\nimport { ensureError } from '../utils/errorUtils.js';\nimport type { ServiceContext } from './ServiceContext.js';\n\n/**\n * AccountService\n *\n * Handles account operations (deposits, withdrawals).\n * Stateless service that delegates to provider.\n * Controller handles state updates and analytics.\n *\n * Instance-based service with constructor injection of platform dependencies\n * and messenger for inter-controller communication.\n */\nexport class AccountService {\n readonly #deps: PerpsPlatformDependencies;\n\n readonly #messenger: PerpsControllerMessengerBase;\n\n /**\n * Create a new AccountService 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 * Withdraw funds with full orchestration\n * Handles tracing, state management, analytics, and account refresh\n *\n * @param options - The withdrawal configuration.\n * @param options.provider - The perps provider to execute the withdrawal.\n * @param options.params - The withdrawal parameters (amount, destination, etc.).\n * @param options.context - The service context for tracing and dependencies.\n * @param options.refreshAccountState - Callback to refresh account state after withdrawal.\n * @returns The withdrawal result containing success status and transaction details.\n */\n async withdraw(options: {\n provider: PerpsProvider;\n params: WithdrawParams;\n context: ServiceContext;\n refreshAccountState: () => Promise<void>;\n }): Promise<WithdrawResult> {\n const { provider, params, context, refreshAccountState } = options;\n\n const traceId = uuidv4();\n const startTime = this.#deps.performance.now();\n let traceData:\n | {\n success: boolean;\n error?: string;\n txHash?: string;\n withdrawalId?: string;\n }\n | undefined;\n\n // Generate withdrawal request ID for tracking\n const currentWithdrawalId = `withdraw-${Date.now()}-${Math.random()\n .toString(36)\n .substring(2, 11)}`;\n\n try {\n this.#deps.tracer.trace({\n name: PerpsTraceNames.Withdraw,\n id: traceId,\n op: PerpsTraceOperations.Operation,\n tags: {\n assetId: params.assetId ?? '',\n provider: context.tracingContext.provider,\n isTestnet: String(context.tracingContext.isTestnet),\n },\n });\n\n this.#deps.debugLogger.log('AccountService: STARTING WITHDRAWAL', {\n params,\n timestamp: new Date().toISOString(),\n assetId: params.assetId,\n amount: params.amount,\n destination: params.destination,\n activeProvider: context.tracingContext.provider,\n isTestnet: context.tracingContext.isTestnet,\n });\n\n // Set withdrawal in progress\n if (context.stateManager) {\n context.stateManager.update((state) => {\n state.withdrawInProgress = true;\n\n // Calculate net amount after fees\n const grossAmount = parseFloat(params.amount);\n const feeAmount = WITHDRAWAL_CONSTANTS.DefaultFeeAmount;\n const netAmount = Math.max(0, grossAmount - feeAmount);\n\n // Get current account address via messenger\n const evmAccount = getSelectedEvmAccountFromMessenger(\n this.#messenger,\n );\n const accountAddress = evmAccount?.address ?? 'unknown';\n\n this.#deps.debugLogger.log(\n 'AccountService: Creating withdrawal request',\n {\n accountAddress,\n hasEvmAccount: Boolean(evmAccount),\n evmAccountAddress: evmAccount?.address,\n amount: netAmount.toString(),\n },\n );\n\n // Add withdrawal request to tracking\n const withdrawalRequest = {\n id: currentWithdrawalId,\n timestamp: Date.now(),\n amount: netAmount.toString(), // Use net amount (after fees)\n asset: USDC_SYMBOL,\n accountAddress, // Track which account initiated withdrawal\n success: false, // Will be updated when transaction completes\n txHash: undefined,\n status: 'pending' as TransactionStatus,\n destination: params.destination,\n transactionId: undefined, // Will be set to withdrawalId when available\n };\n\n state.withdrawalRequests.unshift(withdrawalRequest);\n });\n }\n\n this.#deps.debugLogger.log('AccountService: DELEGATING TO PROVIDER', {\n provider: context.tracingContext.provider,\n providerReady: Boolean(provider),\n });\n\n // Execute withdrawal\n const result = await provider.withdraw(params);\n\n this.#deps.debugLogger.log('AccountService: WITHDRAWAL RESULT', {\n success: result.success,\n error: result.error,\n txHash: result.txHash,\n timestamp: new Date().toISOString(),\n });\n\n // Update state based on result\n if (result.success) {\n if (context.stateManager) {\n context.stateManager.update((state) => {\n state.lastError = null;\n state.lastUpdateTimestamp = Date.now();\n\n const withdrawalRequestIndex = state.withdrawalRequests.findIndex(\n (req) => req.id === currentWithdrawalId,\n );\n\n if (result.txHash) {\n // Direct completion: remove from queue and record the txHash\n // so the polling hook won't re-match this completion.\n // We do NOT update lastCompletedWithdrawalTimestamp here\n // because Date.now() is local device time while the FIFO guard\n // compares against API server timestamps — mixing domains can\n // poison the guard. The txHash exclusion alone prevents\n // re-matching since the item is also spliced from the queue.\n if (withdrawalRequestIndex !== -1) {\n state.withdrawalRequests.splice(withdrawalRequestIndex, 1);\n }\n\n state.lastCompletedWithdrawalTxHashes.push(result.txHash);\n\n const hasOtherPending = state.withdrawalRequests.some(\n (req) => req.status === 'pending' || req.status === 'bridging',\n );\n state.withdrawInProgress = hasOtherPending;\n } else if (withdrawalRequestIndex !== -1) {\n const requestToUpdate =\n state.withdrawalRequests[withdrawalRequestIndex];\n // Withdrawal is bridging (no txHash yet)\n requestToUpdate.status = 'bridging';\n requestToUpdate.success = true;\n if (result.withdrawalId) {\n requestToUpdate.withdrawalId = result.withdrawalId;\n }\n }\n\n // Set lastWithdrawResult when submission is successful (even if bridging)\n // This triggers the \"confirmed\" toast telling user funds arrive in ~5 mins\n state.lastWithdrawResult = {\n success: true,\n txHash: result.txHash ?? '',\n amount: params.amount,\n asset: USDC_SYMBOL,\n timestamp: Date.now(),\n error: '',\n };\n });\n }\n\n this.#deps.debugLogger.log('AccountService: WITHDRAWAL SUCCESSFUL', {\n txHash: result.txHash,\n amount: params.amount,\n assetId: params.assetId,\n withdrawalId: result.withdrawalId,\n });\n\n // Track withdrawal transaction executed\n const completionDuration = this.#deps.performance.now() - startTime;\n this.#deps.metrics.trackPerpsEvent(\n PerpsAnalyticsEvent.WithdrawalTransaction,\n {\n [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.EXECUTED,\n [PERPS_EVENT_PROPERTY.WITHDRAWAL_AMOUNT]: parseFloat(params.amount),\n [PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,\n },\n );\n\n // Trigger account state refresh after withdrawal\n refreshAccountState().catch((refreshError) => {\n this.#deps.logger.error(\n ensureError(refreshError, 'AccountService.withdraw'),\n {\n tags: { feature: PERPS_CONSTANTS.FeatureName },\n context: {\n name: 'AccountService.withdraw',\n data: { operation: 'refreshAccountState' },\n },\n },\n );\n });\n\n // Invalidate standalone caches so external hooks (e.g., usePerpsPositionForAsset) refresh\n this.#deps.cacheInvalidator.invalidate({ cacheType: 'accountState' });\n\n traceData = {\n success: true,\n txHash: result.txHash ?? '',\n withdrawalId: result.withdrawalId ?? '',\n };\n\n return result;\n }\n\n // Handle failure\n if (context.stateManager) {\n context.stateManager.update((state) => {\n state.lastError = result.error ?? PERPS_ERROR_CODES.WITHDRAW_FAILED;\n state.lastUpdateTimestamp = Date.now();\n state.lastWithdrawResult = {\n success: false,\n error: result.error ?? PERPS_ERROR_CODES.WITHDRAW_FAILED,\n amount: params.amount,\n asset: USDC_SYMBOL,\n timestamp: Date.now(),\n txHash: '',\n };\n\n const withdrawalRequestIndex = state.withdrawalRequests.findIndex(\n (req) => req.id === currentWithdrawalId,\n );\n if (withdrawalRequestIndex !== -1) {\n state.withdrawalRequests.splice(withdrawalRequestIndex, 1);\n }\n state.withdrawInProgress = state.withdrawalRequests.some(\n (req) => req.status === 'pending' || req.status === 'bridging',\n );\n });\n }\n\n this.#deps.debugLogger.log('AccountService: WITHDRAWAL FAILED', {\n error: result.error,\n params,\n });\n\n // Track withdrawal transaction failed\n const completionDuration = this.#deps.performance.now() - startTime;\n this.#deps.metrics.trackPerpsEvent(\n PerpsAnalyticsEvent.WithdrawalTransaction,\n {\n [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.FAILED,\n [PERPS_EVENT_PROPERTY.WITHDRAWAL_AMOUNT]: parseFloat(params.amount),\n [PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: result.error ?? 'Unknown error',\n },\n );\n\n traceData = {\n success: false,\n error: result.error ?? 'Unknown error',\n };\n\n return result;\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : PERPS_ERROR_CODES.WITHDRAW_FAILED;\n\n this.#deps.logger.error(ensureError(error, 'AccountService.withdraw'), {\n tags: { feature: PERPS_CONSTANTS.FeatureName },\n context: {\n name: 'AccountService.withdraw',\n data: { assetId: params.assetId, amount: params.amount },\n },\n });\n\n if (context.stateManager) {\n context.stateManager.update((state) => {\n state.lastError = errorMessage;\n state.lastUpdateTimestamp = Date.now();\n state.lastWithdrawResult = {\n success: false,\n error: errorMessage,\n amount: '0',\n asset: USDC_SYMBOL,\n timestamp: Date.now(),\n txHash: '',\n };\n\n const withdrawalRequestIndex = state.withdrawalRequests.findIndex(\n (req) => req.id === currentWithdrawalId,\n );\n if (withdrawalRequestIndex !== -1) {\n state.withdrawalRequests.splice(withdrawalRequestIndex, 1);\n }\n state.withdrawInProgress = state.withdrawalRequests.some(\n (req) => req.status === 'pending' || req.status === 'bridging',\n );\n });\n }\n\n // Track withdrawal transaction failed (catch block)\n const completionDuration = this.#deps.performance.now() - startTime;\n this.#deps.metrics.trackPerpsEvent(\n PerpsAnalyticsEvent.WithdrawalTransaction,\n {\n [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.FAILED,\n [PERPS_EVENT_PROPERTY.WITHDRAWAL_AMOUNT]: params.amount,\n [PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: errorMessage,\n },\n );\n\n traceData = {\n success: false,\n error: errorMessage,\n };\n\n return { success: false, error: errorMessage };\n } finally {\n this.#deps.tracer.endTrace({\n name: PerpsTraceNames.Withdraw,\n id: traceId,\n data: traceData,\n });\n }\n }\n\n /**\n * Validate withdrawal parameters\n *\n * @param options - The validation configuration.\n * @param options.provider - The perps provider to validate against.\n * @param options.params - The withdrawal parameters to validate.\n * @returns An object indicating whether the withdrawal is valid, with an optional error message.\n */\n async validateWithdrawal(options: {\n provider: PerpsProvider;\n params: WithdrawParams;\n }): Promise<{ isValid: boolean; error?: string }> {\n const { provider, params } = options;\n\n try {\n return await provider.validateWithdrawal(params);\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, 'AccountService.validateWithdrawal'),\n {\n tags: { feature: PERPS_CONSTANTS.FeatureName },\n context: {\n name: 'AccountService.validateWithdrawal',\n data: { params },\n },\n },\n );\n throw error;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AccountService.js","sourceRoot":"","sources":["../../src/services/AccountService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EACL,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,mCAAmC,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAS3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,0BAA0B,CAAC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CAAC,mBAAmB;iBAC/C;gBACD,IAAI,EAAE,EAAE,MAAM,EAAE;aACjB,CAAC,CACH,CAAC;YACF,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import { v4 as uuidv4 } from 'uuid';\n\nimport {\n PERPS_EVENT_PROPERTY,\n PERPS_EVENT_VALUE,\n} from '../constants/eventNames.js';\nimport { USDC_SYMBOL } from '../constants/hyperLiquidConfig.js';\nimport { WITHDRAWAL_CONSTANTS } from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport {\n PerpsAnalyticsEvent,\n PerpsTraceNames,\n PerpsTraceOperations,\n} from '../types/index.js';\nimport type {\n PerpsProvider,\n WithdrawParams,\n WithdrawResult,\n PerpsPlatformDependencies,\n} from '../types/index.js';\nimport type { PerpsControllerMessengerBase } from '../types/messenger.js';\nimport type { TransactionStatus } from '../types/transactionTypes.js';\nimport { getSelectedEvmAccountFromMessenger } from '../utils/accountUtils.js';\nimport {\n PERPS_ERROR_ACTION,\n PERPS_ERROR_OPERATION,\n createPerpsErrorContext,\n} from '../utils/errorContext.js';\nimport { ensureError } from '../utils/errorUtils.js';\nimport type { ServiceContext } from './ServiceContext.js';\n\n/**\n * AccountService\n *\n * Handles account operations (deposits, withdrawals).\n * Stateless service that delegates to provider.\n * Controller handles state updates and analytics.\n *\n * Instance-based service with constructor injection of platform dependencies\n * and messenger for inter-controller communication.\n */\nexport class AccountService {\n readonly #deps: PerpsPlatformDependencies;\n\n readonly #messenger: PerpsControllerMessengerBase;\n\n /**\n * Create a new AccountService 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 * Withdraw funds with full orchestration\n * Handles tracing, state management, analytics, and account refresh\n *\n * @param options - The withdrawal configuration.\n * @param options.provider - The perps provider to execute the withdrawal.\n * @param options.params - The withdrawal parameters (amount, destination, etc.).\n * @param options.context - The service context for tracing and dependencies.\n * @param options.refreshAccountState - Callback to refresh account state after withdrawal.\n * @returns The withdrawal result containing success status and transaction details.\n */\n async withdraw(options: {\n provider: PerpsProvider;\n params: WithdrawParams;\n context: ServiceContext;\n refreshAccountState: () => Promise<void>;\n }): Promise<WithdrawResult> {\n const { provider, params, context, refreshAccountState } = options;\n\n const traceId = uuidv4();\n const startTime = this.#deps.performance.now();\n let traceData:\n | {\n success: boolean;\n error?: string;\n txHash?: string;\n withdrawalId?: string;\n }\n | undefined;\n\n // Generate withdrawal request ID for tracking\n const currentWithdrawalId = `withdraw-${Date.now()}-${Math.random()\n .toString(36)\n .substring(2, 11)}`;\n\n try {\n this.#deps.tracer.trace({\n name: PerpsTraceNames.Withdraw,\n id: traceId,\n op: PerpsTraceOperations.Operation,\n tags: {\n assetId: params.assetId ?? '',\n provider: context.tracingContext.provider,\n isTestnet: String(context.tracingContext.isTestnet),\n },\n });\n\n this.#deps.debugLogger.log('AccountService: STARTING WITHDRAWAL', {\n params,\n timestamp: new Date().toISOString(),\n assetId: params.assetId,\n amount: params.amount,\n destination: params.destination,\n activeProvider: context.tracingContext.provider,\n isTestnet: context.tracingContext.isTestnet,\n });\n\n // Set withdrawal in progress\n if (context.stateManager) {\n context.stateManager.update((state) => {\n state.withdrawInProgress = true;\n\n // Calculate net amount after fees\n const grossAmount = parseFloat(params.amount);\n const feeAmount = WITHDRAWAL_CONSTANTS.DefaultFeeAmount;\n const netAmount = Math.max(0, grossAmount - feeAmount);\n\n // Get current account address via messenger\n const evmAccount = getSelectedEvmAccountFromMessenger(\n this.#messenger,\n );\n const accountAddress = evmAccount?.address ?? 'unknown';\n\n this.#deps.debugLogger.log(\n 'AccountService: Creating withdrawal request',\n {\n accountAddress,\n hasEvmAccount: Boolean(evmAccount),\n evmAccountAddress: evmAccount?.address,\n amount: netAmount.toString(),\n },\n );\n\n // Add withdrawal request to tracking\n const withdrawalRequest = {\n id: currentWithdrawalId,\n timestamp: Date.now(),\n amount: netAmount.toString(), // Use net amount (after fees)\n asset: USDC_SYMBOL,\n accountAddress, // Track which account initiated withdrawal\n success: false, // Will be updated when transaction completes\n txHash: undefined,\n status: 'pending' as TransactionStatus,\n destination: params.destination,\n transactionId: undefined, // Will be set to withdrawalId when available\n };\n\n state.withdrawalRequests.unshift(withdrawalRequest);\n });\n }\n\n this.#deps.debugLogger.log('AccountService: DELEGATING TO PROVIDER', {\n provider: context.tracingContext.provider,\n providerReady: Boolean(provider),\n });\n\n // Execute withdrawal\n const result = await provider.withdraw(params);\n\n this.#deps.debugLogger.log('AccountService: WITHDRAWAL RESULT', {\n success: result.success,\n error: result.error,\n txHash: result.txHash,\n timestamp: new Date().toISOString(),\n });\n\n // Update state based on result\n if (result.success) {\n if (context.stateManager) {\n context.stateManager.update((state) => {\n state.lastError = null;\n state.lastUpdateTimestamp = Date.now();\n\n const withdrawalRequestIndex = state.withdrawalRequests.findIndex(\n (req) => req.id === currentWithdrawalId,\n );\n\n if (result.txHash) {\n // Direct completion: remove from queue and record the txHash\n // so the polling hook won't re-match this completion.\n // We do NOT update lastCompletedWithdrawalTimestamp here\n // because Date.now() is local device time while the FIFO guard\n // compares against API server timestamps — mixing domains can\n // poison the guard. The txHash exclusion alone prevents\n // re-matching since the item is also spliced from the queue.\n if (withdrawalRequestIndex !== -1) {\n state.withdrawalRequests.splice(withdrawalRequestIndex, 1);\n }\n\n state.lastCompletedWithdrawalTxHashes.push(result.txHash);\n\n const hasOtherPending = state.withdrawalRequests.some(\n (req) => req.status === 'pending' || req.status === 'bridging',\n );\n state.withdrawInProgress = hasOtherPending;\n } else if (withdrawalRequestIndex !== -1) {\n const requestToUpdate =\n state.withdrawalRequests[withdrawalRequestIndex];\n // Withdrawal is bridging (no txHash yet)\n requestToUpdate.status = 'bridging';\n requestToUpdate.success = true;\n if (result.withdrawalId) {\n requestToUpdate.withdrawalId = result.withdrawalId;\n }\n }\n\n // Set lastWithdrawResult when submission is successful (even if bridging)\n // This triggers the \"confirmed\" toast telling user funds arrive in ~5 mins\n state.lastWithdrawResult = {\n success: true,\n txHash: result.txHash ?? '',\n amount: params.amount,\n asset: USDC_SYMBOL,\n timestamp: Date.now(),\n error: '',\n };\n });\n }\n\n this.#deps.debugLogger.log('AccountService: WITHDRAWAL SUCCESSFUL', {\n txHash: result.txHash,\n amount: params.amount,\n assetId: params.assetId,\n withdrawalId: result.withdrawalId,\n });\n\n // Track withdrawal transaction executed\n const completionDuration = this.#deps.performance.now() - startTime;\n this.#deps.metrics.trackPerpsEvent(\n PerpsAnalyticsEvent.WithdrawalTransaction,\n {\n [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.EXECUTED,\n [PERPS_EVENT_PROPERTY.WITHDRAWAL_AMOUNT]: parseFloat(params.amount),\n [PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,\n },\n );\n\n // Trigger account state refresh after withdrawal\n refreshAccountState().catch((refreshError) => {\n this.#deps.logger.error(\n ensureError(refreshError, 'AccountService.withdraw'),\n createPerpsErrorContext({\n contextName: 'AccountService.withdraw',\n method: 'withdraw',\n errorTags: {\n operation: PERPS_ERROR_OPERATION.FinancialOperations,\n action: PERPS_ERROR_ACTION.FinancialWithdrawal,\n },\n data: { operation: 'refreshAccountState' },\n }),\n );\n });\n\n // Invalidate standalone caches so external hooks (e.g., usePerpsPositionForAsset) refresh\n this.#deps.cacheInvalidator.invalidate({ cacheType: 'accountState' });\n\n traceData = {\n success: true,\n txHash: result.txHash ?? '',\n withdrawalId: result.withdrawalId ?? '',\n };\n\n return result;\n }\n\n // Handle failure\n if (context.stateManager) {\n context.stateManager.update((state) => {\n state.lastError = result.error ?? PERPS_ERROR_CODES.WITHDRAW_FAILED;\n state.lastUpdateTimestamp = Date.now();\n state.lastWithdrawResult = {\n success: false,\n error: result.error ?? PERPS_ERROR_CODES.WITHDRAW_FAILED,\n amount: params.amount,\n asset: USDC_SYMBOL,\n timestamp: Date.now(),\n txHash: '',\n };\n\n const withdrawalRequestIndex = state.withdrawalRequests.findIndex(\n (req) => req.id === currentWithdrawalId,\n );\n if (withdrawalRequestIndex !== -1) {\n state.withdrawalRequests.splice(withdrawalRequestIndex, 1);\n }\n state.withdrawInProgress = state.withdrawalRequests.some(\n (req) => req.status === 'pending' || req.status === 'bridging',\n );\n });\n }\n\n this.#deps.debugLogger.log('AccountService: WITHDRAWAL FAILED', {\n error: result.error,\n params,\n });\n\n // Track withdrawal transaction failed\n const completionDuration = this.#deps.performance.now() - startTime;\n this.#deps.metrics.trackPerpsEvent(\n PerpsAnalyticsEvent.WithdrawalTransaction,\n {\n [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.FAILED,\n [PERPS_EVENT_PROPERTY.WITHDRAWAL_AMOUNT]: parseFloat(params.amount),\n [PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: result.error ?? 'Unknown error',\n },\n );\n\n traceData = {\n success: false,\n error: result.error ?? 'Unknown error',\n };\n\n return result;\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : PERPS_ERROR_CODES.WITHDRAW_FAILED;\n\n this.#deps.logger.error(\n ensureError(error, 'AccountService.withdraw'),\n createPerpsErrorContext({\n contextName: 'AccountService.withdraw',\n method: 'withdraw',\n errorTags: {\n operation: PERPS_ERROR_OPERATION.FinancialOperations,\n action: PERPS_ERROR_ACTION.FinancialWithdrawal,\n },\n data: { assetId: params.assetId, amount: params.amount },\n }),\n );\n\n if (context.stateManager) {\n context.stateManager.update((state) => {\n state.lastError = errorMessage;\n state.lastUpdateTimestamp = Date.now();\n state.lastWithdrawResult = {\n success: false,\n error: errorMessage,\n amount: '0',\n asset: USDC_SYMBOL,\n timestamp: Date.now(),\n txHash: '',\n };\n\n const withdrawalRequestIndex = state.withdrawalRequests.findIndex(\n (req) => req.id === currentWithdrawalId,\n );\n if (withdrawalRequestIndex !== -1) {\n state.withdrawalRequests.splice(withdrawalRequestIndex, 1);\n }\n state.withdrawInProgress = state.withdrawalRequests.some(\n (req) => req.status === 'pending' || req.status === 'bridging',\n );\n });\n }\n\n // Track withdrawal transaction failed (catch block)\n const completionDuration = this.#deps.performance.now() - startTime;\n this.#deps.metrics.trackPerpsEvent(\n PerpsAnalyticsEvent.WithdrawalTransaction,\n {\n [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.FAILED,\n [PERPS_EVENT_PROPERTY.WITHDRAWAL_AMOUNT]: params.amount,\n [PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,\n [PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: errorMessage,\n },\n );\n\n traceData = {\n success: false,\n error: errorMessage,\n };\n\n return { success: false, error: errorMessage };\n } finally {\n this.#deps.tracer.endTrace({\n name: PerpsTraceNames.Withdraw,\n id: traceId,\n data: traceData,\n });\n }\n }\n\n /**\n * Validate withdrawal parameters\n *\n * @param options - The validation configuration.\n * @param options.provider - The perps provider to validate against.\n * @param options.params - The withdrawal parameters to validate.\n * @returns An object indicating whether the withdrawal is valid, with an optional error message.\n */\n async validateWithdrawal(options: {\n provider: PerpsProvider;\n params: WithdrawParams;\n }): Promise<{ isValid: boolean; error?: string }> {\n const { provider, params } = options;\n\n try {\n return await provider.validateWithdrawal(params);\n } catch (error) {\n this.#deps.logger.error(\n ensureError(error, 'AccountService.validateWithdrawal'),\n createPerpsErrorContext({\n contextName: 'AccountService.validateWithdrawal',\n method: 'validateWithdrawal',\n errorTags: {\n operation: PERPS_ERROR_OPERATION.FinancialOperations,\n action: PERPS_ERROR_ACTION.FinancialWithdrawal,\n },\n data: { params },\n }),\n );\n throw error;\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HyperLiquidSubscriptionService.d.ts","sourceRoot":"","sources":["../../src/services/HyperLiquidSubscriptionService.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAMV,mBAAmB,EAKnB,gBAAgB,EAMjB,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"HyperLiquidSubscriptionService.d.ts","sourceRoot":"","sources":["../../src/services/HyperLiquidSubscriptionService.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAMV,mBAAmB,EAKnB,gBAAgB,EAMjB,MAAM,qBAAqB,CAAC;AAO7B,OAAO,KAAK,EAEV,0BAA0B,EAC3B,MAAM,+BAA+B,CAAC;AAGvC,OAAO,KAAK,EAEV,QAAQ,EACR,SAAS,EACT,KAAK,EAEL,SAAS,EACT,qBAAqB,EACrB,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,EACrB,yBAAyB,EACzB,sBAAsB,EACtB,qBAAqB,EACrB,wBAAwB,EAGxB,yBAAyB,EAG1B,MAAM,mBAAmB,CAAC;AA+B3B,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAE9E;;;GAGG;AACH,KAAK,kBAAkB,GAAG,IAAI,CAC5B,wBAAwB,EACxB,qBAAqB,GAAG,2BAA2B,CACpD,CAAC;AA0BF;;;GAGG;AACH,qBAAa,8BAA8B;;IA8VzC,YACE,aAAa,EAAE,wBAAwB,EACvC,aAAa,EAAE,kBAAkB,EACjC,oBAAoB,EAAE,yBAAyB,EAC/C,WAAW,CAAC,EAAE,OAAO,EACrB,WAAW,CAAC,EAAE,MAAM,EAAE,EACtB,gBAAgB,CAAC,EAAE,MAAM,EAAE,EAC3B,gBAAgB,CAAC,EAAE,MAAM,EAAE,EAC3B,mBAAmB,CAAC,EAAE,MAAM,EAC5B,mBAAmB,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,EAAE,CAAC,EAa9C;IAwMD;;;;;;;;OAQG;IACI,eAAe,CACpB,GAAG,EAAE,MAAM,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oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC,CAwPjD;IAED;;OAEG;IACI,QAAQ,IAAI,IAAI,CAwOtB;CACF"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
var _a;
|
|
2
2
|
import { hasProperty } from '@metamask/utils';
|
|
3
3
|
import { HYPERLIQUID_CONFIG } from '../constants/hyperLiquidConfig.js';
|
|
4
|
-
import { TP_SL_CONFIG,
|
|
4
|
+
import { TP_SL_CONFIG, ABSTRACTION_MODE_REFRESH_THROTTLE_MS, } from '../constants/perpsConfig.js';
|
|
5
5
|
import { hyperLiquidModeFoldsSpot } from '../types/hyperliquid-types.js';
|
|
6
6
|
import { WebSocketConnectionState } from '../types/index.js';
|
|
7
7
|
import { addSpotBalanceToAccountState, calculateWeightedReturnOnEquity, } from '../utils/accountUtils.js';
|
|
8
|
+
import { PERPS_ERROR_ACTION, PERPS_ERROR_COMPONENT, PERPS_ERROR_OPERATION, createPerpsErrorContext, } from '../utils/errorContext.js';
|
|
8
9
|
import { ensureError } from '../utils/errorUtils.js';
|
|
9
10
|
import { adaptPositionFromSDK, adaptOrderFromSDK, adaptAccountStateFromSDK, buildHyperLiquidFillId, parseAssetName, } from '../utils/hyperLiquidAdapter.js';
|
|
10
11
|
import { processBboData } from '../utils/hyperLiquidOrderBookProcessor.js';
|
|
@@ -357,20 +358,18 @@ export class HyperLiquidSubscriptionService {
|
|
|
357
358
|
* @private
|
|
358
359
|
*/
|
|
359
360
|
#getErrorContext(method, extra) {
|
|
360
|
-
return {
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
method,
|
|
370
|
-
...extra,
|
|
371
|
-
},
|
|
361
|
+
return createPerpsErrorContext({
|
|
362
|
+
contextName: 'HyperLiquidSubscriptionService',
|
|
363
|
+
method,
|
|
364
|
+
provider: 'hyperliquid',
|
|
365
|
+
network: this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet',
|
|
366
|
+
errorTags: {
|
|
367
|
+
operation: PERPS_ERROR_OPERATION.ConnectionManagement,
|
|
368
|
+
component: PERPS_ERROR_COMPONENT.ConnectionManager,
|
|
369
|
+
action: PERPS_ERROR_ACTION.ConnectionConnection,
|
|
372
370
|
},
|
|
373
|
-
|
|
371
|
+
data: extra,
|
|
372
|
+
});
|
|
374
373
|
}
|
|
375
374
|
/**
|
|
376
375
|
* Check if a DEX is enabled in our configuration
|