@instadapp/interop-x 0.0.0-dev.a168c79 → 0.0.0-dev.a775e30

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 (40) hide show
  1. package/bin/interop-x +1 -1
  2. package/dist/package.json +9 -5
  3. package/dist/src/api/index.js +3 -3
  4. package/dist/src/config/index.js +11 -1
  5. package/dist/src/constants/itokens.js +1 -1
  6. package/dist/src/index.js +69 -7
  7. package/dist/src/net/peer/index.js +8 -3
  8. package/dist/src/net/pool/index.js +32 -9
  9. package/dist/src/net/protocol/dial/SignatureDialProtocol.1.js +28 -0
  10. package/dist/src/net/protocol/dial/SignatureDialProtocol.js +11 -4
  11. package/dist/src/net/protocol/index.js +41 -1
  12. package/dist/src/tasks/AutoUpdateTask.js +70 -0
  13. package/dist/src/tasks/BaseTask.js +12 -4
  14. package/dist/src/tasks/InteropBridge/ProcessWithdrawEvents.js +146 -0
  15. package/dist/src/tasks/InteropBridge/SyncWithdrawEvents.js +69 -0
  16. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +32 -23
  17. package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +4 -5
  18. package/dist/src/tasks/Transactions/SyncTransactionStatusTask.js +53 -0
  19. package/dist/src/tasks/index.js +17 -0
  20. package/dist/src/utils/index.js +110 -9
  21. package/package.json +9 -5
  22. package/patches/@ethersproject+properties+5.6.0.patch +13 -0
  23. package/src/api/index.ts +2 -2
  24. package/src/config/index.ts +11 -1
  25. package/src/constants/itokens.ts +1 -1
  26. package/src/index.ts +90 -9
  27. package/src/net/peer/index.ts +9 -7
  28. package/src/net/pool/index.ts +41 -11
  29. package/src/net/protocol/dial/SignatureDialProtocol.1.ts +31 -0
  30. package/src/net/protocol/dial/SignatureDialProtocol.ts +12 -4
  31. package/src/net/protocol/index.ts +57 -1
  32. package/src/tasks/AutoUpdateTask.ts +82 -0
  33. package/src/tasks/BaseTask.ts +14 -4
  34. package/src/tasks/InteropBridge/ProcessWithdrawEvents.ts +231 -0
  35. package/src/tasks/InteropBridge/SyncWithdrawEvents.ts +119 -0
  36. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +44 -33
  37. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +6 -8
  38. package/src/tasks/Transactions/SyncTransactionStatusTask.ts +65 -0
  39. package/src/tasks/index.ts +24 -2
  40. package/src/utils/index.ts +145 -11
package/bin/interop-x CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- require('../dist/index')
2
+ require('../dist/src/index')
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instadapp/interop-x",
3
- "version": "0.0.0-dev.a168c79",
3
+ "version": "0.0.0-dev.a775e30",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "engines": {
@@ -12,7 +12,8 @@
12
12
  "build": "yarn generate-abi-types && export GIT_REF=$(git rev-parse --short HEAD) && rimraf ./dist && tsc -p tsconfig.json && replace-in-file '@GIT_SHORT_HASH@' $GIT_REF ./dist/**/*.js",
13
13
  "dev": "yarn generate-abi-types && NODE_ENV=development nodemon",
14
14
  "generate-abi-types": "typechain --target=ethers-v5 'src/abi/*.json' --out-dir 'src/typechain'",
15
- "prepublishOnly": "yarn build"
15
+ "prepublishOnly": "yarn build",
16
+ "postinstall": "patch-package"
16
17
  },
17
18
  "nodemonConfig": {
18
19
  "watch": [
@@ -23,9 +24,10 @@
23
24
  },
24
25
  "dependencies": {
25
26
  "@achingbrain/libp2p-gossipsub": "^0.12.2",
27
+ "@fastify/cors": "^7.0.0",
28
+ "await-spawn": "^4.0.2",
26
29
  "axios": "^0.27.1",
27
30
  "axios-retry": "^3.2.4",
28
- "bignumber.js": "^9.0.2",
29
31
  "chalk": "4.1.2",
30
32
  "dotenv": "^16.0.0",
31
33
  "ethereumjs-util": "^7.1.4",
@@ -33,7 +35,7 @@
33
35
  "ethers-multisend": "^2.1.1",
34
36
  "expand-home-dir": "^0.0.3",
35
37
  "fastify": "^3.28.0",
36
- "fastify-cors": "^6.0.3",
38
+ "fs-extra": "^10.1.0",
37
39
  "libp2p": "^0.36.2",
38
40
  "libp2p-bootstrap": "^0.14.0",
39
41
  "libp2p-kad-dht": "^0.28.6",
@@ -45,7 +47,9 @@
45
47
  "libp2p-websockets": "^0.16.2",
46
48
  "luxon": "^2.3.2",
47
49
  "module-alias": "^2.2.2",
48
- "sequelize": "^6.19.0",
50
+ "patch-package": "^6.4.7",
51
+ "postinstall-postinstall": "^2.1.0",
52
+ "sequelize": "6.18.0",
49
53
  "sqlite3": "^5.0.5",
50
54
  "waait": "^1.0.5"
51
55
  },
@@ -5,12 +5,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.startApiServer = void 0;
7
7
  const fastify_1 = __importDefault(require("fastify"));
8
- const fastify_cors_1 = __importDefault(require("fastify-cors"));
8
+ const cors_1 = __importDefault(require("@fastify/cors"));
9
9
  const logger_1 = __importDefault(require("@/logger"));
10
10
  const db_1 = require("@/db");
11
11
  const logger = new logger_1.default("RPC");
12
12
  const server = (0, fastify_1.default)({ logger: false });
13
- server.register(fastify_cors_1.default, {});
13
+ server.register(cors_1.default, {});
14
14
  server.get('/', async () => 'Interop X API');
15
15
  const startApiServer = async () => {
16
16
  const HOST = process.env.API_HOST || '0.0.0.0';
@@ -26,7 +26,7 @@ const startApiServer = async () => {
26
26
  logger.log(`RPC Server listening at http://${HOST}:${PORT}`);
27
27
  }
28
28
  catch (err) {
29
- logger.error(err);
29
+ logger.error(err.message);
30
30
  process.exit(1);
31
31
  }
32
32
  };
@@ -1,15 +1,22 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  const ethers_1 = require("ethers");
4
7
  const types_1 = require("@/types");
8
+ const fs_extra_1 = __importDefault(require("fs-extra"));
9
+ const expand_home_dir_1 = __importDefault(require("expand-home-dir"));
5
10
  class Config {
6
11
  constructor() {
7
12
  this.events = new types_1.EventBus();
8
- this.maxPeers = 10;
13
+ this.maxPeers = 20;
9
14
  this.privateKey = process.env.PRIVATE_KEY;
10
15
  this.staging = !!process.env.STAGING && process.env.STAGING === 'true';
16
+ this.autoUpdate = !!process.env.AUTO_UPDATE && process.env.AUTO_UPDATE === 'true';
11
17
  this.wallet = new ethers_1.Wallet(this.privateKey);
12
18
  this.leadNodeAddress = '0x910E413DBF3F6276Fe8213fF656726bDc142E08E';
19
+ this.baseConfigPath = (0, expand_home_dir_1.default)(`~/.interop-x`);
13
20
  }
14
21
  get publicAddress() {
15
22
  return this.wallet.address;
@@ -17,5 +24,8 @@ class Config {
17
24
  isLeadNode() {
18
25
  return ethers_1.ethers.utils.getAddress(this.leadNodeAddress) === ethers_1.ethers.utils.getAddress(this.wallet.address);
19
26
  }
27
+ isMaintenanceMode() {
28
+ return fs_extra_1.default.existsSync(this.baseConfigPath + '/maintenance');
29
+ }
20
30
  }
21
31
  exports.default = new Config();
@@ -5,7 +5,7 @@ exports.itokens = {
5
5
  1: [],
6
6
  137: [
7
7
  {
8
- address: '0x6c20F03598d5ABF729348E2868b0ff5e8A48aB1F',
8
+ address: '0xEab02fe1F016eE3e4106c1C6aad35FeEe657268E',
9
9
  symbol: 'USDC',
10
10
  }
11
11
  ],
package/dist/src/index.js CHANGED
@@ -4,6 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const module_alias_1 = __importDefault(require("module-alias"));
7
+ const expand_home_dir_1 = __importDefault(require("expand-home-dir"));
8
+ const fs_extra_1 = __importDefault(require("fs-extra"));
7
9
  module_alias_1.default.addAliases({
8
10
  "@/": __dirname + "/",
9
11
  "@/logger": __dirname + "/logger",
@@ -19,36 +21,96 @@ module_alias_1.default.addAliases({
19
21
  "@/typechain": __dirname + "/typechain"
20
22
  });
21
23
  (0, module_alias_1.default)();
22
- const assert_1 = __importDefault(require("assert"));
23
24
  const dotenv_1 = __importDefault(require("dotenv"));
25
+ const chalk_1 = __importDefault(require("chalk"));
24
26
  const ethers_1 = require("ethers");
25
27
  const package_json_1 = __importDefault(require("../package.json"));
26
28
  dotenv_1.default.config();
27
29
  const logger_1 = __importDefault(require("@/logger"));
28
30
  const logger = new logger_1.default('Process');
29
- if (process.argv.at(-1) === 'help') {
31
+ const GIT_SHORT_HASH = 'a775e30';
32
+ const printUsage = () => {
33
+ console.log();
34
+ console.log(`Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
35
+ console.log();
30
36
  console.log('Usage:');
31
- console.log(' PRIVATE_KEY=abcd1234 interop-x');
32
- console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x');
37
+ console.log(' interop-x help Show this message');
38
+ console.log(' interop-x version Print out the installed version of Interop X');
39
+ console.log();
40
+ console.log(' interop-x down Put the node into maintenance mode');
41
+ console.log(' interop-x up Take the node out of maintenance mode');
42
+ console.log();
43
+ console.log(' PRIVATE_KEY=abcd1234 interop-x Start the node with the given private key');
44
+ console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x Start the node in staging mode');
45
+ console.log(' PRIVATE_KEY=abcd1234 AUTO_UPDATE=true interop-x Start the node in auto update mode');
46
+ 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');
47
+ console.log();
48
+ };
49
+ if (process.argv.at(-1) === 'help') {
50
+ printUsage();
33
51
  process.exit(0);
34
52
  }
35
- (0, assert_1.default)(process.env.PRIVATE_KEY, "PRIVATE_KEY is not defined");
53
+ const basePath = (0, expand_home_dir_1.default)(`~/.interop-x`);
54
+ if (process.argv.at(-1) === 'down') {
55
+ fs_extra_1.default.outputFileSync(basePath + '/maintenance', Date.now().toString());
56
+ console.log(chalk_1.default.red('Maintenance mode enabled'));
57
+ process.exit(0);
58
+ }
59
+ if (process.argv.at(-1) === 'up') {
60
+ fs_extra_1.default.removeSync(basePath + '/maintenance');
61
+ console.log(chalk_1.default.green('Maintenance mode disabled'));
62
+ process.exit(0);
63
+ }
64
+ if (process.argv.at(-1) === 'version') {
65
+ console.log(`Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
66
+ process.exit(0);
67
+ }
68
+ if (!process.env.PRIVATE_KEY) {
69
+ console.error(chalk_1.default.bgRed.white.bold('Please provide a private key\n'));
70
+ printUsage();
71
+ process.exit(1);
72
+ }
36
73
  try {
37
74
  new ethers_1.ethers.Wallet(process.env.PRIVATE_KEY);
38
75
  }
39
76
  catch (e) {
40
- logger.error('Invalid private key');
77
+ console.error(chalk_1.default.bgRed.white('Invalid private key\n'));
78
+ printUsage();
41
79
  process.exit(1);
42
80
  }
43
- logger.debug(`Starting Interop X Node (v${package_json_1.default.version} - rev.a168c79)`);
81
+ logger.debug(`Starting Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
44
82
  const tasks_1 = require("@/tasks");
45
83
  const net_1 = require("@/net");
46
84
  const api_1 = require("@/api");
85
+ const db_1 = require("./db");
86
+ const utils_1 = require("./utils");
47
87
  async function main() {
48
88
  (0, net_1.startPeer)({});
49
89
  const tasks = new tasks_1.Tasks();
50
90
  tasks.start();
51
91
  (0, api_1.startApiServer)();
92
+ net_1.protocol.on('TransactionStatus', async (payload) => {
93
+ if (!net_1.peerPool.isLeadNode(payload.peerId)) {
94
+ const peer = net_1.peerPool.getPeer(payload.peerId);
95
+ if (!peer) {
96
+ return;
97
+ }
98
+ logger.info(`ignored transaction status from ${payload.peerId} ${(0, utils_1.shortenHash)(peer.publicAddress)} `);
99
+ return;
100
+ }
101
+ const transaction = await db_1.Transaction.findOne({ where: { transactionHash: payload.data.transactionHash } });
102
+ if (!transaction) {
103
+ return;
104
+ }
105
+ transaction.sourceStatus = payload.data.sourceStatus;
106
+ transaction.sourceTransactionHash = payload.data.sourceTransactionHash;
107
+ transaction.sourceErrors = payload.data.sourceErrors;
108
+ transaction.targetStatus = payload.data.targetStatus;
109
+ transaction.targetTransactionHash = payload.data.targetTransactionHash;
110
+ transaction.targetErrors = payload.data.targetErrors;
111
+ transaction.status = payload.data.status;
112
+ await transaction.save();
113
+ });
52
114
  }
53
115
  main()
54
116
  .then(() => {
@@ -23,6 +23,7 @@ const libp2p_kad_dht_1 = __importDefault(require("libp2p-kad-dht"));
23
23
  const libp2p_pubsub_peer_discovery_1 = __importDefault(require("libp2p-pubsub-peer-discovery"));
24
24
  const net_1 = require("@/net");
25
25
  const config_1 = __importDefault(require("@/config"));
26
+ const chalk_1 = __importDefault(require("chalk"));
26
27
  const logger = new logger_1.default("Peer");
27
28
  let node;
28
29
  // Known peers addresses
@@ -77,13 +78,17 @@ const startPeer = async ({}) => {
77
78
  persistence: true,
78
79
  },
79
80
  });
80
- logger.info("Peer ID:", node.peerId.toB58String());
81
+ logger.info("Peer ID:", chalk_1.default.bold(node.peerId.toB58String()));
81
82
  await node.start();
82
83
  net_1.protocol.start({
83
84
  libp2p: node
84
85
  });
85
- node.on("peer:discovery", (peer) => logger.log(`Discovered peer ${peer}`)); // peer disc.
86
- node.connectionManager.on("peer:connect", (connection) => logger.log(`Connected to ${connection.remotePeer.toB58String()}`));
86
+ node.on("peer:discovery", (peer) => {
87
+ // logger.log(`Discovered peer ${peer}`)
88
+ }); // peer disc.
89
+ node.connectionManager.on("peer:connect", (connection) => {
90
+ // logger.log(`Connected to ${connection.remotePeer.toB58String()}`)
91
+ });
87
92
  logger.log("Peer discovery started");
88
93
  await (0, waait_1.default)(1000);
89
94
  setInterval(() => net_1.protocol.sendPeerInfo({
@@ -6,6 +6,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.peerPool = exports.PeerPool = void 0;
7
7
  const types_1 = require("@/types");
8
8
  const config_1 = __importDefault(require("@/config"));
9
+ const logger_1 = __importDefault(require("@/logger"));
10
+ const utils_1 = require("ethers/lib/utils");
11
+ const utils_2 = require("@/utils");
12
+ const chalk_1 = __importDefault(require("chalk"));
13
+ const logger = new logger_1.default('PeerPool');
9
14
  class PeerPool {
10
15
  constructor() {
11
16
  this.PEERS_CLEANUP_TIME_LIMIT = 1;
@@ -62,10 +67,14 @@ class PeerPool {
62
67
  * @emits {@link Event.POOL_PEER_ADDED}
63
68
  */
64
69
  add(peer) {
65
- if (peer && peer.id && !this.pool.get(peer.id)) {
70
+ if (peer && peer.id) {
71
+ const newPeer = !this.pool.get(peer.id);
66
72
  this.pool.set(peer.id, peer);
67
73
  peer.pooled = true;
68
- config_1.default.events.emit(types_1.Event.POOL_PEER_ADDED, peer);
74
+ if (newPeer) {
75
+ config_1.default.events.emit(types_1.Event.POOL_PEER_ADDED, peer);
76
+ logger.info(`Peer ${chalk_1.default.bold((0, utils_2.shortenHash)(peer.id, 16))} with address ${chalk_1.default.bold((0, utils_2.shortenHash)(peer.publicAddress))} added to pool`);
77
+ }
69
78
  }
70
79
  }
71
80
  /**
@@ -78,6 +87,7 @@ class PeerPool {
78
87
  if (this.pool.delete(peer.id)) {
79
88
  peer.pooled = false;
80
89
  config_1.default.events.emit(types_1.Event.POOL_PEER_REMOVED, peer);
90
+ logger.info(`Peer ${chalk_1.default.bold((0, utils_2.shortenHash)(peer.id, 16))} with address ${chalk_1.default.bold((0, utils_2.shortenHash)(peer.publicAddress))} removed from pool`);
81
91
  }
82
92
  }
83
93
  }
@@ -93,14 +103,27 @@ class PeerPool {
93
103
  get activePeerIds() {
94
104
  return this.activePeers.map((p) => p.id);
95
105
  }
106
+ getPeer(id) {
107
+ return this.pool.get(id);
108
+ }
109
+ isLeadNode(id) {
110
+ const peer = this.pool.get(id);
111
+ if (!peer) {
112
+ return false;
113
+ }
114
+ return (0, utils_1.getAddress)(peer.publicAddress) === (0, utils_1.getAddress)(config_1.default.leadNodeAddress);
115
+ }
116
+ getLeadPeer() {
117
+ return this.peers.find((p) => this.isLeadNode(p.id));
118
+ }
96
119
  cleanup() {
97
- let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60;
98
- this.peers.forEach((peerInfo) => {
99
- if (peerInfo.updated.getTime() < compDate) {
100
- console.log(`Peer ${peerInfo.id} idle for ${this.PEERS_CLEANUP_TIME_LIMIT} minutes`);
101
- this.remove(peerInfo);
102
- }
103
- });
120
+ // let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
121
+ // this.peers.forEach((peerInfo) => {
122
+ // if (peerInfo.updated.getTime() < compDate) {
123
+ // console.log(`Peer ${peerInfo.id} idle for ${this.PEERS_CLEANUP_TIME_LIMIT} minutes`)
124
+ // this.remove(peerInfo)
125
+ // }
126
+ // })
104
127
  }
105
128
  }
106
129
  exports.PeerPool = PeerPool;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TransactionStatusDialProtocol = void 0;
4
+ const BaseDialProtocol_1 = require("./BaseDialProtocol");
5
+ const db_1 = require("@/db");
6
+ class TransactionStatusDialProtocol extends BaseDialProtocol_1.BaseDialProtocol {
7
+ constructor(libp2p) {
8
+ super(libp2p, '/interop-x/transaction-status');
9
+ this.timeout = 30000;
10
+ }
11
+ async response(transactionHash) {
12
+ const transaction = await db_1.Transaction.findOne({ where: { transactionHash } });
13
+ if (!transaction) {
14
+ return null;
15
+ }
16
+ return {
17
+ transactionHash: transaction.transactionHash,
18
+ sourceStatus: transaction.sourceStatus,
19
+ sourceTransactionHash: transaction.sourceTransactionHash,
20
+ sourceErrors: transaction.sourceErrors,
21
+ targetStatus: transaction.targetStatus,
22
+ targetTransactionHash: transaction.targetTransactionHash,
23
+ targetErrors: transaction.targetErrors,
24
+ status: transaction.status,
25
+ };
26
+ }
27
+ }
28
+ exports.TransactionStatusDialProtocol = TransactionStatusDialProtocol;
@@ -33,12 +33,19 @@ class SignatureDialProtocol extends BaseDialProtocol_1.BaseDialProtocol {
33
33
  error: 'Event not found'
34
34
  };
35
35
  }
36
+ console.log("signing:", {
37
+ to: constants_1.addresses[transaction.targetChainId].multisend,
38
+ data: await (0, utils_1.buildDataForTransaction)(transaction, data.type),
39
+ chainId: transaction.targetChainId,
40
+ safeTxGas: data.safeTxGas,
41
+ nonce: data.safeNonce,
42
+ });
36
43
  const signedData = await (0, utils_1.signGnosisSafeTx)({
37
- //TODO: chain id depends on event type
38
- to: constants_1.addresses[transaction.sourceChainId].multisend,
39
- data: (0, utils_1.buildDataForTransaction)(transaction, data.type),
40
- chainId: transaction.sourceChainId,
44
+ to: constants_1.addresses[transaction.targetChainId].multisend,
45
+ data: await (0, utils_1.buildDataForTransaction)(transaction, data.type),
46
+ chainId: transaction.targetChainId,
41
47
  safeTxGas: data.safeTxGas,
48
+ nonce: data.safeNonce,
42
49
  }, { signer });
43
50
  return {
44
51
  signer: signer.address,
@@ -10,13 +10,14 @@ const SignatureDialProtocol_1 = require("./dial/SignatureDialProtocol");
10
10
  const __1 = require("..");
11
11
  const config_1 = __importDefault(require("@/config"));
12
12
  const types_1 = require("@/types");
13
+ const SignatureDialProtocol_1_1 = require("./dial/SignatureDialProtocol.1");
13
14
  class Protocol extends stream_1.EventEmitter {
14
15
  constructor() {
15
16
  super(...arguments);
16
17
  this.protocolMessages = [
17
18
  {
18
19
  name: 'PeerInfo',
19
- code: 0x09,
20
+ code: 0x01,
20
21
  encode: (info) => [
21
22
  Buffer.from(info.publicAddress),
22
23
  ],
@@ -24,6 +25,30 @@ class Protocol extends stream_1.EventEmitter {
24
25
  publicAddress: publicAddress.toString(),
25
26
  }),
26
27
  },
28
+ {
29
+ name: 'TransactionStatus',
30
+ code: 0x02,
31
+ encode: (transaction) => [
32
+ Buffer.from(transaction.transactionHash),
33
+ Buffer.from(transaction.sourceStatus),
34
+ Buffer.from(transaction.sourceTransactionHash),
35
+ transaction.sourceErrors ? transaction.sourceErrors.map((e) => Buffer.from(e)) : [],
36
+ Buffer.from(transaction.targetStatus),
37
+ Buffer.from(transaction.targetTransactionHash),
38
+ transaction.targetErrors ? transaction.targetErrors.map((e) => Buffer.from(e)) : [],
39
+ Buffer.from(transaction.status),
40
+ ],
41
+ decode: ([transactionHash, sourceStatus, sourceTransactionHash, sourceErrors, targetStatus, targetTransactionHash, targetErrors, status]) => ({
42
+ transactionHash: transactionHash.toString(),
43
+ sourceStatus: sourceStatus.toString(),
44
+ sourceTransactionHash: sourceTransactionHash.toString(),
45
+ sourceErrors: sourceErrors.map((e) => e.toString()),
46
+ targetStatus: targetStatus.toString(),
47
+ targetTransactionHash: targetTransactionHash.toString(),
48
+ targetErrors: targetErrors.map((e) => e.toString()),
49
+ status: status.toString(),
50
+ }),
51
+ },
27
52
  ];
28
53
  }
29
54
  start({ libp2p, topic = null, }) {
@@ -40,6 +65,7 @@ class Protocol extends stream_1.EventEmitter {
40
65
  });
41
66
  });
42
67
  this.signature = new SignatureDialProtocol_1.SignatureDialProtocol(this.libp2p);
68
+ this.transactionStatus = new SignatureDialProtocol_1_1.TransactionStatusDialProtocol(this.libp2p);
43
69
  }
44
70
  init() {
45
71
  this.libp2p.pubsub.subscribe(this.topic);
@@ -75,6 +101,11 @@ class Protocol extends stream_1.EventEmitter {
75
101
  const encoded = ethereumjs_util_1.rlp.encode([message.code, message.encode(data)]);
76
102
  this.libp2p.pubsub.publish(this.topic, encoded);
77
103
  }
104
+ sendTransaction(transaction) {
105
+ const message = this.protocolMessages.find((m) => m.name === 'TransactionStatus');
106
+ const encoded = ethereumjs_util_1.rlp.encode([message.code, message.encode(transaction)]);
107
+ this.libp2p.pubsub.publish(this.topic, encoded);
108
+ }
78
109
  async requestSignatures(data, peerIds) {
79
110
  try {
80
111
  peerIds = peerIds || __1.peerPool.activePeerIds;
@@ -88,5 +119,14 @@ class Protocol extends stream_1.EventEmitter {
88
119
  return [];
89
120
  }
90
121
  }
122
+ async requestTransactionStatus(transactionHash, peerId) {
123
+ try {
124
+ return await this.transactionStatus.send(transactionHash, peerId);
125
+ }
126
+ catch (error) {
127
+ console.log(error);
128
+ return null;
129
+ }
130
+ }
91
131
  }
92
132
  exports.protocol = new Protocol();
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const BaseTask_1 = require("./BaseTask");
7
+ const logger_1 = __importDefault(require("@/logger"));
8
+ const await_spawn_1 = __importDefault(require("await-spawn"));
9
+ const child_process_1 = require("child_process");
10
+ const config_1 = __importDefault(require("@/config"));
11
+ const waait_1 = __importDefault(require("waait"));
12
+ const package_json_1 = __importDefault(require("../../package.json"));
13
+ const currentVersion = package_json_1.default.version;
14
+ const tag = config_1.default.staging ? 'dev' : 'latest';
15
+ class AutoUpdateTask extends BaseTask_1.BaseTask {
16
+ constructor() {
17
+ super({
18
+ logger: new logger_1.default("AutoUpdateTask"),
19
+ });
20
+ this.pollIntervalMs = 60 * 10 * 1000;
21
+ }
22
+ prePollHandler() {
23
+ return config_1.default.autoUpdate && !config_1.default.isLeadNode();
24
+ }
25
+ async getInstalledVersion() {
26
+ try {
27
+ const stdout = await (0, await_spawn_1.default)('npm', ['-g', 'ls', '--depth=0', '--json']);
28
+ return JSON.parse(stdout.toString()).dependencies[package_json_1.default.name].version;
29
+ }
30
+ catch (error) {
31
+ this.logger.error(error);
32
+ return currentVersion;
33
+ }
34
+ }
35
+ async getLatestVersion() {
36
+ try {
37
+ const stdout = await (0, await_spawn_1.default)('npm', ['view', `${package_json_1.default.name}@${tag}`, 'version']);
38
+ return stdout.toString().trim();
39
+ }
40
+ catch (error) {
41
+ this.logger.error(error);
42
+ return currentVersion;
43
+ }
44
+ }
45
+ async pollHandler() {
46
+ const version = await this.getLatestVersion();
47
+ if (version === currentVersion) {
48
+ return;
49
+ }
50
+ this.logger.warn(`New version ${version} available.`);
51
+ this.logger.info('Updating...');
52
+ await (0, await_spawn_1.default)('npm', ['-g', 'install', `@instadapp/interop-x@${tag}`, '-f']);
53
+ await (0, waait_1.default)(5000);
54
+ if (version !== await this.getInstalledVersion()) {
55
+ this.logger.warn(`failed to install ${version}, retrying in 5 minutes`);
56
+ return;
57
+ }
58
+ this.logger.warn(`Installed version ${version}`);
59
+ this.logger.warn(`Restarting...`);
60
+ // TODO: its restarting in the bg, but it should be in the fg
61
+ const subprocess = (0, child_process_1.spawn)(process.argv[0], process.argv.slice(1), {
62
+ cwd: process.cwd(),
63
+ stdio: "inherit",
64
+ // shell: process.env.SHELL,
65
+ });
66
+ subprocess.unref();
67
+ process.exit();
68
+ }
69
+ }
70
+ exports.default = AutoUpdateTask;
@@ -14,6 +14,7 @@ class BaseTask extends events_1.default {
14
14
  this.started = false;
15
15
  this.pollIntervalMs = 10 * 1000;
16
16
  this.leadNodeOnly = false;
17
+ this.exceptLeadNode = false;
17
18
  this.logger = logger !== null && logger !== void 0 ? logger : new logger_1.default('BaseTask');
18
19
  }
19
20
  async pollCheck() {
@@ -28,16 +29,23 @@ class BaseTask extends events_1.default {
28
29
  }
29
30
  }
30
31
  catch (err) {
31
- this.logger.error(`poll check error: ${err.message}\ntrace: ${err.stack}`);
32
+ this.logger.error(`poll check error:\n${err.message}\ntrace: ${err.stack}`);
32
33
  }
33
34
  await this.postPollHandler();
34
35
  }
35
36
  }
36
37
  prePollHandler() {
37
- if (!this.leadNodeOnly) {
38
- return true;
38
+ if (config_1.default.isMaintenanceMode()) {
39
+ this.logger.warn('Maintenance mode is enabled. Skipping task.');
40
+ return false;
39
41
  }
40
- return config_1.default.isLeadNode();
42
+ if (this.exceptLeadNode) {
43
+ return !config_1.default.isLeadNode();
44
+ }
45
+ if (this.leadNodeOnly) {
46
+ return config_1.default.isLeadNode();
47
+ }
48
+ return true;
41
49
  }
42
50
  async pollHandler() {
43
51
  this.logger.warn('pollHandler not implemented');