@metamask-previews/perps-controller 21.0.0-preview-520b89c2f → 21.0.0-preview-39f4d11cc
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/services/AccountService.d.ts.map +1 -1
- package/dist/services/AccountService.js +4 -0
- package/dist/services/AccountService.js.map +1 -1
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +5 -0
- package/dist/services/TradingService.js.map +1 -1
- package/dist/services/environmentTypeProperty.d.ts +10 -0
- package/dist/services/environmentTypeProperty.d.ts.map +1 -0
- package/dist/services/environmentTypeProperty.js +17 -0
- package/dist/services/environmentTypeProperty.js.map +1 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Accept an optional `environmentType` string on `TrackingData`, `TPSLTrackingData`, and `WithdrawParams` ([#10899](https://github.com/MetaMask/core/pull/10899)).
|
|
13
|
+
- Trade, close, cancel, order, flip, and TP/SL events that already copy attribution include `environment_type` when the field is set.
|
|
14
|
+
- An order edit includes only `environment_type` from `newOrder.trackingData`.
|
|
15
|
+
- The withdrawal `executed` and `failed` events emitted by `withdraw()` include `environment_type` the same way. Withdrawal events from `updateWithdrawalStatus` and `completeWithdrawalFromHistory` do not.
|
|
16
|
+
- The key is omitted when `environmentType` is absent.
|
|
17
|
+
|
|
10
18
|
### Fixed
|
|
11
19
|
|
|
12
20
|
- **BREAKING:** Set `USDC_ARBITRUM_TESTNET_ADDRESS` and `HYPERLIQUID_ASSET_CONFIGS.usdc.testnet` to USDC2 (`0x1baAbB04529D43a73232B713C0FE471f7c7334d5`), the token the Arbitrum Sepolia bridge credits, so testnet deposit and withdrawal routes name the token that is deposited and paid out ([#10991](https://github.com/MetaMask/core/pull/10991))
|
|
@@ -1 +1 @@
|
|
|
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;
|
|
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;AAU1E,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,CAgU1B;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"}
|
|
@@ -7,6 +7,7 @@ import { PerpsAnalyticsEvent, PerpsTraceNames, PerpsTraceOperations, } from '../
|
|
|
7
7
|
import { getSelectedEvmAccountFromMessenger } from '../utils/accountUtils.js';
|
|
8
8
|
import { PERPS_ERROR_ACTION, PERPS_ERROR_OPERATION, createPerpsErrorContext, } from '../utils/errorContext.js';
|
|
9
9
|
import { ensureError } from '../utils/errorUtils.js';
|
|
10
|
+
import { environmentTypeProperty } from './environmentTypeProperty.js';
|
|
10
11
|
/**
|
|
11
12
|
* AccountService
|
|
12
13
|
*
|
|
@@ -170,6 +171,7 @@ export class AccountService {
|
|
|
170
171
|
[PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.EXECUTED,
|
|
171
172
|
[PERPS_EVENT_PROPERTY.WITHDRAWAL_AMOUNT]: parseFloat(params.amount),
|
|
172
173
|
[PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,
|
|
174
|
+
...environmentTypeProperty(params.environmentType),
|
|
173
175
|
});
|
|
174
176
|
// Trigger account state refresh after withdrawal
|
|
175
177
|
refreshAccountState().catch((refreshError) => {
|
|
@@ -223,6 +225,7 @@ export class AccountService {
|
|
|
223
225
|
[PERPS_EVENT_PROPERTY.WITHDRAWAL_AMOUNT]: parseFloat(params.amount),
|
|
224
226
|
[PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,
|
|
225
227
|
[PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: result.error ?? 'Unknown error',
|
|
228
|
+
...environmentTypeProperty(params.environmentType),
|
|
226
229
|
});
|
|
227
230
|
traceData = {
|
|
228
231
|
success: false,
|
|
@@ -269,6 +272,7 @@ export class AccountService {
|
|
|
269
272
|
[PERPS_EVENT_PROPERTY.WITHDRAWAL_AMOUNT]: params.amount,
|
|
270
273
|
[PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,
|
|
271
274
|
[PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: errorMessage,
|
|
275
|
+
...environmentTypeProperty(params.environmentType),
|
|
272
276
|
});
|
|
273
277
|
traceData = {
|
|
274
278
|
success: false,
|
|
@@ -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,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;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAGrD;;;;;;;;;GASG;AACH,MAAM,OAAO,cAAc;IAChB,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;;;;;;;;;;OAUG;IACH,KAAK,CAAC,QAAQ,CAAC,OAKd;QACC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,mBAAmB,EAAE,GAAG,OAAO,CAAC;QAEnE,MAAM,OAAO,GAAG,MAAM,EAAE,CAAC;QACzB,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC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ACjD,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC;gBACzB,IAAI,EAAE,eAAe,CAAC,QAAQ;gBAC9B,EAAE,EAAE,OAAO;gBACX,IAAI,EAAE,SAAS;aAChB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,kBAAkB,CAAC,OAGxB;QACC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QAErC,IAAI,CAAC;YACH,OAAO,MAAM,QAAQ,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC;QACnD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CACrB,WAAW,CAAC,KAAK,EAAE,mCAAmC,CAAC,EACvD,uBAAuB,CAAC;gBACtB,WAAW,EAAE,mCAAmC;gBAChD,MAAM,EAAE,oBAAoB;gBAC5B,SAAS,EAAE;oBACT,SAAS,EAAE,qBAAqB,CAAC,mBAAmB;oBACpD,MAAM,EAAE,kBAAkB,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
|
+
{"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;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;A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AuB,CAAC;gBACtB,WAAW,EAAE,mCAAmC;gBAChD,MAAM,EAAE,oBAAoB;gBAC5B,SAAS,EAAE;oBACT,SAAS,EAAE,qBAAqB,CAAC,mBAAmB;oBACpD,MAAM,EAAE,kBAAkB,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 { environmentTypeProperty } from './environmentTypeProperty.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 ...environmentTypeProperty(params.environmentType),\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 ...environmentTypeProperty(params.environmentType),\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 ...environmentTypeProperty(params.environmentType),\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":"TradingService.d.ts","sourceRoot":"","sources":["../../src/services/TradingService.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,aAAa,EAEb,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,EAExB,yBAAyB,EAG1B,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"TradingService.d.ts","sourceRoot":"","sources":["../../src/services/TradingService.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,aAAa,EAEb,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,EAExB,yBAAyB,EAG1B,MAAM,mBAAmB,CAAC;AAkB3B,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;AAsDF;;;;;;;;;GASG;AACH,qBAAa,cAAc;;IAezB;;;;OAIG;IACH,YAAY,IAAI,EAAE,yBAAyB,EAE1C;IAED;;;;;OAKG;IACH,yBAAyB,CACvB,cAAc,EAAE,4BAA4B,GAC3C,IAAI,CAEN;IA6eD;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C,EAAE,YAAY,CAAC;QAC5B,OAAO,EAAE,cAAc,CAAC;KACzB,GAAG,OAAO,CAAC,WAAW,CAAC,CA0OvB;CACF"}
|
|
@@ -11,6 +11,7 @@ import { PERPS_ERROR_ACTION, PERPS_ERROR_OPERATION, createPerpsErrorContext, was
|
|
|
11
11
|
import { ensureError } from '../utils/errorUtils.js';
|
|
12
12
|
import { captureScaleOrderParams } from '../utils/lighterScaleOrders.js';
|
|
13
13
|
import { isLimitExecutionOrderType, SCALE_ORDER_COUNT, } from '../utils/orderTypes.js';
|
|
14
|
+
import { environmentTypeProperty } from './environmentTypeProperty.js';
|
|
14
15
|
/**
|
|
15
16
|
* Whether a write failed because the signer could not sign it (a locked
|
|
16
17
|
* keyring or account signer, or an unavailable or rejected agent). The user
|
|
@@ -126,6 +127,7 @@ export class TradingService {
|
|
|
126
127
|
if (trackingData?.hlFeeRate !== undefined) {
|
|
127
128
|
properties[PERPS_EVENT_PROPERTY.HL_FEE_RATE] = trackingData.hlFeeRate;
|
|
128
129
|
}
|
|
130
|
+
Object.assign(properties, environmentTypeProperty(trackingData?.environmentType));
|
|
129
131
|
return properties;
|
|
130
132
|
}
|
|
131
133
|
/**
|
|
@@ -1248,6 +1250,7 @@ export class TradingService {
|
|
|
1248
1250
|
[PERPS_EVENT_PROPERTY.LEVERAGE]: params.newOrder.leverage ?? 1,
|
|
1249
1251
|
[PERPS_EVENT_PROPERTY.ORDER_SIZE]: params.newOrder.size,
|
|
1250
1252
|
[PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,
|
|
1253
|
+
...environmentTypeProperty(params.newOrder.trackingData?.environmentType),
|
|
1251
1254
|
};
|
|
1252
1255
|
if (params.newOrder.price) {
|
|
1253
1256
|
editExecutedProps[PERPS_EVENT_PROPERTY.LIMIT_PRICE] = parseFloat(params.newOrder.price);
|
|
@@ -1268,6 +1271,7 @@ export class TradingService {
|
|
|
1268
1271
|
[PERPS_EVENT_PROPERTY.ORDER_SIZE]: params.newOrder.size,
|
|
1269
1272
|
[PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,
|
|
1270
1273
|
[PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: result.error ?? 'Unknown error',
|
|
1274
|
+
...environmentTypeProperty(params.newOrder.trackingData?.environmentType),
|
|
1271
1275
|
});
|
|
1272
1276
|
traceData = { success: false, error: result.error ?? 'Unknown error' };
|
|
1273
1277
|
}
|
|
@@ -1287,6 +1291,7 @@ export class TradingService {
|
|
|
1287
1291
|
[PERPS_EVENT_PROPERTY.ORDER_SIZE]: params.newOrder.size,
|
|
1288
1292
|
[PERPS_EVENT_PROPERTY.COMPLETION_DURATION]: completionDuration,
|
|
1289
1293
|
[PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: error instanceof Error ? error.message : 'Unknown error',
|
|
1294
|
+
...environmentTypeProperty(params.newOrder.trackingData?.environmentType),
|
|
1290
1295
|
});
|
|
1291
1296
|
this.#deps.logger.error(ensureError(error, 'TradingService.editOrder'), this.#getErrorContext(context, context.errorContext.method, {
|
|
1292
1297
|
operation: PERPS_ERROR_OPERATION.OrderManagement,
|