@rango-dev/queue-manager-rango-preset 0.1.10-next.98 → 0.1.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
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  ExecuterActions,
3
3
  QueueInfo,
4
+ QueueName,
4
5
  QueueType,
5
6
  } from '@rango-dev/queue-manager-core';
6
7
  import {
@@ -51,20 +52,21 @@ import {
51
52
  PendingSwap,
52
53
  PendingSwapNetworkStatus,
53
54
  PendingSwapStep,
54
- prettifyErrorMessage,
55
55
  StepStatus,
56
56
  SwapStatus,
57
57
  Wallet,
58
- WalletTypeAndAddress,
59
58
  SwapProgressNotification,
59
+ getRelatedWallet,
60
+ getCurrentAddressOf,
60
61
  } from './shared';
61
62
  import { logRPCError } from './shared-sentry';
62
63
  import {
63
64
  PrettyError,
64
65
  mapAppErrorCodesToAPIErrorCode,
65
- APIErrorCode,
66
+ prettifyErrorMessage,
66
67
  } from './shared-errors';
67
68
  import { httpService } from './services';
69
+ import { APIErrorCode, SignerErrorCode } from 'rango-types/lib';
68
70
 
69
71
  type WhenTaskBlocked = Parameters<NonNullable<SwapQueueDef['whenTaskBlocked']>>;
70
72
  type WhenTaskBlockedEvent = WhenTaskBlocked[0];
@@ -92,13 +94,26 @@ function claimQueue() {
92
94
  }
93
95
 
94
96
  /**
95
- *
97
+ * Sample inputs are:
98
+ * - "metamask-ETH"
99
+ * - "metamask-BSC-BSC:0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
100
+ * - "token-pocket-BSC-BSC:0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
96
101
  * Returns "wallet and network" separately, even if the wallet is dashed inside.
97
102
  *
98
103
  */
99
104
 
100
- function splitWalletNetwork(input: string): string[] {
101
- return input?.split(/-(?=[^-]*$)/);
105
+ export function splitWalletNetwork(input: string): string[] {
106
+ const removedAddressInput = input?.split(':')[0] || '';
107
+ const splittedInput = removedAddressInput.split('-');
108
+ const network = splittedInput[splittedInput.length - 1];
109
+ const walletNetwork = splittedInput.slice(0, -1);
110
+
111
+ if (walletNetwork[walletNetwork.length - 1] === network) {
112
+ walletNetwork.pop();
113
+ }
114
+ const wallet = walletNetwork.join('-');
115
+
116
+ return [wallet, network];
102
117
  }
103
118
 
104
119
  /**
@@ -143,7 +158,7 @@ export function updateSwapStatus({
143
158
  nextStepStatus?: StepStatus;
144
159
  message?: string;
145
160
  details?: string | null | undefined;
146
- errorCode?: string | null;
161
+ errorCode?: APIErrorCode | SignerErrorCode | null;
147
162
  hasAlreadyProceededToSign?: boolean;
148
163
  }): {
149
164
  swap: PendingSwap;
@@ -158,9 +173,10 @@ export function updateSwapStatus({
158
173
  if (!!nextStatus && ['failed', 'success'].includes(nextStatus))
159
174
  swap.finishTime = new Date().getTime().toString();
160
175
 
161
- if (!!message) swap.extraMessage = message;
162
-
163
- if (!!details) swap.extraMessageDetail = details;
176
+ if (!!message || !!details) {
177
+ swap.extraMessage = message || '';
178
+ swap.extraMessageDetail = details || '';
179
+ }
164
180
 
165
181
  if (!!nextStepStatus && ['failed'].includes(nextStepStatus)) {
166
182
  //if user cancel the swap, we should pass relevant reason to the server.
@@ -174,9 +190,7 @@ export function updateSwapStatus({
174
190
  .reportFailure({
175
191
  requestId: swap.requestId,
176
192
  step: currentStep?.id || 1,
177
- eventType: mapAppErrorCodesToAPIErrorCode(
178
- hasAlreadyProceededToSign ? APIErrorCode.TX_FAIL : errorCode
179
- ),
193
+ eventType: mapAppErrorCodesToAPIErrorCode(errorCode),
180
194
  reason: errorReason || '',
181
195
  data: walletType ? { wallet: walletType } : undefined,
182
196
  })
@@ -206,19 +220,40 @@ export function updateSwapStatus({
206
220
  export function setStepTransactionIds(
207
221
  { getStorage, setStorage }: ExecuterActions<SwapStorage, SwapActionTypes>,
208
222
  txId: string | null,
209
- eventType: EventType,
210
- notifier: SwapQueueContext['notifier']
223
+ notifier: SwapQueueContext['notifier'],
224
+ eventType?: EventType,
225
+ approveUrl?: string
211
226
  ): void {
212
227
  const swap = getStorage().swapDetails;
213
228
  swap.hasAlreadyProceededToSign = null;
214
229
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
215
230
  const currentStep = getCurrentStep(swap)!;
216
- currentStep.executedTransactionId = txId || currentStep.executedTransactionId;
231
+ currentStep.executedTransactionId = txId;
232
+ currentStep.executedTransactionTime = new Date().getTime().toString();
233
+ if (!!approveUrl)
234
+ currentStep.explorerUrl = [
235
+ ...(currentStep.explorerUrl || []),
236
+ {
237
+ url: approveUrl,
238
+ description: `approve`,
239
+ },
240
+ ];
241
+ if (eventType === 'check_tx_status') {
242
+ swap.extraMessage = 'Checking transaction status ...';
243
+ swap.extraMessageDetail = '';
244
+ swap.extraMessageSeverity = MessageSeverity.info;
245
+ } else if (eventType === 'check_approve_tx_status') {
246
+ swap.extraMessage = 'Checking approve transaction status ...';
247
+ swap.extraMessageDetail = '';
248
+ swap.extraMessageSeverity = MessageSeverity.info;
249
+ }
250
+
217
251
  setStorage({
218
252
  ...getStorage(),
219
253
  swapDetails: swap,
220
254
  });
221
- notifier({ eventType: eventType, swap: swap, step: currentStep });
255
+ if (!!eventType)
256
+ notifier({ eventType: eventType, swap: swap, step: currentStep });
222
257
  }
223
258
 
224
259
  export function getSwapNotitfication(
@@ -324,7 +359,10 @@ export function markRunningSwapAsSwitchingNetwork({
324
359
  export function markRunningSwapAsDependsOnOtherQueues({
325
360
  getStorage,
326
361
  setStorage,
327
- }: Pick<ExecuterActions, 'getStorage' | 'setStorage'>):
362
+ notifier,
363
+ }: Pick<ExecuterActions, 'getStorage' | 'setStorage'> & {
364
+ notifier: SwapQueueContext['notifier'];
365
+ }):
328
366
  | {
329
367
  swap: PendingSwap;
330
368
  step: PendingSwapStep;
@@ -338,6 +376,12 @@ export function markRunningSwapAsDependsOnOtherQueues({
338
376
  swap.networkStatusExtraMessageDetail = '';
339
377
  currentStep.networkStatus = PendingSwapNetworkStatus.WaitingForQueue;
340
378
 
379
+ notifier({
380
+ eventType: 'waiting_for_queue',
381
+ swap,
382
+ step: currentStep,
383
+ });
384
+
341
385
  setStorage({
342
386
  ...getStorage(),
343
387
  swapDetails: swap,
@@ -466,7 +510,6 @@ export async function isNetworkMatchedForTransaction(
466
510
  providers: Providers
467
511
  ): Promise<boolean> {
468
512
  if (isWalletNull(wallet)) {
469
- console.warn('wallet object is null');
470
513
  return false;
471
514
  }
472
515
  const fromBlockChain = getCurrentBlockchainOfOrNull(swap, step);
@@ -533,51 +576,6 @@ export async function isNetworkMatchedForTransaction(
533
576
  return true;
534
577
  }
535
578
 
536
- /**
537
- * Returns the wallet address, based on the current step of `PendingSwap`.
538
- */
539
- export const getCurrentAddressOf = (
540
- swap: PendingSwap,
541
- step: PendingSwapStep
542
- ): string => {
543
- const result =
544
- swap.wallets[step.evmTransaction?.blockChain || ''] ||
545
- swap.wallets[step.evmApprovalTransaction?.blockChain || ''] ||
546
- swap.wallets[step.tronTransaction?.blockChain || ''] ||
547
- swap.wallets[step.tronApprovalTransaction?.blockChain || ''] ||
548
- swap.wallets[step.starknetTransaction?.blockChain || ''] ||
549
- swap.wallets[step.starknetApprovalTransaction?.blockChain || ''] ||
550
- swap.wallets[step.cosmosTransaction?.blockChain || ''] ||
551
- swap.wallets[step.solanaTransaction?.blockChain || ''] ||
552
- (step.transferTransaction?.fromWalletAddress
553
- ? { address: step.transferTransaction?.fromWalletAddress }
554
- : null) ||
555
- null;
556
- if (result == null) throw PrettyError.WalletMissing();
557
- return result.address;
558
- };
559
-
560
- // Todo: Is it same with `getRequiredWallet`?
561
- export function getRelatedWallet(
562
- swap: PendingSwap,
563
- currentStep: PendingSwapStep
564
- ): WalletTypeAndAddress {
565
- const walletAddress = getCurrentAddressOf(swap, currentStep);
566
- const walletKV =
567
- Object.keys(swap.wallets)
568
- .map((k) => ({ k, v: swap.wallets[k] }))
569
- .find(({ v }) => v.address === walletAddress) || null;
570
- const blockchain = walletKV?.k || null;
571
- const wallet = walletKV?.v || null;
572
-
573
- const walletType = wallet?.walletType;
574
- if (walletType === WalletType.UNKNOWN || wallet === null)
575
- throw PrettyError.AssertionFailed(
576
- `Wallet for source ${blockchain} not passed: walletType: ${walletType}`
577
- );
578
- return wallet;
579
- }
580
-
581
579
  export const isTxAlreadyCreated = (
582
580
  swap: PendingSwap,
583
581
  step: PendingSwapStep
@@ -637,7 +635,7 @@ export function updateNetworkStatus(
637
635
 
638
636
  /**
639
637
  * Event handler for blocked tasks.
640
- * If a transcation execution is manually blocked (like for parallel or waiting for walle),
638
+ * If a transcation execution is manually blocked (like for parallel or waiting for wallet),
641
639
  * This function will be called by queue manager using `queue definition`.
642
640
  *
643
641
  * It checks if the required wallet is connected, unblock the queue to be run.
@@ -649,11 +647,16 @@ export function onBlockForConnectWallet(
649
647
  const { context, queue } = meta;
650
648
  const swap = queue.getStorage().swapDetails as SwapStorage['swapDetails'];
651
649
 
652
- if (!isRequiredWalletConnected(swap, context.state)) {
650
+ const { ok, reason } = isRequiredWalletConnected(swap, context.state);
651
+
652
+ if (!ok) {
653
653
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
654
654
  const currentStep = getCurrentStep(swap)!;
655
655
  context.notifier({
656
- eventType: 'waiting_for_connecting_wallet',
656
+ eventType:
657
+ reason === 'account_miss_match'
658
+ ? 'waiting_for_change_wallet_account'
659
+ : 'waiting_for_connecting_wallet',
657
660
  swap: swap,
658
661
  step: currentStep,
659
662
  });
@@ -718,7 +721,7 @@ export function onBlockForChangeNetwork(
718
721
 
719
722
  /**
720
723
  * Event handler for blocked tasks. (Parallel mode)
721
- * If a transcation execution is manually blocked (like for parallel or waiting for walle),
724
+ * If a transcation execution flow is manually blocked (like for parallel or waiting for walle),
722
725
  * This function will be called by queue manager using `queue definition`.
723
726
  *
724
727
  * It checks the blocked tasks, if there is no active `claimed` queue, try to give it to the best candidate.
@@ -727,7 +730,7 @@ export function onDependsOnOtherQueues(
727
730
  _event: WhenTaskBlockedEvent,
728
731
  meta: WhenTaskBlockedMeta
729
732
  ): void {
730
- const { getBlockedTasks, forceExecute, queue, manager } = meta;
733
+ const { getBlockedTasks, forceExecute, queue, manager, context } = meta;
731
734
  const { setClaimer, claimedBy, reset } = claimQueue();
732
735
 
733
736
  // We only needs those blocked tasks that have DEPENDS_ON_OTHER_QUEUES reason.
@@ -742,12 +745,15 @@ export function onDependsOnOtherQueues(
742
745
  const claimerId = claimedBy();
743
746
  const isClaimedByAnyQueue = !!claimerId;
744
747
 
748
+ if (claimerId === queue.id) return;
749
+
745
750
  // Check if any queue `claimed` before, if yes, we don't should do anything.
746
751
  if (isClaimedByAnyQueue) {
747
752
  // We need to keep the latest swap messages
748
753
  markRunningSwapAsDependsOnOtherQueues({
749
754
  getStorage: queue.getStorage.bind(queue),
750
755
  setStorage: queue.setStorage.bind(queue),
756
+ notifier: context.notifier,
751
757
  });
752
758
  return;
753
759
  }
@@ -776,7 +782,7 @@ export function onDependsOnOtherQueues(
776
782
  resetClaimedBy: () => {
777
783
  reset();
778
784
  // TODO: Use key generator
779
- retryOn(`${type}-${network}-${address}`, manager);
785
+ retryOn(`${type}-${network}:${address}`, context.notifier, manager);
780
786
  },
781
787
  });
782
788
  }
@@ -784,19 +790,21 @@ export function onDependsOnOtherQueues(
784
790
  export function isRequiredWalletConnected(
785
791
  swap: PendingSwap,
786
792
  getState: (type: WalletType) => WalletState
787
- ): boolean {
793
+ ): { ok: boolean; reason: 'not_connected' | 'account_miss_match' } {
788
794
  const { type, address } = getRequiredWallet(swap);
789
795
  if (!type || !address) {
790
- return false;
796
+ return { ok: false, reason: 'not_connected' };
791
797
  }
792
798
  const walletState = getState(type);
793
- const { accounts } = walletState;
799
+ const { accounts, connected } = walletState;
794
800
  const connectedAccounts = accounts || [];
801
+ if (!connected) return { ok: false, reason: 'not_connected' };
795
802
 
796
- return connectedAccounts.some((account) => {
803
+ const matched = connectedAccounts.some((account) => {
797
804
  const { address: accountAddress } = readAccountAddress(account);
798
805
  return address === accountAddress;
799
806
  });
807
+ return { ok: matched, reason: 'account_miss_match' };
800
808
  }
801
809
 
802
810
  export function singTransaction(
@@ -823,6 +831,7 @@ export function singTransaction(
823
831
  const walletSigners = getSigners(sourceWallet.walletType);
824
832
 
825
833
  const onFinish = () => {
834
+ // TODO resetClaimedBy is undefined here
826
835
  if (actions.context.resetClaimedBy) {
827
836
  actions.context.resetClaimedBy();
828
837
  }
@@ -851,7 +860,7 @@ export function singTransaction(
851
860
  'Waiting for approve transaction to be mined and confirmed successfully',
852
861
  });
853
862
  notifier({
854
- eventType: 'confirm_contract',
863
+ eventType: 'confirm_approve_contract',
855
864
  ...updateResult,
856
865
  });
857
866
 
@@ -861,25 +870,18 @@ export function singTransaction(
861
870
  .signAndSendTx(evmApprovalTransaction, walletAddress, null)
862
871
  .then(
863
872
  (hash) => {
864
- console.debug('transaction of approval minted successfully', hash);
865
873
  const approveUrl = getEvmApproveUrl(
866
874
  hash,
867
875
  getCurrentBlockchainOf(swap, currentStep),
868
876
  meta.evmBasedChains
869
877
  );
870
- currentStep.explorerUrl = [
871
- ...(currentStep.explorerUrl || []),
872
- {
873
- url: approveUrl,
874
- description: `approve`,
875
- },
876
- ];
877
-
878
- // `currentStep` has been mutated, let's update storage.
879
- setStorage({
880
- ...getStorage(),
881
- swapDetails: swap,
882
- });
878
+ setStepTransactionIds(
879
+ actions,
880
+ hash,
881
+ notifier,
882
+ 'check_approve_tx_status',
883
+ approveUrl
884
+ );
883
885
  schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
884
886
  next();
885
887
  onFinish();
@@ -887,7 +889,7 @@ export function singTransaction(
887
889
 
888
890
  (error) => {
889
891
  if (swap.status === 'failed') return;
890
- console.debug('error in approving', error);
892
+
891
893
  const { extraMessage, extraMessageDetail, extraMessageErrorCode } =
892
894
  prettifyErrorMessage(error);
893
895
  if (
@@ -940,7 +942,7 @@ export function singTransaction(
940
942
  'Waiting for approve transaction to be mined and confirmed successfully',
941
943
  });
942
944
  notifier({
943
- eventType: 'confirm_contract',
945
+ eventType: 'confirm_approve_contract',
944
946
  ...updateResult,
945
947
  });
946
948
 
@@ -950,21 +952,14 @@ export function singTransaction(
950
952
  .signAndSendTx(tronApprovalTransaction, walletAddress, null)
951
953
  .then(
952
954
  (hash) => {
953
- console.debug('transaction of approval minted successfully', hash);
954
955
  const approveUrl = getTronApproveUrl(hash);
955
- currentStep.explorerUrl = [
956
- ...(currentStep.explorerUrl || []),
957
- {
958
- url: approveUrl,
959
- description: `approve`,
960
- },
961
- ];
962
-
963
- // `currentStep` has been mutated, let's update storage.
964
- setStorage({
965
- ...getStorage(),
966
- swapDetails: swap,
967
- });
956
+ setStepTransactionIds(
957
+ actions,
958
+ hash,
959
+ notifier,
960
+ 'check_approve_tx_status',
961
+ approveUrl
962
+ );
968
963
  schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
969
964
  next();
970
965
  onFinish();
@@ -972,7 +967,7 @@ export function singTransaction(
972
967
 
973
968
  (error) => {
974
969
  if (swap.status === 'failed') return;
975
- console.debug('error in approving', error);
970
+
976
971
  const { extraMessage, extraMessageDetail, extraMessageErrorCode } =
977
972
  prettifyErrorMessage(error);
978
973
  if (
@@ -1025,7 +1020,7 @@ export function singTransaction(
1025
1020
  'Waiting for approve transaction to be mined and confirmed successfully',
1026
1021
  });
1027
1022
  notifier({
1028
- eventType: 'confirm_contract',
1023
+ eventType: 'confirm_approve_contract',
1029
1024
  ...updateResult,
1030
1025
  });
1031
1026
 
@@ -1035,21 +1030,14 @@ export function singTransaction(
1035
1030
  .signAndSendTx(starknetApprovalTransaction, walletAddress, null)
1036
1031
  .then(
1037
1032
  (hash) => {
1038
- console.debug('transaction of approval minted successfully', hash);
1039
1033
  const approveUrl = getStarknetApproveUrl(hash);
1040
- currentStep.explorerUrl = [
1041
- ...(currentStep.explorerUrl || []),
1042
- {
1043
- url: approveUrl,
1044
- description: `approve`,
1045
- },
1046
- ];
1047
-
1048
- // `currentStep` has been mutated, let's update storage.
1049
- setStorage({
1050
- ...getStorage(),
1051
- swapDetails: swap,
1052
- });
1034
+ setStepTransactionIds(
1035
+ actions,
1036
+ hash,
1037
+ notifier,
1038
+ 'check_approve_tx_status',
1039
+ approveUrl
1040
+ );
1053
1041
  schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1054
1042
  next();
1055
1043
  onFinish();
@@ -1057,7 +1045,7 @@ export function singTransaction(
1057
1045
 
1058
1046
  (error) => {
1059
1047
  if (swap.status === 'failed') return;
1060
- console.debug('error in approving', error);
1048
+
1061
1049
  const { extraMessage, extraMessageDetail, extraMessageErrorCode } =
1062
1050
  prettifyErrorMessage(error);
1063
1051
  if (
@@ -1098,6 +1086,11 @@ export function singTransaction(
1098
1086
 
1099
1087
  const hasAlreadyProceededToSign =
1100
1088
  typeof swap.hasAlreadyProceededToSign === 'boolean';
1089
+ const nextStepStatusBasedOnHasAlreadyProceededToSign =
1090
+ hasAlreadyProceededToSign ? 'failed' : 'running';
1091
+ const errorCodeBasedOnHasAlreadyProceededToSign = hasAlreadyProceededToSign
1092
+ ? 'TX_EXPIRED'
1093
+ : null;
1101
1094
  const executeMessage = hasAlreadyProceededToSign
1102
1095
  ? 'Transaction is expired. Please try again'
1103
1096
  : 'executing transaction';
@@ -1111,11 +1104,12 @@ export function singTransaction(
1111
1104
  const updateResult = updateSwapStatus({
1112
1105
  getStorage,
1113
1106
  setStorage,
1114
- nextStepStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1115
- nextStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1107
+ nextStepStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1108
+ nextStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1116
1109
  message: executeMessage,
1117
1110
  details: executeDetails,
1118
1111
  hasAlreadyProceededToSign,
1112
+ errorCode: errorCodeBasedOnHasAlreadyProceededToSign,
1119
1113
  });
1120
1114
 
1121
1115
  const notification = getSwapNotitfication('confirm_transfer', updateResult);
@@ -1130,12 +1124,7 @@ export function singTransaction(
1130
1124
  .signAndSendTx(transferTransaction, walletAddress, null)
1131
1125
  .then(
1132
1126
  (txId) => {
1133
- setStepTransactionIds(
1134
- actions,
1135
- txId,
1136
- 'transfer_confirmed',
1137
- notifier
1138
- );
1127
+ setStepTransactionIds(actions, txId, notifier, 'check_tx_status');
1139
1128
  schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1140
1129
  next();
1141
1130
  onFinish();
@@ -1166,11 +1155,12 @@ export function singTransaction(
1166
1155
  const updateResult = updateSwapStatus({
1167
1156
  getStorage,
1168
1157
  setStorage,
1169
- nextStepStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1170
- nextStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1158
+ nextStepStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1159
+ nextStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1171
1160
  message: executeMessage,
1172
1161
  details: executeDetails,
1173
1162
  hasAlreadyProceededToSign,
1163
+ errorCode: errorCodeBasedOnHasAlreadyProceededToSign,
1174
1164
  });
1175
1165
  const notification = getSwapNotitfication(
1176
1166
  'calling_smart_contract',
@@ -1187,12 +1177,7 @@ export function singTransaction(
1187
1177
  .signAndSendTx(evmTransaction, walletAddress, null)
1188
1178
  .then(
1189
1179
  (id) => {
1190
- setStepTransactionIds(
1191
- actions,
1192
- id,
1193
- 'smart_contract_called',
1194
- notifier
1195
- );
1180
+ setStepTransactionIds(actions, id, notifier, 'check_tx_status');
1196
1181
  schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1197
1182
  next();
1198
1183
  onFinish();
@@ -1238,11 +1223,12 @@ export function singTransaction(
1238
1223
  const updateResult = updateSwapStatus({
1239
1224
  getStorage,
1240
1225
  setStorage,
1241
- nextStepStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1242
- nextStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1226
+ nextStepStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1227
+ nextStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1243
1228
  message: executeMessage,
1244
1229
  details: executeDetails,
1245
1230
  hasAlreadyProceededToSign,
1231
+ errorCode: errorCodeBasedOnHasAlreadyProceededToSign,
1246
1232
  });
1247
1233
  const notification = getSwapNotitfication(
1248
1234
  'calling_smart_contract',
@@ -1292,12 +1278,7 @@ export function singTransaction(
1292
1278
  .then(
1293
1279
  // todo
1294
1280
  (id: string | null) => {
1295
- setStepTransactionIds(
1296
- actions,
1297
- id,
1298
- 'smart_contract_called',
1299
- notifier
1300
- );
1281
+ setStepTransactionIds(actions, id, notifier, 'check_tx_status');
1301
1282
  schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1302
1283
  next();
1303
1284
  onFinish();
@@ -1328,11 +1309,12 @@ export function singTransaction(
1328
1309
  const updateResult = updateSwapStatus({
1329
1310
  getStorage,
1330
1311
  setStorage,
1331
- nextStepStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1332
- nextStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1312
+ nextStepStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1313
+ nextStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1333
1314
  message: executeMessage,
1334
1315
  details: executeDetails,
1335
1316
  hasAlreadyProceededToSign,
1317
+ errorCode: errorCodeBasedOnHasAlreadyProceededToSign,
1336
1318
  });
1337
1319
  const notification = getSwapNotitfication(
1338
1320
  'calling_smart_contract',
@@ -1350,12 +1332,7 @@ export function singTransaction(
1350
1332
  .signAndSendTx(tx, walletAddress, null)
1351
1333
  .then(
1352
1334
  (txId) => {
1353
- setStepTransactionIds(
1354
- actions,
1355
- txId,
1356
- 'smart_contract_called',
1357
- notifier
1358
- );
1335
+ setStepTransactionIds(actions, txId, notifier, 'check_tx_status');
1359
1336
  schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1360
1337
  next();
1361
1338
  onFinish();
@@ -1386,11 +1363,12 @@ export function singTransaction(
1386
1363
  const updateResult = updateSwapStatus({
1387
1364
  getStorage,
1388
1365
  setStorage,
1389
- nextStepStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1390
- nextStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1366
+ nextStepStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1367
+ nextStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1391
1368
  message: executeMessage,
1392
1369
  details: executeDetails,
1393
1370
  hasAlreadyProceededToSign,
1371
+ errorCode: errorCodeBasedOnHasAlreadyProceededToSign,
1394
1372
  });
1395
1373
  const notification = getSwapNotitfication(
1396
1374
  'calling_smart_contract',
@@ -1407,12 +1385,7 @@ export function singTransaction(
1407
1385
  .signAndSendTx(tronTransaction, walletAddress, null)
1408
1386
  .then(
1409
1387
  (id) => {
1410
- setStepTransactionIds(
1411
- actions,
1412
- id,
1413
- 'smart_contract_called',
1414
- notifier
1415
- );
1388
+ setStepTransactionIds(actions, id, notifier, 'check_tx_status');
1416
1389
  schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1417
1390
  next();
1418
1391
  onFinish();
@@ -1458,11 +1431,12 @@ export function singTransaction(
1458
1431
  const updateResult = updateSwapStatus({
1459
1432
  getStorage,
1460
1433
  setStorage,
1461
- nextStepStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1462
- nextStatus: hasAlreadyProceededToSign ? 'failed' : 'running',
1434
+ nextStepStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1435
+ nextStatus: nextStepStatusBasedOnHasAlreadyProceededToSign,
1463
1436
  message: executeMessage,
1464
1437
  details: executeDetails,
1465
1438
  hasAlreadyProceededToSign,
1439
+ errorCode: errorCodeBasedOnHasAlreadyProceededToSign,
1466
1440
  });
1467
1441
  const notification = getSwapNotitfication(
1468
1442
  'calling_smart_contract',
@@ -1479,12 +1453,7 @@ export function singTransaction(
1479
1453
  .signAndSendTx(starknetTransaction, walletAddress, null)
1480
1454
  .then(
1481
1455
  (id) => {
1482
- setStepTransactionIds(
1483
- actions,
1484
- id,
1485
- 'smart_contract_called',
1486
- notifier
1487
- );
1456
+ setStepTransactionIds(actions, id, notifier, 'check_tx_status');
1488
1457
  schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1489
1458
  next();
1490
1459
  onFinish();
@@ -1533,6 +1502,7 @@ export function checkWaitingForConnectWalletChange(params: {
1533
1502
  wallet_network: string;
1534
1503
  manager?: Manager;
1535
1504
  evmChains: EvmBlockchainMeta[];
1505
+ notifier: SwapQueueContext['notifier'];
1536
1506
  }): void {
1537
1507
  const { wallet_network, evmChains, manager } = params;
1538
1508
  const [wallet, network] = splitWalletNetwork(wallet_network);
@@ -1553,6 +1523,7 @@ export function checkWaitingForConnectWalletChange(params: {
1553
1523
  const task = q.list.state.tasks[taskId];
1554
1524
  return (
1555
1525
  task.status === Status.BLOCKED &&
1526
+ // TODO double check later
1556
1527
  [BlockReason.WAIT_FOR_CONNECT_WALLET].includes(
1557
1528
  task.blockedFor?.reason
1558
1529
  )
@@ -1577,10 +1548,18 @@ export function checkWaitingForConnectWalletChange(params: {
1577
1548
  silent: true,
1578
1549
  });
1579
1550
 
1580
- markRunningSwapAsSwitchingNetwork({
1551
+ const result = markRunningSwapAsSwitchingNetwork({
1581
1552
  getStorage: queueInstance.getStorage.bind(queueInstance),
1582
1553
  setStorage: queueInstance.setStorage.bind(queueInstance),
1583
1554
  });
1555
+
1556
+ if (result) {
1557
+ params?.notifier({
1558
+ eventType: 'waiting_for_network_change',
1559
+ swap: result.swap,
1560
+ step: result.step,
1561
+ });
1562
+ }
1584
1563
  }
1585
1564
  }
1586
1565
  }
@@ -1621,6 +1600,56 @@ export function checkWaitingForNetworkChange(manager?: Manager): void {
1621
1600
  });
1622
1601
  }
1623
1602
 
1603
+ /**
1604
+ * Get list of all running swaps
1605
+ *
1606
+ * @param manager
1607
+ * @returns list of pending swaps
1608
+ */
1609
+ export function getRunningSwaps(manager: Manager): PendingSwap[] {
1610
+ const queues = manager?.getAll() || new Map<QueueName, QueueInfo>();
1611
+ let result: PendingSwap[] = [];
1612
+ queues.forEach((q) => {
1613
+ // retry only on affected queues
1614
+ const queueStorage = q.list.getStorage() as SwapStorage | undefined;
1615
+ const swap = queueStorage?.swapDetails;
1616
+ if (!swap || swap.status !== 'running') return;
1617
+ result.push(swap);
1618
+ });
1619
+ return result;
1620
+ }
1621
+
1622
+ /**
1623
+ *
1624
+ * Trying to reset notifications for pending swaps to correct message on page load.
1625
+ * We could remove this after supporting auto connect for wallets.
1626
+ *
1627
+ * @param swaps
1628
+ * @param notifier
1629
+ * @returns
1630
+ */
1631
+ export function resetRunningSwapNotifsOnPageLoad(
1632
+ runningSwaps: PendingSwap[],
1633
+ notifier: SwapQueueContext['notifier']
1634
+ ) {
1635
+ runningSwaps.forEach((swap) => {
1636
+ const currentStep = getCurrentStep(swap);
1637
+ let eventType: EventType | undefined;
1638
+ if (currentStep?.networkStatus === PendingSwapNetworkStatus.WaitingForQueue)
1639
+ eventType = 'waiting_for_queue';
1640
+ else if (swap?.status === 'running') {
1641
+ eventType = 'waiting_for_connecting_wallet';
1642
+ }
1643
+ if (!!eventType && !!notifier) {
1644
+ notifier({
1645
+ eventType,
1646
+ swap: swap,
1647
+ step: currentStep,
1648
+ });
1649
+ }
1650
+ });
1651
+ }
1652
+
1624
1653
  /**
1625
1654
  *
1626
1655
  * Try to run blocked tasks by wallet and network name.
@@ -1634,6 +1663,7 @@ export function checkWaitingForNetworkChange(manager?: Manager): void {
1634
1663
  */
1635
1664
  export function retryOn(
1636
1665
  wallet_network: string,
1666
+ notifier: SwapQueueContext['notifier'],
1637
1667
  manager?: Manager,
1638
1668
  options = { fallbackToOnlyWallet: true }
1639
1669
  ): void {
@@ -1670,7 +1700,6 @@ export function retryOn(
1670
1700
  }
1671
1701
  });
1672
1702
 
1673
- // const isWaitingForConnectWallet = (status: Status) =>
1674
1703
  let finalQueueToBeRun: QueueType | undefined = undefined;
1675
1704
  if (walletAndNetworkMatched.length > 0) {
1676
1705
  finalQueueToBeRun = walletAndNetworkMatched[0];
@@ -1682,6 +1711,7 @@ export function retryOn(
1682
1711
  markRunningSwapAsDependsOnOtherQueues({
1683
1712
  getStorage: currentQueue.getStorage.bind(currentQueue),
1684
1713
  setStorage: currentQueue.setStorage.bind(currentQueue),
1714
+ notifier: notifier,
1685
1715
  });
1686
1716
  }
1687
1717
  }