@instadapp/interop-x 0.0.0-dev.f9253db → 0.0.0-dev.fabee70

Sign up to get free protection for your applications and to get access to all the features.
Files changed (73) hide show
  1. package/bin/interop-x +1 -1
  2. package/dist/package.json +73 -0
  3. package/dist/{abi → src/abi}/erc20.json +0 -0
  4. package/dist/{abi → src/abi}/gnosisSafe.json +0 -0
  5. package/dist/{abi → src/abi}/index.js +0 -0
  6. package/dist/{abi → src/abi}/interopBridgeToken.json +0 -0
  7. package/dist/{abi → src/abi}/interopXGateway.json +0 -0
  8. package/dist/src/api/index.js +33 -0
  9. package/dist/{config → src/config}/index.js +1 -0
  10. package/dist/{constants → src/constants}/addresses.js +0 -8
  11. package/dist/{constants → src/constants}/index.js +1 -0
  12. package/dist/src/constants/itokens.js +13 -0
  13. package/dist/{constants → src/constants}/tokens.js +0 -0
  14. package/dist/{db → src/db}/index.js +0 -0
  15. package/dist/{db → src/db}/models/index.js +0 -0
  16. package/dist/{db → src/db}/models/transaction.js +3 -1
  17. package/dist/{db → src/db}/sequelize.js +0 -0
  18. package/dist/src/index.js +107 -0
  19. package/dist/{logger → src/logger}/index.js +0 -0
  20. package/dist/{net → src/net}/index.js +0 -0
  21. package/dist/{net → src/net}/peer/index.js +8 -3
  22. package/dist/{net → src/net}/pool/index.js +32 -9
  23. package/dist/{net → src/net}/protocol/dial/BaseDialProtocol.js +0 -0
  24. package/dist/src/net/protocol/dial/SignatureDialProtocol.1.js +28 -0
  25. package/dist/{net → src/net}/protocol/dial/SignatureDialProtocol.js +22 -12
  26. package/dist/{net → src/net}/protocol/index.js +41 -1
  27. package/dist/src/tasks/AutoUpdateTask.js +57 -0
  28. package/dist/{tasks → src/tasks}/BaseTask.js +8 -4
  29. package/dist/src/tasks/InteropBridge/ProcessWithdrawEvents.js +146 -0
  30. package/dist/src/tasks/InteropBridge/SyncWithdrawEvents.js +69 -0
  31. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +149 -0
  32. package/dist/{tasks → src/tasks}/InteropXGateway/SyncDepositEvents.js +16 -21
  33. package/dist/src/tasks/Transactions/SyncTransactionStatusTask.js +53 -0
  34. package/dist/src/tasks/index.js +44 -0
  35. package/dist/{typechain → src/typechain}/Erc20.js +0 -0
  36. package/dist/{typechain → src/typechain}/GnosisSafe.js +0 -0
  37. package/dist/{typechain → src/typechain}/InteropBridgeToken.js +0 -0
  38. package/dist/{typechain → src/typechain}/InteropXGateway.js +0 -0
  39. package/dist/{typechain → src/typechain}/common.js +0 -0
  40. package/dist/{typechain → src/typechain}/factories/Erc20__factory.js +0 -0
  41. package/dist/{typechain → src/typechain}/factories/GnosisSafe__factory.js +0 -0
  42. package/dist/{typechain → src/typechain}/factories/InteropBridgeToken__factory.js +0 -0
  43. package/dist/{typechain → src/typechain}/factories/InteropXGateway__factory.js +0 -0
  44. package/dist/{typechain → src/typechain}/factories/index.js +0 -0
  45. package/dist/{typechain → src/typechain}/index.js +0 -0
  46. package/dist/{types.js → src/types.js} +0 -0
  47. package/dist/src/utils/index.js +238 -0
  48. package/package.json +9 -3
  49. package/patches/@ethersproject+properties+5.6.0.patch +13 -0
  50. package/src/api/index.ts +33 -0
  51. package/src/config/index.ts +2 -0
  52. package/src/constants/addresses.ts +0 -8
  53. package/src/constants/index.ts +1 -0
  54. package/src/constants/itokens.ts +10 -0
  55. package/src/db/models/transaction.ts +8 -4
  56. package/src/index.ts +62 -6
  57. package/src/net/peer/index.ts +9 -7
  58. package/src/net/pool/index.ts +41 -11
  59. package/src/net/protocol/dial/SignatureDialProtocol.1.ts +31 -0
  60. package/src/net/protocol/dial/SignatureDialProtocol.ts +25 -13
  61. package/src/net/protocol/index.ts +57 -1
  62. package/src/tasks/AutoUpdateTask.ts +73 -0
  63. package/src/tasks/BaseTask.ts +9 -4
  64. package/src/tasks/InteropBridge/ProcessWithdrawEvents.ts +231 -0
  65. package/src/tasks/InteropBridge/SyncWithdrawEvents.ts +119 -0
  66. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +243 -0
  67. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +23 -13
  68. package/src/tasks/Transactions/SyncTransactionStatusTask.ts +65 -0
  69. package/src/tasks/index.ts +24 -2
  70. package/src/utils/index.ts +197 -7
  71. package/dist/index.js +0 -63
  72. package/dist/tasks/index.js +0 -27
  73. package/dist/utils/index.js +0 -101
package/bin/interop-x CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- require('../dist/index')
2
+ require('../dist/src/index')
@@ -0,0 +1,73 @@
1
+ {
2
+ "name": "@instadapp/interop-x",
3
+ "version": "0.0.0-dev.fabee70",
4
+ "license": "MIT",
5
+ "main": "dist/index.js",
6
+ "engines": {
7
+ "node": ">=16",
8
+ "yarn": "^1.22.0"
9
+ },
10
+ "scripts": {
11
+ "start": "yarn build && node bin/interop-x",
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
+ "dev": "yarn generate-abi-types && NODE_ENV=development nodemon",
14
+ "generate-abi-types": "typechain --target=ethers-v5 'src/abi/*.json' --out-dir 'src/typechain'",
15
+ "prepublishOnly": "yarn build",
16
+ "postinstall": "patch-package"
17
+ },
18
+ "nodemonConfig": {
19
+ "watch": [
20
+ "src"
21
+ ],
22
+ "ext": "ts",
23
+ "exec": "./node_modules/.bin/ts-node --files -r tsconfig-paths/register ./src/index.ts"
24
+ },
25
+ "dependencies": {
26
+ "@achingbrain/libp2p-gossipsub": "^0.12.2",
27
+ "@fastify/cors": "^7.0.0",
28
+ "await-spawn": "^4.0.2",
29
+ "axios": "^0.27.1",
30
+ "axios-retry": "^3.2.4",
31
+ "bignumber.js": "^9.0.2",
32
+ "chalk": "4.1.2",
33
+ "dotenv": "^16.0.0",
34
+ "ethereumjs-util": "^7.1.4",
35
+ "ethers": "^5.6.4",
36
+ "ethers-multisend": "^2.1.1",
37
+ "expand-home-dir": "^0.0.3",
38
+ "fastify": "^3.28.0",
39
+ "libp2p": "^0.36.2",
40
+ "libp2p-bootstrap": "^0.14.0",
41
+ "libp2p-kad-dht": "^0.28.6",
42
+ "libp2p-mdns": "^0.18.0",
43
+ "libp2p-mplex": "^0.10.7",
44
+ "libp2p-noise": "^4.0.0",
45
+ "libp2p-pubsub-peer-discovery": "^4.0.0",
46
+ "libp2p-tcp": "^0.17.2",
47
+ "libp2p-websockets": "^0.16.2",
48
+ "luxon": "^2.3.2",
49
+ "module-alias": "^2.2.2",
50
+ "patch-package": "^6.4.7",
51
+ "postinstall-postinstall": "^2.1.0",
52
+ "sequelize": "6.18.0",
53
+ "sqlite3": "^5.0.5",
54
+ "waait": "^1.0.5"
55
+ },
56
+ "bin": {
57
+ "interop-x": "bin/interop-x",
58
+ "interopx": "bin/interop-x"
59
+ },
60
+ "devDependencies": {
61
+ "@typechain/ethers-v5": "^10.0.0",
62
+ "@types/bn.js": "^5.1.0",
63
+ "@types/fs-extra": "^9.0.13",
64
+ "@types/node": "^17.0.17",
65
+ "nodemon": "^2.0.15",
66
+ "replace-in-file": "^6.3.2",
67
+ "rimraf": "^3.0.2",
68
+ "ts-node": "^10.5.0",
69
+ "tsconfig-paths": "^3.12.0",
70
+ "typechain": "^8.0.0",
71
+ "typescript": "^4.5.5"
72
+ }
73
+ }
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -0,0 +1,33 @@
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
+ exports.startApiServer = void 0;
7
+ const fastify_1 = __importDefault(require("fastify"));
8
+ const cors_1 = __importDefault(require("@fastify/cors"));
9
+ const logger_1 = __importDefault(require("@/logger"));
10
+ const db_1 = require("@/db");
11
+ const logger = new logger_1.default("RPC");
12
+ const server = (0, fastify_1.default)({ logger: false });
13
+ server.register(cors_1.default, {});
14
+ server.get('/', async () => 'Interop X API');
15
+ const startApiServer = async () => {
16
+ const HOST = process.env.API_HOST || '0.0.0.0';
17
+ const PORT = process.env.API_PORT || '8080';
18
+ try {
19
+ server.get('/transactions', async (req) => {
20
+ return await db_1.Transaction.findAndCountAll({
21
+ limit: 20,
22
+ offset: 0,
23
+ });
24
+ });
25
+ await server.listen(PORT, HOST);
26
+ logger.log(`RPC Server listening at http://${HOST}:${PORT}`);
27
+ }
28
+ catch (err) {
29
+ logger.error(err.message);
30
+ process.exit(1);
31
+ }
32
+ };
33
+ exports.startApiServer = startApiServer;
@@ -8,6 +8,7 @@ class Config {
8
8
  this.maxPeers = 10;
9
9
  this.privateKey = process.env.PRIVATE_KEY;
10
10
  this.staging = !!process.env.STAGING && process.env.STAGING === 'true';
11
+ this.autoUpdate = !!process.env.AUTO_UPDATE && process.env.AUTO_UPDATE === 'true';
11
12
  this.wallet = new ethers_1.Wallet(this.privateKey);
12
13
  this.leadNodeAddress = '0x910E413DBF3F6276Fe8213fF656726bDc142E08E';
13
14
  }
@@ -6,23 +6,15 @@ exports.addresses = {
6
6
  gnosisSafe: '0x811Bff6eF88dAAA0aD6438386B534A81cE3F160F',
7
7
  multisend: '0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761',
8
8
  interopXGateway: '',
9
- interopBridgeTokens: [],
10
9
  },
11
10
  137: {
12
11
  gnosisSafe: '0x5635d2910e51da33d9DC0422c893CF4F28B69A25',
13
12
  multisend: '0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761',
14
13
  interopXGateway: '',
15
- interopBridgeTokens: [
16
- {
17
- address: '0x6c20F03598d5ABF729348E2868b0ff5e8A48aB1F',
18
- symbol: 'USDC',
19
- }
20
- ],
21
14
  },
22
15
  43114: {
23
16
  gnosisSafe: '0x31d7a5194Fe60AC209Cf1Ce2d539C9A60662Ed6b',
24
17
  multisend: '0x998739BFdAAdde7C933B942a68053933098f9EDa',
25
18
  interopXGateway: '0x8D27758751BA488690974B6Ccfcda771D462945f',
26
- interopBridgeTokens: [],
27
19
  }
28
20
  };
@@ -16,3 +16,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./addresses"), exports);
18
18
  __exportStar(require("./tokens"), exports);
19
+ __exportStar(require("./itokens"), exports);
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.itokens = void 0;
4
+ exports.itokens = {
5
+ 1: [],
6
+ 137: [
7
+ {
8
+ address: '0xEab02fe1F016eE3e4106c1C6aad35FeEe657268E',
9
+ symbol: 'USDC',
10
+ }
11
+ ],
12
+ 43114: []
13
+ };
File without changes
File without changes
File without changes
@@ -12,8 +12,10 @@ Transaction.init({
12
12
  autoIncrement: true,
13
13
  primaryKey: true
14
14
  },
15
+ submitTransactionHash: sequelize_2.DataTypes.NUMBER,
16
+ submitBlockNumber: sequelize_2.DataTypes.NUMBER,
15
17
  transactionHash: sequelize_2.DataTypes.STRING,
16
- type: sequelize_2.DataTypes.STRING,
18
+ action: sequelize_2.DataTypes.STRING,
17
19
  from: sequelize_2.DataTypes.STRING,
18
20
  to: sequelize_2.DataTypes.STRING,
19
21
  sourceChainId: sequelize_2.DataTypes.NUMBER,
File without changes
@@ -0,0 +1,107 @@
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 module_alias_1 = __importDefault(require("module-alias"));
7
+ module_alias_1.default.addAliases({
8
+ "@/": __dirname + "/",
9
+ "@/logger": __dirname + "/logger",
10
+ "@/tasks": __dirname + "/tasks",
11
+ "@/utils": __dirname + "/utils",
12
+ "@/api": __dirname + "/api",
13
+ "@/net": __dirname + "/net",
14
+ "@/db": __dirname + "/db",
15
+ "@/config": __dirname + "/config",
16
+ "@/types": __dirname + "/types",
17
+ "@/abi": __dirname + "/abi",
18
+ "@/constants": __dirname + "/constants",
19
+ "@/typechain": __dirname + "/typechain"
20
+ });
21
+ (0, module_alias_1.default)();
22
+ const dotenv_1 = __importDefault(require("dotenv"));
23
+ const chalk_1 = __importDefault(require("chalk"));
24
+ const ethers_1 = require("ethers");
25
+ const package_json_1 = __importDefault(require("../package.json"));
26
+ dotenv_1.default.config();
27
+ const logger_1 = __importDefault(require("@/logger"));
28
+ const logger = new logger_1.default('Process');
29
+ const printUsage = () => {
30
+ console.log('Usage:');
31
+ console.log(' PRIVATE_KEY=abcd1234 interop-x');
32
+ console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x');
33
+ console.log(' PRIVATE_KEY=abcd1234 AUTO_UPDATE=true interop-x');
34
+ console.log(' PRIVATE_KEY=abcd1234 API_HOST=0.0.0.0 API_PORT=8080 interop-x');
35
+ };
36
+ if (process.argv.at(-1) === 'help') {
37
+ printUsage();
38
+ process.exit(0);
39
+ }
40
+ const GIT_SHORT_HASH = 'fabee70';
41
+ if (process.argv.at(-1) === 'version') {
42
+ console.log(`Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
43
+ process.exit(0);
44
+ }
45
+ if (!process.env.PRIVATE_KEY) {
46
+ console.error(chalk_1.default.bgRed.white.bold('Please provide a private key\n'));
47
+ printUsage();
48
+ process.exit(1);
49
+ }
50
+ try {
51
+ new ethers_1.ethers.Wallet(process.env.PRIVATE_KEY);
52
+ }
53
+ catch (e) {
54
+ console.error(chalk_1.default.bgRed.white('Invalid private key\n'));
55
+ printUsage();
56
+ process.exit(1);
57
+ }
58
+ logger.debug(`Starting Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
59
+ const tasks_1 = require("@/tasks");
60
+ const net_1 = require("@/net");
61
+ const api_1 = require("@/api");
62
+ const db_1 = require("./db");
63
+ const utils_1 = require("./utils");
64
+ async function main() {
65
+ (0, net_1.startPeer)({});
66
+ const tasks = new tasks_1.Tasks();
67
+ tasks.start();
68
+ (0, api_1.startApiServer)();
69
+ net_1.protocol.on('TransactionStatus', async (payload) => {
70
+ if (!net_1.peerPool.isLeadNode(payload.peerId)) {
71
+ const peer = net_1.peerPool.getPeer(payload.peerId);
72
+ if (!peer) {
73
+ return;
74
+ }
75
+ logger.info(`ignored transaction status from ${payload.peerId} ${(0, utils_1.shortenHash)(peer.publicAddress)} `);
76
+ return;
77
+ }
78
+ const transaction = await db_1.Transaction.findOne({ where: { transactionHash: payload.data.transactionHash } });
79
+ if (!transaction) {
80
+ return;
81
+ }
82
+ transaction.sourceStatus = payload.data.sourceStatus;
83
+ transaction.sourceTransactionHash = payload.data.sourceTransactionHash;
84
+ transaction.sourceErrors = payload.data.sourceErrors;
85
+ transaction.targetStatus = payload.data.targetStatus;
86
+ transaction.targetTransactionHash = payload.data.targetTransactionHash;
87
+ transaction.targetErrors = payload.data.targetErrors;
88
+ transaction.status = payload.data.status;
89
+ await transaction.save();
90
+ });
91
+ }
92
+ main()
93
+ .then(() => {
94
+ }).catch(err => {
95
+ console.error(err);
96
+ });
97
+ process.on('SIGINT', () => {
98
+ logger.debug('received SIGINT signal. exiting.');
99
+ process.exit(0);
100
+ });
101
+ process.on('SIGTERM', () => {
102
+ logger.debug('received SIGTERM signal. exiting.');
103
+ process.exit(0);
104
+ });
105
+ process.on('unhandledRejection', (reason, p) => {
106
+ logger.error('unhandled rejection: promise:', p, 'reason:', reason);
107
+ });
File without changes
File without changes
@@ -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;
@@ -8,6 +8,8 @@ const BaseDialProtocol_1 = require("./BaseDialProtocol");
8
8
  const waait_1 = __importDefault(require("waait"));
9
9
  const config_1 = __importDefault(require("@/config"));
10
10
  const db_1 = require("@/db");
11
+ const utils_1 = require("@/utils");
12
+ const constants_1 = require("@/constants");
11
13
  class SignatureDialProtocol extends BaseDialProtocol_1.BaseDialProtocol {
12
14
  constructor(libp2p) {
13
15
  super(libp2p, '/interop-x/signatures');
@@ -15,31 +17,39 @@ class SignatureDialProtocol extends BaseDialProtocol_1.BaseDialProtocol {
15
17
  }
16
18
  async response(data) {
17
19
  const signer = config_1.default.wallet;
18
- let event;
20
+ let transaction;
19
21
  let maxTimeout = 20000;
20
22
  do {
21
- event = await db_1.Transaction.findOne({ where: { transactionHash: data.transactionHash } });
22
- if (!event) {
23
+ transaction = await db_1.Transaction.findOne({ where: { transactionHash: data.transactionHash } });
24
+ if (!transaction) {
23
25
  await (0, waait_1.default)(1000);
24
26
  maxTimeout -= 1000;
25
27
  }
26
- } while (!event && maxTimeout > 0);
27
- if (!event) {
28
+ } while (!transaction && maxTimeout > 0);
29
+ if (!transaction) {
28
30
  return {
29
31
  signer: signer.address,
30
32
  data: null,
31
33
  error: 'Event not found'
32
34
  };
33
35
  }
34
- // const signedData = await signGnosisSafeTx({
35
- // to: addresses[event.chainId as ChainId].multisend,
36
- // data: 'TODO',
37
- // chainId: event.chainId as ChainId,
38
- // safeTxGas: data.safeTxGas,
39
- // }, { signer });
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
+ });
43
+ const signedData = await (0, utils_1.signGnosisSafeTx)({
44
+ to: constants_1.addresses[transaction.targetChainId].multisend,
45
+ data: await (0, utils_1.buildDataForTransaction)(transaction, data.type),
46
+ chainId: transaction.targetChainId,
47
+ safeTxGas: data.safeTxGas,
48
+ nonce: data.safeNonce,
49
+ }, { signer });
40
50
  return {
41
51
  signer: signer.address,
42
- data: null, //signedData,
52
+ data: signedData
43
53
  };
44
54
  }
45
55
  }
@@ -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,57 @@
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 utils_1 = require("@/utils");
9
+ const await_spawn_1 = __importDefault(require("await-spawn"));
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
+ class AutoUpdateTask extends BaseTask_1.BaseTask {
15
+ constructor() {
16
+ super({
17
+ logger: new logger_1.default("AutoUpdateTask"),
18
+ });
19
+ this.pollIntervalMs = 60 * 5 * 1000;
20
+ }
21
+ prePollHandler() {
22
+ return config_1.default.autoUpdate && !config_1.default.isLeadNode();
23
+ }
24
+ async getInstalledVersion() {
25
+ try {
26
+ const stdout = await (0, await_spawn_1.default)('npm', ['-g', 'ls', '--depth=0', '--json']);
27
+ return JSON.parse(stdout.toString()).dependencies[package_json_1.default.name].version;
28
+ }
29
+ catch (error) {
30
+ this.logger.error(error);
31
+ return currentVersion;
32
+ }
33
+ }
34
+ async pollHandler() {
35
+ const { data } = await utils_1.http.get('https://registry.npmjs.org/@instadapp/interop-x');
36
+ const version = data['dist-tags'].latest;
37
+ if (version === currentVersion) {
38
+ return;
39
+ }
40
+ this.logger.warn(`New version ${version} available.`);
41
+ this.logger.info('Updating...');
42
+ await (0, await_spawn_1.default)('npm', ['-g', 'install', '@instadapp/interop-x', '-f']);
43
+ await (0, waait_1.default)(5000);
44
+ if (version !== await this.getInstalledVersion()) {
45
+ this.logger.warn(`failed to install ${version}, retrying in 5 minutes`);
46
+ return;
47
+ }
48
+ this.logger.warn(`Installed version ${version}`);
49
+ this.logger.warn(`Restarting...`);
50
+ (0, await_spawn_1.default)(process.argv[0], process.argv.slice(1), {
51
+ cwd: process.cwd(),
52
+ stdio: "inherit"
53
+ });
54
+ process.exit();
55
+ }
56
+ }
57
+ exports.default = AutoUpdateTask;