@instadapp/interop-x 0.0.0-dev.4887ba6 → 0.0.0-dev.4df5dc2

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.
Files changed (81) hide show
  1. package/.github/workflows/ci.yml +19 -0
  2. package/dist/package.json +14 -13
  3. package/dist/src/abi/index.js +2 -4
  4. package/dist/src/abi/interopX.json +1436 -0
  5. package/dist/src/alias.js +10 -0
  6. package/dist/src/api/index.js +4 -1
  7. package/dist/src/config/index.js +10 -1
  8. package/dist/src/constants/addresses.js +2 -7
  9. package/dist/src/constants/index.js +0 -1
  10. package/dist/src/constants/tokens.js +62 -39
  11. package/dist/src/db/models/transaction.js +29 -11
  12. package/dist/src/gnosis/actions/index.js +9 -0
  13. package/dist/src/gnosis/actions/withdraw/index.js +114 -0
  14. package/dist/src/gnosis/index.js +20 -0
  15. package/dist/src/index.js +39 -23
  16. package/dist/src/net/peer/index.js +2 -1
  17. package/dist/src/net/pool/index.js +7 -2
  18. package/dist/src/net/protocol/dial/SignatureDialProtocol.js +9 -10
  19. package/dist/src/net/protocol/dial/TransactionStatusDialProtocol.js +30 -0
  20. package/dist/src/net/protocol/index.js +26 -5
  21. package/dist/src/tasks/AutoUpdateTask.js +36 -13
  22. package/dist/src/tasks/BaseTask.js +11 -3
  23. package/dist/src/tasks/InteropX/SyncLogSubmitEvents.js +84 -0
  24. package/dist/src/tasks/Transactions/SyncTransactionStatusTask.js +57 -0
  25. package/dist/src/tasks/index.js +7 -17
  26. package/dist/src/typechain/{InteropBridgeToken.js → InteropX.js} +0 -0
  27. package/dist/src/typechain/factories/InteropX__factory.js +1928 -0
  28. package/dist/src/typechain/factories/index.js +3 -5
  29. package/dist/src/typechain/index.js +3 -5
  30. package/dist/src/utils/index.js +59 -92
  31. package/package.json +14 -13
  32. package/src/abi/index.ts +2 -4
  33. package/src/abi/interopX.json +1436 -0
  34. package/src/alias.ts +6 -0
  35. package/src/api/index.ts +4 -1
  36. package/src/config/index.ts +9 -1
  37. package/src/constants/addresses.ts +3 -8
  38. package/src/constants/index.ts +0 -1
  39. package/src/constants/tokens.ts +63 -40
  40. package/src/db/models/transaction.ts +65 -25
  41. package/src/gnosis/actions/index.ts +5 -0
  42. package/src/gnosis/actions/withdraw/index.ts +155 -0
  43. package/src/gnosis/index.ts +19 -0
  44. package/src/index.ts +52 -25
  45. package/src/net/peer/index.ts +2 -1
  46. package/src/net/pool/index.ts +7 -3
  47. package/src/net/protocol/dial/SignatureDialProtocol.ts +11 -13
  48. package/src/net/protocol/dial/TransactionStatusDialProtocol.ts +33 -0
  49. package/src/net/protocol/index.ts +28 -6
  50. package/src/tasks/AutoUpdateTask.ts +40 -16
  51. package/src/tasks/BaseTask.ts +13 -3
  52. package/src/tasks/InteropX/SyncLogSubmitEvents.ts +136 -0
  53. package/src/tasks/Transactions/SyncTransactionStatusTask.ts +69 -0
  54. package/src/tasks/index.ts +12 -21
  55. package/src/typechain/InteropX.ts +1216 -0
  56. package/src/typechain/factories/InteropX__factory.ts +1932 -0
  57. package/src/typechain/factories/index.ts +1 -2
  58. package/src/typechain/index.ts +2 -4
  59. package/src/utils/index.ts +113 -131
  60. package/tsconfig.json +7 -2
  61. package/dist/src/abi/interopBridgeToken.json +0 -286
  62. package/dist/src/abi/interopXGateway.json +0 -184
  63. package/dist/src/constants/itokens.js +0 -13
  64. package/dist/src/tasks/InteropBridge/ProcessWithdrawEvents.js +0 -147
  65. package/dist/src/tasks/InteropBridge/SyncWithdrawEvents.js +0 -70
  66. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +0 -150
  67. package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +0 -75
  68. package/dist/src/typechain/InteropXGateway.js +0 -2
  69. package/dist/src/typechain/factories/InteropBridgeToken__factory.js +0 -459
  70. package/dist/src/typechain/factories/InteropXGateway__factory.js +0 -265
  71. package/src/abi/interopBridgeToken.json +0 -286
  72. package/src/abi/interopXGateway.json +0 -184
  73. package/src/constants/itokens.ts +0 -10
  74. package/src/tasks/InteropBridge/ProcessWithdrawEvents.ts +0 -233
  75. package/src/tasks/InteropBridge/SyncWithdrawEvents.ts +0 -121
  76. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +0 -245
  77. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +0 -126
  78. package/src/typechain/InteropBridgeToken.ts +0 -686
  79. package/src/typechain/InteropXGateway.ts +0 -407
  80. package/src/typechain/factories/InteropBridgeToken__factory.ts +0 -466
  81. package/src/typechain/factories/InteropXGateway__factory.ts +0 -272
package/src/index.ts CHANGED
@@ -1,21 +1,7 @@
1
- import moduleAlias from 'module-alias';
2
-
3
- moduleAlias.addAliases({
4
- "@/": __dirname + "/",
5
- "@/logger": __dirname + "/logger",
6
- "@/tasks": __dirname + "/tasks",
7
- "@/utils": __dirname + "/utils",
8
- "@/api": __dirname + "/api",
9
- "@/net": __dirname + "/net",
10
- "@/db": __dirname + "/db",
11
- "@/config": __dirname + "/config",
12
- "@/types": __dirname + "/types",
13
- "@/abi": __dirname + "/abi",
14
- "@/constants": __dirname + "/constants",
15
- "@/typechain": __dirname + "/typechain"
16
- })
1
+ import './alias'
2
+ import expandHomeDir from "expand-home-dir";
3
+ import fs from 'fs-extra'
17
4
 
18
- moduleAlias();
19
5
  import dotenv from "dotenv";
20
6
  import chalk from 'chalk';
21
7
  import { ethers } from "ethers";
@@ -25,12 +11,30 @@ dotenv.config();
25
11
  import Logger from "@/logger";
26
12
  const logger = new Logger('Process')
27
13
 
14
+ const GIT_SHORT_HASH = '@GIT_SHORT_HASH@';
15
+
28
16
  const printUsage = () => {
17
+ console.log()
18
+ console.log(`Interop X Node (v${packageJson.version} - rev.${GIT_SHORT_HASH})`)
19
+ console.log()
20
+
29
21
  console.log('Usage:')
30
- console.log(' PRIVATE_KEY=abcd1234 interop-x')
31
- console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x')
32
- console.log(' PRIVATE_KEY=abcd1234 AUTO_UPDATE=true interop-x')
33
- console.log(' PRIVATE_KEY=abcd1234 API_HOST=0.0.0.0 API_PORT=8080 interop-x')
22
+ console.log(' interop-x help Show this message')
23
+ console.log(' interop-x version Print out the installed version of Interop X')
24
+
25
+ console.log()
26
+
27
+ console.log(' interop-x down Put the node into maintenance mode')
28
+ console.log(' interop-x up Take the node out of maintenance mode')
29
+
30
+ console.log()
31
+
32
+ console.log(' PRIVATE_KEY=abcd1234 interop-x Start the node with the given private key')
33
+ console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x Start the node in staging mode')
34
+ console.log(' PRIVATE_KEY=abcd1234 AUTO_UPDATE=true interop-x Start the node in auto update mode')
35
+ console.log(' PRIVATE_KEY=abcd1234 API_HOST=0.0.0.0 API_PORT=8080 interop-x Start the node with custom API host and port')
36
+ console.log()
37
+
34
38
  }
35
39
 
36
40
  if (process.argv.at(-1) === 'help') {
@@ -38,14 +42,27 @@ if (process.argv.at(-1) === 'help') {
38
42
  process.exit(0)
39
43
  }
40
44
 
41
- const GIT_SHORT_HASH = '@GIT_SHORT_HASH@';
45
+ const basePath = expandHomeDir(`~/.interop-x`);
46
+
47
+ if (process.argv.at(-1) === 'down') {
48
+ fs.outputFileSync(basePath + '/maintenance', Date.now().toString())
49
+ console.log(chalk.red('Maintenance mode enabled'))
50
+ process.exit(0)
51
+ }
52
+
53
+ if (process.argv.at(-1) === 'up') {
54
+ fs.removeSync(basePath + '/maintenance')
55
+ console.log(chalk.green('Maintenance mode disabled'))
56
+ process.exit(0)
57
+ }
58
+
42
59
 
43
60
  if (process.argv.at(-1) === 'version') {
44
61
  console.log(`Interop X Node (v${packageJson.version} - rev.${GIT_SHORT_HASH})`)
45
62
  process.exit(0)
46
63
  }
47
64
 
48
- if(! process.env.PRIVATE_KEY) {
65
+ if (!process.env.PRIVATE_KEY) {
49
66
  console.error(chalk.bgRed.white.bold('Please provide a private key\n'))
50
67
  printUsage()
51
68
  process.exit(1)
@@ -64,6 +81,7 @@ import { Tasks } from "@/tasks";
64
81
  import { startPeer, protocol, peerPool } from "@/net";
65
82
  import { startApiServer } from '@/api';
66
83
  import { Transaction } from './db';
84
+ import { shortenHash } from './utils';
67
85
 
68
86
  async function main() {
69
87
 
@@ -71,14 +89,21 @@ async function main() {
71
89
 
72
90
  const tasks = new Tasks()
73
91
 
74
- tasks.start();
92
+ setTimeout(() => {
93
+ tasks.start();
94
+ }, 10000)
75
95
 
76
96
  startApiServer()
77
97
 
78
98
  protocol.on('TransactionStatus', async (payload) => {
79
99
  if (!peerPool.isLeadNode(payload.peerId)) {
80
100
  const peer = peerPool.getPeer(payload.peerId)
81
- logger.info(`ignored transaction status from ${payload.peerId} ${peer?.publicAddress} `)
101
+
102
+ if (!peer) {
103
+ return;
104
+ }
105
+
106
+ logger.info(`ignored transaction status from ${payload.peerId} ${shortenHash(peer.publicAddress)} `)
82
107
  return;
83
108
  }
84
109
 
@@ -91,10 +116,12 @@ async function main() {
91
116
  transaction.sourceStatus = payload.data.sourceStatus
92
117
  transaction.sourceTransactionHash = payload.data.sourceTransactionHash
93
118
  transaction.sourceErrors = payload.data.sourceErrors
119
+ transaction.sourceLogs = payload.data.sourceLogs
94
120
 
95
121
  transaction.targetStatus = payload.data.targetStatus
96
122
  transaction.targetTransactionHash = payload.data.targetTransactionHash
97
123
  transaction.targetErrors = payload.data.targetErrors
124
+ transaction.targetLogs = payload.data.targetLogs
98
125
 
99
126
  transaction.status = payload.data.status
100
127
 
@@ -17,6 +17,7 @@ import KadDHT from "libp2p-kad-dht";
17
17
  import PubsubPeerDiscovery from "libp2p-pubsub-peer-discovery";
18
18
  import { protocol } from "@/net";
19
19
  import config from "@/config";
20
+ import chalk from "chalk";
20
21
 
21
22
  const logger = new Logger("Peer");
22
23
 
@@ -80,7 +81,7 @@ export const startPeer = async ({ }: IPeerOptions) => {
80
81
  },
81
82
  });
82
83
 
83
- logger.info("Peer ID:", node.peerId.toB58String());
84
+ logger.info("Peer ID:", chalk.bold(node.peerId.toB58String()));
84
85
 
85
86
  await node.start();
86
87
 
@@ -2,6 +2,8 @@ import { Event } from "@/types";
2
2
  import config from "@/config";
3
3
  import Logger from "@/logger";
4
4
  import { getAddress } from "ethers/lib/utils";
5
+ import { shortenHash } from "@/utils";
6
+ import chalk from "chalk";
5
7
 
6
8
 
7
9
  const logger = new Logger('PeerPool')
@@ -87,7 +89,7 @@ export class PeerPool {
87
89
 
88
90
  if (newPeer) {
89
91
  config.events.emit(Event.POOL_PEER_ADDED, peer)
90
- logger.info(`Peer ${peer.id} with address ${peer.publicAddress} added to pool`)
92
+ logger.info(`Peer ${chalk.bold(shortenHash(peer.id, 16))} with address ${chalk.bold(shortenHash(peer.publicAddress))} added to pool`)
91
93
  }
92
94
  }
93
95
  }
@@ -102,7 +104,7 @@ export class PeerPool {
102
104
  if (this.pool.delete(peer.id)) {
103
105
  peer.pooled = false
104
106
  config.events.emit(Event.POOL_PEER_REMOVED, peer)
105
- logger.info(`Peer ${peer.id} with address ${peer.publicAddress} removed from pool`)
107
+ logger.info(`Peer ${chalk.bold(shortenHash(peer.id, 16))} with address ${chalk.bold(shortenHash(peer.publicAddress))} removed from pool`)
106
108
  }
107
109
  }
108
110
  }
@@ -123,7 +125,6 @@ export class PeerPool {
123
125
  return this.activePeers.map((p) => p.id)
124
126
  }
125
127
 
126
-
127
128
  getPeer(id: string){
128
129
  return this.pool.get(id);
129
130
  }
@@ -138,6 +139,9 @@ export class PeerPool {
138
139
  return getAddress(peer.publicAddress) === getAddress(config.leadNodeAddress)
139
140
  }
140
141
 
142
+ getLeadPeer() {
143
+ return this.peers.find((p) => this.isLeadNode(p.id))
144
+ }
141
145
 
142
146
  cleanup() {
143
147
  // let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
@@ -2,12 +2,13 @@ import { BaseDialProtocol } from "./BaseDialProtocol";
2
2
  import wait from "waait";
3
3
  import config from "@/config";
4
4
  import { Transaction } from "@/db";
5
- import { buildDataForTransaction, signGnosisSafeTx } from "@/utils";
5
+ import { signGnosisSafeTx } from "@/utils";
6
6
  import { addresses } from "@/constants";
7
7
  import { ChainId } from "@/types";
8
+ import { buildGnosisAction } from "@/gnosis";
8
9
 
9
10
  export interface ISignatureRequest {
10
- type: 'source' | 'target' ,
11
+ type: 'source' | 'target',
11
12
  transactionHash: string
12
13
  safeTxGas: string
13
14
  safeNonce: string
@@ -25,6 +26,10 @@ export class SignatureDialProtocol extends BaseDialProtocol<ISignatureRequest, I
25
26
  }
26
27
 
27
28
  async response(data: ISignatureRequest): Promise<ISignatureResponse> {
29
+ console.log({
30
+ tag: 'SignatureDialProtocol',
31
+ data
32
+ })
28
33
  const signer = config.wallet;
29
34
 
30
35
  let transaction: Transaction | null;
@@ -46,19 +51,12 @@ export class SignatureDialProtocol extends BaseDialProtocol<ISignatureRequest, I
46
51
  error: 'Event not found'
47
52
  };
48
53
  }
49
-
50
- console.log("signing:", {
51
- to: addresses[transaction.targetChainId].multisend,
52
- data: await buildDataForTransaction(transaction, data.type),
53
- chainId: transaction.targetChainId as ChainId,
54
- safeTxGas: data.safeTxGas,
55
- nonce: data.safeNonce,
56
- });
54
+ const { data: gnosisData } = await buildGnosisAction(transaction, data.type);
57
55
 
58
56
  const signedData = await signGnosisSafeTx({
59
- to: addresses[transaction.targetChainId].multisend,
60
- data: await buildDataForTransaction(transaction, data.type),
61
- chainId: transaction.targetChainId as ChainId,
57
+ to: addresses[transaction.sourceChainId].multisend,
58
+ data: gnosisData,
59
+ chainId: transaction.sourceChainId as ChainId,
62
60
  safeTxGas: data.safeTxGas,
63
61
  nonce: data.safeNonce,
64
62
  }, { signer });
@@ -0,0 +1,33 @@
1
+ import { BaseDialProtocol } from "./BaseDialProtocol";
2
+ import { Transaction } from "@/db";
3
+
4
+ export class TransactionStatusDialProtocol extends BaseDialProtocol<string, Pick<Transaction, 'transactionHash' | 'sourceStatus' | 'sourceTransactionHash' | 'sourceErrors' | 'sourceLogs' | 'targetStatus' | 'targetTransactionHash' | 'targetErrors' | 'targetLogs' | 'status'> | null> {
5
+ protected timeout = 30000;
6
+
7
+ constructor(libp2p) {
8
+ super(libp2p, '/interop-x/transaction-status')
9
+ }
10
+
11
+ async response(transactionHash: string){
12
+ const transaction = await Transaction.findOne({ where: { transactionHash } })
13
+
14
+ if(! transaction){
15
+ return null
16
+ }
17
+ return {
18
+ transactionHash: transaction.transactionHash,
19
+
20
+ sourceStatus: transaction.sourceStatus,
21
+ sourceTransactionHash: transaction.sourceTransactionHash,
22
+ sourceErrors: transaction.sourceErrors,
23
+ sourceLogs: transaction.sourceLogs,
24
+
25
+ targetStatus: transaction.targetStatus,
26
+ targetTransactionHash: transaction.targetTransactionHash,
27
+ targetErrors: transaction.targetErrors,
28
+ targetLogs: transaction.targetLogs,
29
+
30
+ status: transaction.status,
31
+ }
32
+ }
33
+ }
@@ -6,6 +6,7 @@ import { IPeerInfo, peerPool } from "..";
6
6
  import config from "@/config";
7
7
  import { Event } from "@/types";
8
8
  import { Transaction } from "@/db";
9
+ import { TransactionStatusDialProtocol } from "./dial/TransactionStatusDialProtocol";
9
10
 
10
11
  export interface ProtocolOptions {
11
12
  /* Handshake timeout in ms (default: 8000) */
@@ -35,7 +36,7 @@ interface PeerInfoEvent extends BaseMessageEvent {
35
36
  }
36
37
 
37
38
  interface TransactionStatusEvent extends BaseMessageEvent {
38
- data: Pick<Transaction, 'transactionHash' | 'sourceStatus' | 'sourceTransactionHash' | 'sourceErrors' | 'targetStatus' | 'targetTransactionHash' | 'targetErrors' | 'status'>
39
+ data: Pick<Transaction, 'transactionHash' | 'sourceStatus' | 'sourceTransactionHash' | 'sourceErrors' | 'sourceLogs' | 'targetStatus' | 'targetTransactionHash' | 'targetErrors' | 'targetLogs' | 'status'>
39
40
  }
40
41
 
41
42
  declare interface Protocol {
@@ -65,31 +66,42 @@ class Protocol extends EventEmitter {
65
66
  Buffer.from(transaction.transactionHash),
66
67
 
67
68
  Buffer.from(transaction.sourceStatus),
68
- Buffer.from(transaction.sourceTransactionHash),
69
+ Buffer.from(transaction.sourceTransactionHash || ''),
69
70
  transaction.sourceErrors ? transaction.sourceErrors.map((e) => Buffer.from(e)) : [],
71
+ transaction.sourceLogs ? transaction.sourceLogs.map((e) => [Buffer.from(e.type), Buffer.from(e.message)]) : [],
70
72
 
71
73
  Buffer.from(transaction.targetStatus),
72
- Buffer.from(transaction.targetTransactionHash),
74
+ Buffer.from(transaction.targetTransactionHash || ''),
73
75
  transaction.targetErrors ? transaction.targetErrors.map((e) => Buffer.from(e)) : [],
76
+ transaction.targetLogs ? transaction.targetLogs.map((e) => [Buffer.from(e.type), Buffer.from(e.message)]) : [],
74
77
 
75
78
  Buffer.from(transaction.status),
76
79
  ],
77
- decode: ([transactionHash, sourceStatus, sourceTransactionHash, sourceErrors, targetStatus, targetTransactionHash, targetErrors, status]: [Buffer, Buffer, Buffer, Buffer[], Buffer, Buffer, Buffer[], Buffer]) => ({
80
+ decode: ([transactionHash, sourceStatus, sourceTransactionHash, sourceErrors, sourceLogs, targetStatus, targetTransactionHash, targetErrors, targetLogs, status]: [Buffer, Buffer, Buffer, Buffer[],[Buffer,Buffer][], Buffer, Buffer, Buffer[],[Buffer,Buffer][], Buffer]) => ({
78
81
  transactionHash: transactionHash.toString(),
79
82
 
80
83
  sourceStatus: sourceStatus.toString(),
81
- sourceTransactionHash: sourceTransactionHash.toString(),
84
+ sourceTransactionHash: sourceTransactionHash.toString() || null,
82
85
  sourceErrors: sourceErrors.map((e) => e.toString()),
86
+ sourceLogs: sourceLogs.map(e => ({
87
+ type: e[0].toString(),
88
+ message: e[1].toString(),
89
+ })),
83
90
 
84
91
  targetStatus: targetStatus.toString(),
85
- targetTransactionHash: targetTransactionHash.toString(),
92
+ targetTransactionHash: targetTransactionHash.toString() || null,
86
93
  targetErrors: targetErrors.map((e) => e.toString()),
94
+ targetLogs: targetLogs.map(e => ({
95
+ type: e[0].toString(),
96
+ message: e[1].toString(),
97
+ })),
87
98
 
88
99
  status: status.toString(),
89
100
  }),
90
101
  },
91
102
  ];
92
103
  private signature: SignatureDialProtocol;
104
+ private transactionStatus: TransactionStatusDialProtocol;
93
105
 
94
106
 
95
107
  start({ libp2p, topic = null, }) {
@@ -109,6 +121,7 @@ class Protocol extends EventEmitter {
109
121
  })
110
122
 
111
123
  this.signature = new SignatureDialProtocol(this.libp2p);
124
+ this.transactionStatus = new TransactionStatusDialProtocol(this.libp2p);
112
125
  }
113
126
 
114
127
 
@@ -177,6 +190,15 @@ class Protocol extends EventEmitter {
177
190
  return []
178
191
  }
179
192
  }
193
+
194
+ async requestTransactionStatus(transactionHash: string, peerId: string) {
195
+ try {
196
+ return await this.transactionStatus.send(transactionHash, peerId);
197
+ } catch (error) {
198
+ console.log(error);
199
+ return null
200
+ }
201
+ }
180
202
  }
181
203
 
182
204
  export const protocol = new Protocol();
@@ -1,12 +1,16 @@
1
1
  import { BaseTask } from "./BaseTask";
2
2
  import Logger from '@/logger';
3
- import { http } from "@/utils";
4
- import spawn from 'await-spawn';
3
+ import spawnAsync from 'await-spawn';
4
+ import { spawn } from 'child_process'
5
5
  import config from "@/config";
6
6
  import wait from "waait";
7
+ import packageJson from "../../package.json";
8
+
9
+ const currentVersion = packageJson.version;
10
+ const tag = config.staging ? 'dev' : 'latest';
7
11
 
8
12
  class AutoUpdateTask extends BaseTask {
9
- pollIntervalMs: number = 60 * 1000
13
+ pollIntervalMs: number = 60 * 10 * 1000
10
14
 
11
15
  constructor() {
12
16
  super({
@@ -18,15 +22,28 @@ class AutoUpdateTask extends BaseTask {
18
22
  return config.autoUpdate && !config.isLeadNode();
19
23
  }
20
24
 
21
- getCurrentVersion() {
22
- return require('../../package.json').version
25
+ async getInstalledVersion() {
26
+ try {
27
+ const stdout = await spawnAsync('npm', ['-g', 'ls', '--depth=0', '--json'])
28
+ return JSON.parse(stdout.toString()).dependencies[packageJson.name].version
29
+ } catch (error) {
30
+ this.logger.error(error)
31
+ return currentVersion
32
+ }
23
33
  }
24
- async pollHandler() {
25
34
 
26
- const { data } = await http.get('https://registry.npmjs.org/@instadapp/interop-x')
35
+ async getLatestVersion() {
36
+ try {
37
+ const stdout = await spawnAsync('npm', ['view', `${packageJson.name}@${tag}`, 'version'])
38
+ return stdout.toString().trim()
39
+ } catch (error) {
40
+ this.logger.error(error)
41
+ return currentVersion
42
+ }
43
+ }
27
44
 
28
- const version = data['dist-tags'].latest
29
- const currentVersion = this.getCurrentVersion()
45
+ async pollHandler() {
46
+ const version = await this.getLatestVersion()
30
47
 
31
48
  if (version === currentVersion) {
32
49
  return;
@@ -34,23 +51,30 @@ class AutoUpdateTask extends BaseTask {
34
51
 
35
52
  this.logger.warn(`New version ${version} available.`)
36
53
 
54
+ this.logger.info('Updating...')
37
55
 
38
- await spawn('npm', ['-g', 'install', '@instadapp/interop-x', '-f']);
39
-
40
- this.logger.warn(`Installed version ${version}`)
41
- this.logger.warn(`Restarting...`)
56
+ await spawnAsync('npm', ['-g', 'install', `@instadapp/interop-x@${tag}`, '-f']);
42
57
 
43
58
  await wait(5000)
44
59
 
45
- if (currentVersion === this.getCurrentVersion()) {
60
+ if (version !== await this.getInstalledVersion()) {
61
+ this.logger.warn(`failed to install ${version}, retrying in 5 minutes`)
46
62
  return;
47
63
  }
48
64
 
49
- spawn(process.argv[0], process.argv.slice(1), {
65
+ this.logger.warn(`Installed version ${version}`)
66
+ this.logger.warn(`Restarting...`)
67
+
68
+
69
+ // TODO: its restarting in the bg, but it should be in the fg
70
+ const subprocess = spawn(process.argv[0], process.argv.slice(1), {
50
71
  cwd: process.cwd(),
51
- stdio: "inherit"
72
+ stdio: "inherit",
73
+ // shell: process.env.SHELL,
52
74
  });
53
75
 
76
+ subprocess.unref();
77
+
54
78
  process.exit()
55
79
  }
56
80
  }
@@ -19,6 +19,7 @@ export class BaseTask extends EventEmitter implements IBaseTask {
19
19
  started: boolean = false
20
20
  pollIntervalMs: number = 10 * 1000
21
21
  leadNodeOnly: boolean = false
22
+ exceptLeadNode: boolean = false
22
23
 
23
24
  public constructor({ logger }: { logger?: Logger }) {
24
25
  super()
@@ -45,11 +46,20 @@ export class BaseTask extends EventEmitter implements IBaseTask {
45
46
  }
46
47
 
47
48
  prePollHandler(): boolean {
48
- if (!this.leadNodeOnly) {
49
- return true
49
+ if(config.isMaintenanceMode()){
50
+ this.logger.warn('Maintenance mode is enabled. Skipping task.')
51
+ return false
50
52
  }
51
53
 
52
- return config.isLeadNode()
54
+ if (this.exceptLeadNode) {
55
+ return !config.isLeadNode();
56
+ }
57
+
58
+ if (this.leadNodeOnly) {
59
+ return config.isLeadNode()
60
+ }
61
+
62
+ return true
53
63
  }
54
64
 
55
65
  async pollHandler() {
@@ -0,0 +1,136 @@
1
+ import { BaseTask } from "../BaseTask";
2
+ import Logger from '@/logger';
3
+ import { ethers } from "ethers";
4
+ import abi from "@/abi";
5
+ import { Transaction } from "@/db";
6
+ import { generateInteropTransactionHash, getContract, getRpcProviderUrl } from "@/utils";
7
+ import { addresses } from "@/constants";
8
+ import { ChainId } from "@/types";
9
+ import config from "@/config";
10
+ import { InteropX } from "@/typechain";
11
+
12
+ class SyncLogSubmitEvents extends BaseTask {
13
+ contractAddress: string;
14
+ provider: ethers.providers.JsonRpcProvider;
15
+ contract: InteropX;
16
+ chainId: ChainId;
17
+
18
+ constructor({ chainId }: { chainId: ChainId }) {
19
+ super({
20
+ logger: new Logger("InteropX::SyncLogSubmitEvents"),
21
+ })
22
+ this.chainId = chainId;
23
+ }
24
+
25
+ async pollHandler() {
26
+ const currentBlock = await this.provider.getBlockNumber();
27
+
28
+ const events = await this.contract.queryFilter(
29
+ this.contract.filters.LogSubmit(),
30
+ currentBlock - 2000,
31
+ currentBlock,
32
+ );
33
+
34
+ let processedEvents = 0;
35
+
36
+ for (const event of events) {
37
+
38
+ try {
39
+ if (!event.args) {
40
+ continue;
41
+ }
42
+
43
+ const {
44
+ position,
45
+ actionId,
46
+ actionIdHashHash,
47
+ sourceSender,
48
+ sourceDsaId,
49
+ targetDsaId,
50
+ sourceChainId,
51
+ targetChainId,
52
+ vnonce,
53
+ metadata,
54
+
55
+ } = event.args;
56
+
57
+ const uniqueIdentifier = {
58
+ actionId,
59
+ vnonce: vnonce.toString(),
60
+ sourceSender: sourceSender.toString(),
61
+ sourceChainId: sourceChainId.toNumber(),
62
+ targetChainId: targetChainId.toNumber(),
63
+ sourceDsaId: sourceDsaId.toString(),
64
+ targetDsaId: targetDsaId.toString(),
65
+ }
66
+
67
+ let transactionHash = generateInteropTransactionHash(uniqueIdentifier);
68
+
69
+ const transaction = await Transaction.findOne({ where: { transactionHash } });
70
+
71
+ if (transaction) {
72
+ continue;
73
+ }
74
+
75
+ await Transaction.create({
76
+ transactionHash,
77
+ ...uniqueIdentifier,
78
+ submitChainId: this.chainId,
79
+ submitTransactionHash: event.transactionHash,
80
+ submitBlockNumber: event.blockNumber,
81
+ submitCreatedAt: new Date(),
82
+ submitEvent: {
83
+ actionId,
84
+ actionIdHashHash,
85
+ vnonce: vnonce.toString(),
86
+ position: {
87
+ withdraw: position.withdraw.map((v) => ({
88
+ sourceToken: v.sourceToken,
89
+ targetToken: v.targetToken,
90
+ amount: v.amount.toString()
91
+ })),
92
+ supply: position.supply.map((v) => ({
93
+ sourceToken: v.sourceToken,
94
+ targetToken: v.targetToken,
95
+ amount: v.amount.toString()
96
+ })),
97
+ },
98
+ sourceChainId: sourceChainId.toNumber(),
99
+ targetChainId: targetChainId.toNumber(),
100
+ sourceSender,
101
+ sourceDsaId: sourceDsaId.toString(),
102
+ targetDsaId: targetDsaId.toString(),
103
+ metadata,
104
+ }
105
+ })
106
+
107
+ this.logger.info(
108
+ `New InteropX tranaction: ${transactionHash} `
109
+ );
110
+ } catch (error) {
111
+ this.logger.error(error);
112
+ }
113
+ }
114
+
115
+ if (processedEvents > 0)
116
+ this.logger.info(`${processedEvents} events processed`);
117
+ }
118
+
119
+ async start(): Promise<void> {
120
+ this.contractAddress = addresses[this.chainId].interopX;
121
+
122
+ this.provider = new ethers.providers.JsonRpcProvider(
123
+ getRpcProviderUrl(this.chainId)
124
+ );
125
+
126
+ this.contract = getContract<InteropX>(
127
+ this.contractAddress,
128
+ abi.interopX,
129
+ new ethers.Wallet(config.privateKey!, this.provider)
130
+ );
131
+
132
+ await super.start()
133
+ }
134
+ }
135
+
136
+ export default SyncLogSubmitEvents;