@rango-dev/queue-manager-rango-preset 0.5.1-next.0 → 0.5.1-next.10

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/src/helpers.ts CHANGED
@@ -5,16 +5,22 @@ import {
5
5
  QueueType,
6
6
  } from '@rango-dev/queue-manager-core';
7
7
  import {
8
+ ArrayElement,
8
9
  BlockReason,
10
+ StepEventType,
9
11
  SwapActionTypes,
10
12
  SwapQueueContext,
11
13
  SwapQueueDef,
12
14
  SwapStorage,
15
+ StepExecutionEventStatus,
16
+ StepExecutionBlockedEventStatus,
17
+ Step,
13
18
  } from './types';
14
19
  import {
15
20
  getBlockChainNameFromId,
16
21
  Meta,
17
22
  Network,
23
+ Networks,
18
24
  WalletState,
19
25
  WalletType,
20
26
  } from '@rango-dev/wallets-shared';
@@ -25,15 +31,10 @@ import {
25
31
  TransactionType,
26
32
  EvmBlockchainMeta,
27
33
  CreateTransactionResponse,
28
- isEvmTransaction,
29
- isCosmosTransaction,
30
- isSolanaTransaction,
31
- isTronTransaction,
32
- isStarknetTransaction,
33
- isTransferTransaction,
34
34
  } from 'rango-sdk';
35
35
 
36
36
  import {
37
+ DEFAULT_ERROR_CODE,
37
38
  ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK,
38
39
  ERROR_MESSAGE_WAIT_FOR_WALLET,
39
40
  ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION,
@@ -41,7 +42,6 @@ import {
41
42
  import { Manager } from '@rango-dev/queue-manager-core';
42
43
  import { Status } from '@rango-dev/queue-manager-core';
43
44
  import {
44
- EventType,
45
45
  getCurrentBlockchainOf,
46
46
  getCurrentBlockchainOfOrNull,
47
47
  getScannerUrl,
@@ -64,6 +64,7 @@ import {
64
64
  } from './shared-errors';
65
65
  import { httpService } from './services';
66
66
  import { APIErrorCode, SignerErrorCode } from 'rango-types/lib';
67
+ import { notifier } from './services/eventEmitter';
67
68
 
68
69
  type WhenTaskBlocked = Parameters<NonNullable<SwapQueueDef['whenTaskBlocked']>>;
69
70
  type WhenTaskBlockedEvent = WhenTaskBlocked[0];
@@ -101,7 +102,7 @@ type TransactionData = {
101
102
  receiptReceived?: boolean; // e.g. is TransactionReceipt ready in case of EVM transactions
102
103
  };
103
104
  const swapTransactionToDataMap: { [id: string]: TransactionData } = {};
104
- export function useTransactionsData() {
105
+ export function inMemoryTransactionsData() {
105
106
  return {
106
107
  getTransactionDataByHash: (hash: string) =>
107
108
  swapTransactionToDataMap[hash] || {},
@@ -206,24 +207,36 @@ export const setCurrentStepTx = (
206
207
  currentStep.tronApprovalTransaction = null;
207
208
  currentStep.tronTransaction = null;
208
209
 
209
- if (isEvmTransaction(transaction)) {
210
- if (transaction.isApprovalTx)
211
- currentStep.evmApprovalTransaction = transaction;
212
- else currentStep.evmTransaction = transaction;
213
- } else if (isCosmosTransaction(transaction)) {
214
- currentStep.cosmosTransaction = transaction;
215
- } else if (isSolanaTransaction(transaction)) {
216
- currentStep.solanaTransaction = transaction;
217
- } else if (isTransferTransaction(transaction)) {
218
- currentStep.transferTransaction = transaction;
219
- } else if (isStarknetTransaction(transaction)) {
220
- if (transaction.isApprovalTx)
221
- currentStep.starknetApprovalTransaction = transaction;
222
- else currentStep.starknetTransaction = transaction;
223
- } else if (isTronTransaction(transaction)) {
224
- if (transaction.isApprovalTx)
225
- currentStep.tronApprovalTransaction = transaction;
226
- else currentStep.tronTransaction = transaction;
210
+ const txType = transaction.type;
211
+ switch (txType) {
212
+ case TransactionType.EVM:
213
+ if (transaction.isApprovalTx)
214
+ currentStep.evmApprovalTransaction = transaction;
215
+ else currentStep.evmTransaction = transaction;
216
+ break;
217
+ case TransactionType.TRON:
218
+ if (transaction.isApprovalTx)
219
+ currentStep.tronApprovalTransaction = transaction;
220
+ else currentStep.tronTransaction = transaction;
221
+ break;
222
+ case TransactionType.STARKNET:
223
+ if (transaction.isApprovalTx)
224
+ currentStep.starknetApprovalTransaction = transaction;
225
+ else currentStep.starknetTransaction = transaction;
226
+ break;
227
+ case TransactionType.COSMOS:
228
+ currentStep.cosmosTransaction = transaction;
229
+ break;
230
+ case TransactionType.SOLANA:
231
+ currentStep.solanaTransaction = transaction;
232
+ break;
233
+ case TransactionType.TRANSFER:
234
+ currentStep.transferTransaction = transaction;
235
+ break;
236
+ default:
237
+ ((x: never) => {
238
+ throw new Error(`${x} was unhandled!`);
239
+ })(txType);
227
240
  }
228
241
  return currentStep;
229
242
  };
@@ -292,9 +305,18 @@ export function updateSwapStatus({
292
305
  }): {
293
306
  swap: PendingSwap;
294
307
  step: PendingSwapStep | null;
308
+ failureType?: APIErrorCode;
295
309
  } {
296
310
  const swap = getStorage().swapDetails;
297
311
  const currentStep = getCurrentStep(swap);
312
+ const updatedResult: {
313
+ swap: PendingSwap;
314
+ step: PendingSwapStep | null;
315
+ failureType?: APIErrorCode;
316
+ } = {
317
+ swap,
318
+ step: currentStep,
319
+ };
298
320
  if (!!nextStepStatus && !!currentStep) currentStep.status = nextStepStatus;
299
321
 
300
322
  if (nextStatus) swap.status = nextStatus;
@@ -316,11 +338,14 @@ export function updateSwapStatus({
316
338
  const walletType = getRelatedWalletOrNull(swap, currentStep!)?.walletType;
317
339
  swap.extraMessageSeverity = MessageSeverity.error;
318
340
 
341
+ const failureType = mapAppErrorCodesToAPIErrorCode(errorCode);
342
+ updatedResult.failureType = failureType;
343
+
319
344
  httpService()
320
345
  .reportFailure({
321
346
  requestId: swap.requestId,
322
347
  step: currentStep?.id || 1,
323
- eventType: mapAppErrorCodesToAPIErrorCode(errorCode),
348
+ eventType: failureType,
324
349
  reason: errorReason || '',
325
350
  data: walletType ? { wallet: walletType } : undefined,
326
351
  })
@@ -341,10 +366,7 @@ export function updateSwapStatus({
341
366
  swapDetails: swap,
342
367
  });
343
368
 
344
- return {
345
- swap,
346
- step: currentStep,
347
- };
369
+ return updatedResult;
348
370
  }
349
371
 
350
372
  /**
@@ -355,8 +377,6 @@ export function updateSwapStatus({
355
377
  export function setStepTransactionIds(
356
378
  { getStorage, setStorage }: ExecuterActions<SwapStorage, SwapActionTypes>,
357
379
  txId: string | null,
358
- notifier: SwapQueueContext['notifier'],
359
- eventType?: EventType,
360
380
  explorerUrl?: { url?: string; description?: string }
361
381
  ): void {
362
382
  const swap = getStorage().swapDetails;
@@ -373,22 +393,29 @@ export function setStepTransactionIds(
373
393
  description: explorerUrl.description || null,
374
394
  },
375
395
  ];
376
- if (eventType === 'check_tx_status') {
377
- swap.extraMessage = 'Checking transaction status ...';
378
- swap.extraMessageDetail = '';
379
- swap.extraMessageSeverity = MessageSeverity.info;
380
- } else if (eventType === 'check_approve_tx_status') {
381
- swap.extraMessage = 'Checking approve transaction status ...';
382
- swap.extraMessageDetail = '';
383
- swap.extraMessageSeverity = MessageSeverity.info;
384
- }
396
+ swap.extraMessage = 'Transaction sent ...';
397
+ swap.extraMessageDetail = '';
398
+ swap.extraMessageSeverity = MessageSeverity.info;
385
399
 
386
400
  setStorage({
387
401
  ...getStorage(),
388
402
  swapDetails: swap,
389
403
  });
390
- if (eventType)
391
- notifier({ eventType: eventType, swap: swap, step: currentStep });
404
+
405
+ notifier({
406
+ event: {
407
+ type: StepEventType.TX_EXECUTION,
408
+ status: StepExecutionEventStatus.TX_SENT,
409
+ },
410
+ swap: swap,
411
+ step: currentStep,
412
+ });
413
+
414
+ notifier({
415
+ event: { type: StepEventType.CHECK_STATUS },
416
+ swap: swap,
417
+ step: currentStep,
418
+ });
392
419
  }
393
420
 
394
421
  /**
@@ -479,10 +506,7 @@ export function markRunningSwapAsSwitchingNetwork({
479
506
  export function markRunningSwapAsDependsOnOtherQueues({
480
507
  getStorage,
481
508
  setStorage,
482
- notifier,
483
- }: Pick<ExecuterActions, 'getStorage' | 'setStorage'> & {
484
- notifier: SwapQueueContext['notifier'];
485
- }):
509
+ }: Pick<ExecuterActions, 'getStorage' | 'setStorage'>):
486
510
  | {
487
511
  swap: PendingSwap;
488
512
  step: PendingSwapStep;
@@ -497,7 +521,10 @@ export function markRunningSwapAsDependsOnOtherQueues({
497
521
  currentStep.networkStatus = PendingSwapNetworkStatus.WaitingForQueue;
498
522
 
499
523
  notifier({
500
- eventType: 'waiting_for_queue',
524
+ event: {
525
+ type: StepEventType.TX_EXECUTION_BLOCKED,
526
+ status: StepExecutionBlockedEventStatus.WAITING_FOR_QUEUE,
527
+ },
501
528
  swap,
502
529
  step: currentStep,
503
530
  });
@@ -554,7 +581,7 @@ export function isWalletNull(wallet: Wallet | null): boolean {
554
581
  export function getEvmProvider(providers: Providers, type: WalletType): any {
555
582
  if (type && providers[type]) {
556
583
  // we need this because provider can return an instance or a map of instances, so what you are doing here is try to detect that.
557
- if (providers[type].size) return providers[type].get(Network.ETHEREUM);
584
+ if (providers[type].size) return providers[type].get(Networks.ETHEREUM);
558
585
 
559
586
  return providers[type];
560
587
  }
@@ -736,11 +763,23 @@ export function onBlockForConnectWallet(
736
763
  if (!ok) {
737
764
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
738
765
  const currentStep = getCurrentStep(swap)!;
739
- context.notifier({
740
- eventType:
741
- reason === 'account_miss_match'
742
- ? 'waiting_for_change_wallet_account'
743
- : 'waiting_for_connecting_wallet',
766
+ const { type: walletType, address } = getRequiredWallet(swap);
767
+ notifier({
768
+ event: {
769
+ type: StepEventType.TX_EXECUTION_BLOCKED,
770
+ ...(reason === 'account_miss_match'
771
+ ? {
772
+ status:
773
+ StepExecutionBlockedEventStatus.WAITING_FOR_CHANGE_WALLET_ACCOUNT,
774
+ requiredAccount: address ?? undefined,
775
+ }
776
+ : {
777
+ status:
778
+ StepExecutionBlockedEventStatus.WAITING_FOR_WALLET_CONNECT,
779
+ requiredWallet: walletType ?? undefined,
780
+ requiredAccount: address ?? undefined,
781
+ }),
782
+ },
744
783
  swap: swap,
745
784
  step: currentStep,
746
785
  });
@@ -783,9 +822,22 @@ export function onBlockForChangeNetwork(
783
822
  setStorage: queue.setStorage.bind(queue),
784
823
  });
785
824
 
825
+ const requiredNetwork = getCurrentBlockchainOfOrNull(swap, currentStep);
826
+
827
+ const requiredWallet = getRequiredWallet(swap).type;
828
+
829
+ const currentNetwork = requiredWallet
830
+ ? context.state(requiredWallet).network
831
+ : undefined;
832
+
786
833
  if (result) {
787
- context.notifier({
788
- eventType: 'waiting_for_network_change',
834
+ notifier({
835
+ event: {
836
+ type: StepEventType.TX_EXECUTION_BLOCKED,
837
+ status: StepExecutionBlockedEventStatus.WAITING_FOR_NETWORK_CHANGE,
838
+ requiredNetwork: requiredNetwork ?? undefined,
839
+ currentNetwork: currentNetwork ?? undefined,
840
+ },
789
841
  swap: result.swap,
790
842
  step: result.step,
791
843
  });
@@ -844,7 +896,6 @@ export function onDependsOnOtherQueues(
844
896
  markRunningSwapAsDependsOnOtherQueues({
845
897
  getStorage: queue.getStorage.bind(queue),
846
898
  setStorage: queue.setStorage.bind(queue),
847
- notifier: context.notifier,
848
899
  });
849
900
  return;
850
901
  }
@@ -875,7 +926,6 @@ export function onDependsOnOtherQueues(
875
926
  // TODO: Use key generator
876
927
  retryOn(
877
928
  `${type}-${network}:${address}`,
878
- context.notifier,
879
929
  manager,
880
930
  context.canSwitchNetworkTo
881
931
  );
@@ -906,9 +956,9 @@ export function isRequiredWalletConnected(
906
956
  export function singTransaction(
907
957
  actions: ExecuterActions<SwapStorage, SwapActionTypes, SwapQueueContext>
908
958
  ): void {
909
- const { setTransactionDataByHash } = useTransactionsData();
959
+ const { setTransactionDataByHash } = inMemoryTransactionsData();
910
960
  const { getStorage, setStorage, failed, next, schedule, context } = actions;
911
- const { meta, getSigners, notifier, isMobileWallet } = context;
961
+ const { meta, getSigners, isMobileWallet } = context;
912
962
  const swap = getStorage().swapDetails;
913
963
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
914
964
  const currentStep = getCurrentStep(swap)!;
@@ -929,20 +979,40 @@ export function singTransaction(
929
979
  const tx = getCurrentStepTx(currentStep);
930
980
  const txType = tx?.type;
931
981
  const isApproval = isApprovalCurrentStepTx(currentStep);
932
- const isSmartContractCall = [
933
- TransactionType.EVM,
934
- TransactionType.STARKNET,
935
- TransactionType.TRON,
936
- ].includes(txType!);
982
+
983
+ if (!tx || !txType) {
984
+ const extraMessage = 'Unexpected Error: tx is null!';
985
+ const updateResult = updateSwapStatus({
986
+ getStorage,
987
+ setStorage,
988
+ nextStatus: 'failed',
989
+ nextStepStatus: 'failed',
990
+ message: extraMessage,
991
+ details: undefined,
992
+ errorCode: 'CLIENT_UNEXPECTED_BEHAVIOUR',
993
+ });
994
+ notifier({
995
+ event: {
996
+ type: StepEventType.FAILED,
997
+ reason: extraMessage,
998
+ reasonCode: 'CLIENT_UNEXPECTED_BEHAVIOUR',
999
+ },
1000
+ ...updateResult,
1001
+ });
1002
+ failed();
1003
+ return onFinish();
1004
+ }
1005
+
1006
+ const chainId = meta.blockchains?.[tx.blockChain]?.chainId;
937
1007
 
938
1008
  const hasAlreadyProceededToSign =
939
1009
  typeof swap.hasAlreadyProceededToSign === 'boolean';
940
1010
 
941
1011
  let nextStatus: SwapStatus | undefined,
942
1012
  nextStepStatus: StepStatus,
943
- eventType: EventType,
944
1013
  message: string,
945
- details: string;
1014
+ details: string,
1015
+ eventType: StepEventType;
946
1016
 
947
1017
  if (isApproval) {
948
1018
  message = `Waiting for approval of ${currentStep?.fromSymbol} coin ${
@@ -952,21 +1022,19 @@ export function singTransaction(
952
1022
  'Waiting for approve transaction to be mined and confirmed successfully';
953
1023
  nextStepStatus = 'waitingForApproval';
954
1024
  nextStatus = undefined;
955
- eventType = 'confirm_approve_contract';
1025
+ eventType = StepEventType.TX_EXECUTION;
956
1026
  } else if (hasAlreadyProceededToSign) {
957
1027
  message = 'Transaction is expired. Please try again.';
958
1028
  nextStepStatus = 'failed';
959
1029
  nextStatus = 'failed';
960
1030
  details = '';
961
- eventType = 'transaction_expired';
1031
+ eventType = StepEventType.FAILED;
962
1032
  } else {
963
1033
  message = 'Executing transaction ...';
964
1034
  nextStepStatus = 'running';
965
1035
  nextStatus = 'running';
966
1036
  details = `${mobileWallet ? 'Check your mobile phone!' : ''}`;
967
- eventType = isSmartContractCall
968
- ? 'calling_smart_contract'
969
- : 'confirm_transfer';
1037
+ eventType = StepEventType.TX_EXECUTION;
970
1038
  }
971
1039
 
972
1040
  const updateResult = updateSwapStatus({
@@ -981,18 +1049,29 @@ export function singTransaction(
981
1049
  : hasAlreadyProceededToSign,
982
1050
  errorCode: hasAlreadyProceededToSign ? 'TX_EXPIRED' : undefined,
983
1051
  });
984
- notifier({
985
- eventType,
986
- ...updateResult,
987
- });
1052
+
1053
+ if (eventType === StepEventType.FAILED) {
1054
+ notifier({
1055
+ event: {
1056
+ type: eventType,
1057
+ reason: message,
1058
+ reasonCode: updateResult.failureType ?? DEFAULT_ERROR_CODE,
1059
+ },
1060
+ ...updateResult,
1061
+ });
1062
+ } else
1063
+ notifier({
1064
+ event: { type: eventType, status: StepExecutionEventStatus.SEND_TX },
1065
+ ...updateResult,
1066
+ });
988
1067
 
989
1068
  if (hasAlreadyProceededToSign) {
990
1069
  failed();
991
1070
  onFinish();
992
1071
  return;
993
1072
  }
994
- const signer = walletSigners.getSigner(txType!);
995
- signer.signAndSendTx(tx!, walletAddress, null).then(
1073
+ const signer = walletSigners.getSigner(txType);
1074
+ signer.signAndSendTx(tx, walletAddress, chainId).then(
996
1075
  ({ hash, response }) => {
997
1076
  const explorerUrl = getScannerUrl(
998
1077
  hash,
@@ -1002,8 +1081,6 @@ export function singTransaction(
1002
1081
  setStepTransactionIds(
1003
1082
  actions,
1004
1083
  hash,
1005
- notifier,
1006
- isApproval ? 'check_approve_tx_status' : 'check_tx_status',
1007
1084
  explorerUrl
1008
1085
  ? { url: explorerUrl, description: isApproval ? 'Approve' : 'Swap' }
1009
1086
  : undefined
@@ -1021,13 +1098,7 @@ export function singTransaction(
1021
1098
  prettifyErrorMessage(error);
1022
1099
 
1023
1100
  // if it is an rpc error with details, send the log to sentry
1024
- if (
1025
- error &&
1026
- error?.root &&
1027
- error?.root?.message &&
1028
- error?.root?.code &&
1029
- error?.root?.reason
1030
- )
1101
+ if (error?.root?.message && error?.root?.code && error?.root?.reason)
1031
1102
  logRPCError(error.root, swap, currentStep, sourceWallet?.walletType);
1032
1103
 
1033
1104
  const updateResult = updateSwapStatus({
@@ -1039,14 +1110,13 @@ export function singTransaction(
1039
1110
  details: extraMessageDetail,
1040
1111
  errorCode: extraMessageErrorCode,
1041
1112
  });
1042
- const eventType =
1043
- extraMessageErrorCode === 'REJECTED_BY_USER'
1044
- ? 'contract_rejected'
1045
- : isSmartContractCall
1046
- ? 'smart_contract_call_failed'
1047
- : 'transfer_failed';
1113
+
1048
1114
  notifier({
1049
- eventType,
1115
+ event: {
1116
+ type: StepEventType.FAILED,
1117
+ reason: extraMessage,
1118
+ reasonCode: updateResult.failureType ?? DEFAULT_ERROR_CODE,
1119
+ },
1050
1120
  ...updateResult,
1051
1121
  });
1052
1122
  failed();
@@ -1059,7 +1129,6 @@ export function checkWaitingForConnectWalletChange(params: {
1059
1129
  wallet_network: string;
1060
1130
  manager?: Manager;
1061
1131
  evmChains: EvmBlockchainMeta[];
1062
- notifier: SwapQueueContext['notifier'];
1063
1132
  }): void {
1064
1133
  const { wallet_network, evmChains, manager } = params;
1065
1134
  const [wallet, network] = splitWalletNetwork(wallet_network);
@@ -1088,10 +1157,12 @@ export function checkWaitingForConnectWalletChange(params: {
1088
1157
  }
1089
1158
  );
1090
1159
 
1160
+ const requiredNetwork = getCurrentBlockchainOfOrNull(swap, currentStep);
1161
+
1091
1162
  if (
1092
1163
  currentStepRequiredWallet === wallet &&
1093
1164
  hasWaitingForConnect &&
1094
- getCurrentBlockchainOfOrNull(swap, currentStep) != network
1165
+ requiredNetwork != network
1095
1166
  ) {
1096
1167
  const queueInstance = q.list;
1097
1168
  const { type } = getRequiredWallet(swap);
@@ -1111,8 +1182,14 @@ export function checkWaitingForConnectWalletChange(params: {
1111
1182
  });
1112
1183
 
1113
1184
  if (result) {
1114
- params?.notifier({
1115
- eventType: 'waiting_for_network_change',
1185
+ notifier({
1186
+ event: {
1187
+ type: StepEventType.TX_EXECUTION_BLOCKED,
1188
+ status:
1189
+ StepExecutionBlockedEventStatus.WAITING_FOR_NETWORK_CHANGE,
1190
+ currentNetwork: network,
1191
+ requiredNetwork: requiredNetwork ?? undefined,
1192
+ },
1116
1193
  swap: result.swap,
1117
1194
  step: result.step,
1118
1195
  });
@@ -1185,21 +1262,26 @@ export function getRunningSwaps(manager: Manager): PendingSwap[] {
1185
1262
  * @param notifier
1186
1263
  * @returns
1187
1264
  */
1188
- export function resetRunningSwapNotifsOnPageLoad(
1189
- runningSwaps: PendingSwap[],
1190
- notifier: SwapQueueContext['notifier']
1191
- ) {
1265
+ export function resetRunningSwapNotifsOnPageLoad(runningSwaps: PendingSwap[]) {
1192
1266
  runningSwaps.forEach((swap) => {
1193
1267
  const currentStep = getCurrentStep(swap);
1194
- let eventType: EventType | undefined;
1268
+ const eventType = StepEventType.TX_EXECUTION_BLOCKED;
1269
+ let eventSubtype:
1270
+ | StepExecutionBlockedEventStatus.WAITING_FOR_QUEUE
1271
+ | StepExecutionBlockedEventStatus.WAITING_FOR_WALLET_CONNECT
1272
+ | undefined;
1195
1273
  if (currentStep?.networkStatus === PendingSwapNetworkStatus.WaitingForQueue)
1196
- eventType = 'waiting_for_queue';
1274
+ eventSubtype = StepExecutionBlockedEventStatus.WAITING_FOR_QUEUE;
1197
1275
  else if (swap?.status === 'running') {
1198
- eventType = 'waiting_for_connecting_wallet';
1276
+ eventSubtype = StepExecutionBlockedEventStatus.WAITING_FOR_WALLET_CONNECT;
1199
1277
  }
1200
1278
  if (!!eventType && !!notifier) {
1201
1279
  notifier({
1202
- eventType,
1280
+ event: {
1281
+ type: eventType,
1282
+ status:
1283
+ eventSubtype ?? StepExecutionBlockedEventStatus.WAITING_FOR_QUEUE,
1284
+ },
1203
1285
  swap: swap,
1204
1286
  step: currentStep,
1205
1287
  });
@@ -1220,7 +1302,6 @@ export function resetRunningSwapNotifsOnPageLoad(
1220
1302
  */
1221
1303
  export function retryOn(
1222
1304
  wallet_network: string,
1223
- notifier: SwapQueueContext['notifier'],
1224
1305
  manager?: Manager,
1225
1306
  canSwitchNetworkTo?: (type: WalletType, network: Network) => boolean,
1226
1307
  options = { fallbackToOnlyWallet: true }
@@ -1269,7 +1350,6 @@ export function retryOn(
1269
1350
  markRunningSwapAsDependsOnOtherQueues({
1270
1351
  getStorage: currentQueue.getStorage.bind(currentQueue),
1271
1352
  setStorage: currentQueue.setStorage.bind(currentQueue),
1272
- notifier: notifier,
1273
1353
  });
1274
1354
  }
1275
1355
  }
@@ -1277,8 +1357,7 @@ export function retryOn(
1277
1357
  finalQueueToBeRun = onlyWalletMatched[0];
1278
1358
  }
1279
1359
 
1280
- if (!canSwitchNetworkTo?.(wallet, network as Network))
1281
- finalQueueToBeRun?.unblock();
1360
+ if (!canSwitchNetworkTo?.(wallet, network)) finalQueueToBeRun?.unblock();
1282
1361
  else finalQueueToBeRun?.checkBlock();
1283
1362
  }
1284
1363
 
@@ -1326,8 +1405,49 @@ export function cancelSwap(
1326
1405
  nextStepStatus: 'failed',
1327
1406
  errorCode: 'USER_CANCEL',
1328
1407
  });
1408
+
1409
+ notifier({
1410
+ event: {
1411
+ type: StepEventType.FAILED,
1412
+ reasonCode: 'USER_CANCEL',
1413
+ reason: updateResult.swap.extraMessage ?? undefined,
1414
+ },
1415
+
1416
+ swap: updateResult.swap,
1417
+ step: updateResult.step,
1418
+ });
1419
+
1329
1420
  reset();
1330
1421
  if (manager) manager?.retry();
1331
1422
 
1332
1423
  return updateResult;
1333
1424
  }
1425
+
1426
+ export function getLastSuccessfulStep<T extends { status: StepStatus }[]>(
1427
+ steps: T
1428
+ ): ArrayElement<T> | undefined {
1429
+ return steps
1430
+ .slice()
1431
+ .reverse()
1432
+ .find((step) => step.status === 'success') as ArrayElement<T> | undefined;
1433
+ }
1434
+
1435
+ export function getFailedStep<T extends { status: StepStatus }[]>(
1436
+ steps: T
1437
+ ): ArrayElement<T> | undefined {
1438
+ return steps
1439
+ .slice()
1440
+ .reverse()
1441
+ .find((step) => step.status === 'failed') as ArrayElement<T> | undefined;
1442
+ }
1443
+
1444
+ export function isApprovalTX(step: Step): boolean {
1445
+ const { transaction } = step;
1446
+ const approvalTx =
1447
+ (transaction?.type === TransactionType.EVM && transaction.isApprovalTx) ||
1448
+ (transaction?.type === TransactionType.STARKNET &&
1449
+ transaction.isApprovalTx) ||
1450
+ (transaction?.type === TransactionType.TRON && transaction.isApprovalTx);
1451
+
1452
+ return approvalTx;
1453
+ }
package/src/hooks.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  } from './helpers';
8
8
  import { migrated, migration } from './migration';
9
9
  import { UseQueueManagerParams } from './types';
10
+ import { eventEmitter } from './services/eventEmitter';
10
11
 
11
12
  let isCalled = 0;
12
13
 
@@ -54,14 +55,8 @@ function useQueueManager(params: UseQueueManagerParams): void {
54
55
  evmChains: params.evmChains,
55
56
  wallet_network: params.lastConnectedWallet,
56
57
  manager,
57
- notifier: params.notifier,
58
58
  });
59
- retryOn(
60
- params.lastConnectedWallet,
61
- params.notifier,
62
- manager,
63
- params.canSwitchNetworkTo
64
- );
59
+ retryOn(params.lastConnectedWallet, manager, params.canSwitchNetworkTo);
65
60
  }
66
61
  }, [params.lastConnectedWallet]);
67
62
 
@@ -78,4 +73,8 @@ function useQueueManager(params: UseQueueManagerParams): void {
78
73
  }, [params.disconnectedWallet]);
79
74
  }
80
75
 
81
- export { useQueueManager, useMigration };
76
+ function useEvents() {
77
+ return eventEmitter;
78
+ }
79
+
80
+ export { useQueueManager, useMigration, useEvents };
package/src/index.ts CHANGED
@@ -3,13 +3,28 @@ import { SwapQueueDef } from './types';
3
3
  import { swapQueueDef } from './queueDef';
4
4
 
5
5
  export { PrettyError, prettifyErrorMessage } from './shared-errors';
6
- export type { SwapQueueContext, SwapStorage } from './types';
6
+ export type {
7
+ SwapQueueContext,
8
+ SwapStorage,
9
+ RouteExecutionEvents,
10
+ Route,
11
+ Step,
12
+ RouteEvent,
13
+ StepEvent,
14
+ EventSeverity,
15
+ } from './types';
16
+ export {
17
+ MainEvents,
18
+ StepEventType,
19
+ RouteEventType,
20
+ StepExecutionEventStatus,
21
+ StepExecutionBlockedEventStatus,
22
+ } from './types';
7
23
  export type {
8
24
  PendingSwapWithQueueID,
9
25
  PendingSwapStep,
10
26
  PendingSwap,
11
27
  EventType,
12
- SwapProgressNotification,
13
28
  } from './shared';
14
29
  export {
15
30
  getCurrentBlockchainOfOrNull,
@@ -29,8 +44,9 @@ export {
29
44
  getRunningSwaps,
30
45
  splitWalletNetwork,
31
46
  resetRunningSwapNotifsOnPageLoad,
47
+ isApprovalTX,
32
48
  } from './helpers';
33
- export { useMigration, useQueueManager } from './hooks';
49
+ export { useMigration, useQueueManager, useEvents } from './hooks';
34
50
 
35
51
  export function makeQueueDefinition(configs: Configs): SwapQueueDef {
36
52
  initConfig(configs);