@instadapp/interop-x 0.0.0-dev.9b1fcb8 → 0.0.0-dev.a846f65

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 (34) hide show
  1. package/dist/package.json +5 -5
  2. package/dist/src/api/index.js +3 -3
  3. package/dist/src/config/index.js +1 -0
  4. package/dist/src/index.js +44 -5
  5. package/dist/src/net/peer/index.js +2 -1
  6. package/dist/src/net/pool/index.js +18 -2
  7. package/dist/src/net/protocol/dial/SignatureDialProtocol.1.js +28 -0
  8. package/dist/src/net/protocol/index.js +41 -1
  9. package/dist/src/tasks/AutoUpdateTask.js +67 -0
  10. package/dist/src/tasks/BaseTask.js +7 -3
  11. package/dist/src/tasks/InteropBridge/ProcessWithdrawEvents.js +146 -0
  12. package/dist/src/tasks/InteropBridge/SyncWithdrawEvents.js +2 -1
  13. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +3 -1
  14. package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +0 -1
  15. package/dist/src/tasks/Transactions/SyncTransactionStatusTask.js +53 -0
  16. package/dist/src/tasks/index.js +8 -0
  17. package/dist/src/utils/index.js +68 -8
  18. package/package.json +5 -5
  19. package/src/api/index.ts +2 -2
  20. package/src/config/index.ts +2 -0
  21. package/src/index.ts +56 -7
  22. package/src/net/peer/index.ts +2 -1
  23. package/src/net/pool/index.ts +25 -5
  24. package/src/net/protocol/dial/SignatureDialProtocol.1.ts +31 -0
  25. package/src/net/protocol/index.ts +57 -1
  26. package/src/tasks/AutoUpdateTask.ts +81 -0
  27. package/src/tasks/BaseTask.ts +8 -3
  28. package/src/tasks/InteropBridge/ProcessWithdrawEvents.ts +231 -0
  29. package/src/tasks/InteropBridge/SyncWithdrawEvents.ts +3 -3
  30. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +4 -2
  31. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +0 -2
  32. package/src/tasks/Transactions/SyncTransactionStatusTask.ts +65 -0
  33. package/src/tasks/index.ts +11 -0
  34. package/src/utils/index.ts +88 -7
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instadapp/interop-x",
3
- "version": "0.0.0-dev.9b1fcb8",
3
+ "version": "0.0.0-dev.a846f65",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "engines": {
@@ -24,9 +24,10 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@achingbrain/libp2p-gossipsub": "^0.12.2",
27
+ "@fastify/cors": "^7.0.0",
28
+ "await-spawn": "^4.0.2",
27
29
  "axios": "^0.27.1",
28
30
  "axios-retry": "^3.2.4",
29
- "bignumber.js": "^9.0.2",
30
31
  "chalk": "4.1.2",
31
32
  "dotenv": "^16.0.0",
32
33
  "ethereumjs-util": "^7.1.4",
@@ -34,7 +35,6 @@
34
35
  "ethers-multisend": "^2.1.1",
35
36
  "expand-home-dir": "^0.0.3",
36
37
  "fastify": "^3.28.0",
37
- "fastify-cors": "^6.0.3",
38
38
  "libp2p": "^0.36.2",
39
39
  "libp2p-bootstrap": "^0.14.0",
40
40
  "libp2p-kad-dht": "^0.28.6",
@@ -46,6 +46,8 @@
46
46
  "libp2p-websockets": "^0.16.2",
47
47
  "luxon": "^2.3.2",
48
48
  "module-alias": "^2.2.2",
49
+ "patch-package": "^6.4.7",
50
+ "postinstall-postinstall": "^2.1.0",
49
51
  "sequelize": "6.18.0",
50
52
  "sqlite3": "^5.0.5",
51
53
  "waait": "^1.0.5"
@@ -60,8 +62,6 @@
60
62
  "@types/fs-extra": "^9.0.13",
61
63
  "@types/node": "^17.0.17",
62
64
  "nodemon": "^2.0.15",
63
- "patch-package": "^6.4.7",
64
- "postinstall-postinstall": "^2.1.0",
65
65
  "replace-in-file": "^6.3.2",
66
66
  "rimraf": "^3.0.2",
67
67
  "ts-node": "^10.5.0",
@@ -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
  };
@@ -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
  }
package/dist/src/index.js CHANGED
@@ -19,36 +19,75 @@ module_alias_1.default.addAliases({
19
19
  "@/typechain": __dirname + "/typechain"
20
20
  });
21
21
  (0, module_alias_1.default)();
22
- const assert_1 = __importDefault(require("assert"));
23
22
  const dotenv_1 = __importDefault(require("dotenv"));
23
+ const chalk_1 = __importDefault(require("chalk"));
24
24
  const ethers_1 = require("ethers");
25
25
  const package_json_1 = __importDefault(require("../package.json"));
26
26
  dotenv_1.default.config();
27
27
  const logger_1 = __importDefault(require("@/logger"));
28
28
  const logger = new logger_1.default('Process');
29
- if (process.argv.at(-1) === 'help') {
29
+ const printUsage = () => {
30
30
  console.log('Usage:');
31
31
  console.log(' PRIVATE_KEY=abcd1234 interop-x');
32
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();
33
38
  process.exit(0);
34
39
  }
35
- (0, assert_1.default)(process.env.PRIVATE_KEY, "PRIVATE_KEY is not defined");
40
+ const GIT_SHORT_HASH = 'a846f65';
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
+ }
36
50
  try {
37
51
  new ethers_1.ethers.Wallet(process.env.PRIVATE_KEY);
38
52
  }
39
53
  catch (e) {
40
- logger.error('Invalid private key');
54
+ console.error(chalk_1.default.bgRed.white('Invalid private key\n'));
55
+ printUsage();
41
56
  process.exit(1);
42
57
  }
43
- logger.debug(`Starting Interop X Node (v${package_json_1.default.version} - rev.9b1fcb8)`);
58
+ logger.debug(`Starting Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
44
59
  const tasks_1 = require("@/tasks");
45
60
  const net_1 = require("@/net");
46
61
  const api_1 = require("@/api");
62
+ const db_1 = require("./db");
63
+ const utils_1 = require("./utils");
47
64
  async function main() {
48
65
  (0, net_1.startPeer)({});
49
66
  const tasks = new tasks_1.Tasks();
50
67
  tasks.start();
51
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
+ });
52
91
  }
53
92
  main()
54
93
  .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,7 +78,7 @@ 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
@@ -7,6 +7,9 @@ exports.peerPool = exports.PeerPool = void 0;
7
7
  const types_1 = require("@/types");
8
8
  const config_1 = __importDefault(require("@/config"));
9
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"));
10
13
  const logger = new logger_1.default('PeerPool');
11
14
  class PeerPool {
12
15
  constructor() {
@@ -70,7 +73,7 @@ class PeerPool {
70
73
  peer.pooled = true;
71
74
  if (newPeer) {
72
75
  config_1.default.events.emit(types_1.Event.POOL_PEER_ADDED, peer);
73
- logger.info(`Peer ${peer.id} with address ${peer.publicAddress} added to pool`);
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`);
74
77
  }
75
78
  }
76
79
  }
@@ -84,7 +87,7 @@ class PeerPool {
84
87
  if (this.pool.delete(peer.id)) {
85
88
  peer.pooled = false;
86
89
  config_1.default.events.emit(types_1.Event.POOL_PEER_REMOVED, peer);
87
- logger.info(`Peer ${peer.id} with address ${peer.publicAddress} removed from pool`);
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`);
88
91
  }
89
92
  }
90
93
  }
@@ -100,6 +103,19 @@ class PeerPool {
100
103
  get activePeerIds() {
101
104
  return this.activePeers.map((p) => p.id);
102
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
+ }
103
119
  cleanup() {
104
120
  // let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
105
121
  // this.peers.forEach((peerInfo) => {
@@ -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;
@@ -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,67 @@
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 config_1 = __importDefault(require("@/config"));
10
+ const waait_1 = __importDefault(require("waait"));
11
+ const package_json_1 = __importDefault(require("../../package.json"));
12
+ const currentVersion = package_json_1.default.version;
13
+ class AutoUpdateTask extends BaseTask_1.BaseTask {
14
+ constructor() {
15
+ super({
16
+ logger: new logger_1.default("AutoUpdateTask"),
17
+ });
18
+ this.pollIntervalMs = 60 * 5 * 1000;
19
+ }
20
+ prePollHandler() {
21
+ return config_1.default.autoUpdate && !config_1.default.isLeadNode();
22
+ }
23
+ async getInstalledVersion() {
24
+ try {
25
+ const stdout = await (0, await_spawn_1.default)('npm', ['-g', 'ls', '--depth=0', '--json']);
26
+ return JSON.parse(stdout.toString()).dependencies[package_json_1.default.name].version;
27
+ }
28
+ catch (error) {
29
+ this.logger.error(error);
30
+ return currentVersion;
31
+ }
32
+ }
33
+ async getLatestVersion() {
34
+ try {
35
+ const stdout = await (0, await_spawn_1.default)('npm', ['view', package_json_1.default.name, 'version']);
36
+ return stdout.toString();
37
+ }
38
+ catch (error) {
39
+ this.logger.error(error);
40
+ return currentVersion;
41
+ }
42
+ }
43
+ async pollHandler() {
44
+ const version = await this.getLatestVersion();
45
+ if (version === currentVersion) {
46
+ return;
47
+ }
48
+ this.logger.warn(`New version ${version} available.`);
49
+ this.logger.info('Updating...');
50
+ const spawner = (0, await_spawn_1.default)('npm', ['-g', 'install', '@instadapp/interop-x@latest']);
51
+ spawner.child.on('data', console.log);
52
+ await spawner;
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
+ (0, await_spawn_1.default)(process.argv[0], process.argv.slice(1), {
61
+ cwd: process.cwd(),
62
+ stdio: "inherit"
63
+ });
64
+ process.exit();
65
+ }
66
+ }
67
+ 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() {
@@ -34,10 +35,13 @@ class BaseTask extends events_1.default {
34
35
  }
35
36
  }
36
37
  prePollHandler() {
37
- if (!this.leadNodeOnly) {
38
- return true;
38
+ if (this.exceptLeadNode) {
39
+ return !config_1.default.isLeadNode();
39
40
  }
40
- return config_1.default.isLeadNode();
41
+ if (this.leadNodeOnly) {
42
+ return config_1.default.isLeadNode();
43
+ }
44
+ return true;
41
45
  }
42
46
  async pollHandler() {
43
47
  this.logger.warn('pollHandler not implemented');
@@ -0,0 +1,146 @@
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 ethers_1 = require("ethers");
9
+ const abi_1 = __importDefault(require("@/abi"));
10
+ const db_1 = require("@/db");
11
+ const utils_1 = require("@/utils");
12
+ const constants_1 = require("@/constants");
13
+ const config_1 = __importDefault(require("@/config"));
14
+ const sequelize_1 = require("sequelize");
15
+ const waait_1 = __importDefault(require("waait"));
16
+ const net_1 = require("@/net");
17
+ const generateGnosisTransaction = async (transactionData, safeContract) => {
18
+ console.log(transactionData);
19
+ let isExecuted = await safeContract.dataHashes(await safeContract.getTransactionHash(transactionData.to, transactionData.value, transactionData.data, transactionData.operation, transactionData.safeTxGas, transactionData.baseGas, transactionData.gasPrice, transactionData.gasToken, transactionData.refundReceiver, transactionData.nonce));
20
+ while (isExecuted == 1) {
21
+ transactionData.safeTxGas = ethers_1.BigNumber.from(String(transactionData.safeTxGas)).add(1).toString();
22
+ isExecuted = await safeContract.dataHashes(await safeContract.getTransactionHash(transactionData.to, transactionData.value, transactionData.data, transactionData.operation, transactionData.safeTxGas, transactionData.baseGas, transactionData.gasPrice, transactionData.gasToken, transactionData.refundReceiver, transactionData.nonce));
23
+ }
24
+ return transactionData;
25
+ };
26
+ class ProcessWithdrawEvents extends BaseTask_1.BaseTask {
27
+ constructor({ chainId }) {
28
+ super({
29
+ logger: new logger_1.default("InteropXGateway::ProcessWithdrawEvents"),
30
+ });
31
+ this.leadNodeOnly = true;
32
+ this.chainId = chainId;
33
+ }
34
+ async pollHandler() {
35
+ var _a;
36
+ const blockNumber = await this.provider.getBlockNumber();
37
+ const transaction = await db_1.Transaction.findOne({
38
+ where: {
39
+ status: 'pending',
40
+ sourceStatus: 'success',
41
+ targetStatus: 'uninitialised',
42
+ action: 'withdraw',
43
+ sourceCreatedAt: {
44
+ [sequelize_1.Op.gte]: new Date(Date.now() - 12 * 60 * 60 * 1000),
45
+ },
46
+ targetDelayUntil: {
47
+ [sequelize_1.Op.or]: {
48
+ [sequelize_1.Op.is]: null,
49
+ [sequelize_1.Op.lt]: new Date(),
50
+ }
51
+ },
52
+ sourceBlockNumber: {
53
+ [sequelize_1.Op.lt]: blockNumber - 12,
54
+ },
55
+ sourceChainId: this.chainId,
56
+ }
57
+ });
58
+ if (!transaction) {
59
+ return;
60
+ }
61
+ console.log(`Processing transaction ${transaction.transactionHash}`);
62
+ transaction.targetStatus = 'pending';
63
+ await transaction.save();
64
+ // refresh event data?
65
+ const targetChainProvider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(transaction.targetChainId));
66
+ const targetWallet = new ethers_1.ethers.Wallet(config_1.default.privateKey, targetChainProvider);
67
+ const safeAddress = constants_1.addresses[transaction.targetChainId].gnosisSafe;
68
+ const safeContract = (0, utils_1.getContract)(safeAddress, abi_1.default.gnosisSafe, targetWallet);
69
+ const ownersThreshold = await safeContract.getThreshold();
70
+ await (0, waait_1.default)(10000);
71
+ let gnosisTx = await generateGnosisTransaction({
72
+ baseGas: "0",
73
+ data: await (0, utils_1.buildDataForTransaction)(transaction),
74
+ gasPrice: "0",
75
+ gasToken: "0x0000000000000000000000000000000000000000",
76
+ nonce: '0',
77
+ operation: "1",
78
+ refundReceiver: "0x0000000000000000000000000000000000000000",
79
+ safeAddress: safeAddress,
80
+ safeTxGas: "79668",
81
+ to: constants_1.addresses[transaction.targetChainId].multisend,
82
+ value: "0",
83
+ }, safeContract);
84
+ const owners = await safeContract.getOwners().then(owners => owners.map(owner => owner.toLowerCase()));
85
+ const ownerPeerIds = net_1.peerPool.activePeers.filter(peer => owners.includes(peer.publicAddress.toLowerCase())).map(peer => peer.id);
86
+ console.log(`Collecting signatures for execution ${transaction.transactionHash}`);
87
+ console.log(ownerPeerIds);
88
+ const signatures = await net_1.protocol.requestSignatures({
89
+ type: 'source',
90
+ transactionHash: transaction.transactionHash,
91
+ safeTxGas: gnosisTx.safeTxGas,
92
+ safeNonce: gnosisTx.nonce
93
+ }, ownerPeerIds);
94
+ const validSignatures = signatures.filter(s => !!s.data && s.data !== '0x');
95
+ console.log({ signatures, validSignatures, ownersThreshold: ownersThreshold.toString() });
96
+ if (validSignatures.length === 0 || ownersThreshold.gt(validSignatures.length)) {
97
+ await transaction.save();
98
+ transaction.targetDelayUntil = new Date(Date.now() + 30 * 1000);
99
+ transaction.targetStatus = 'uninitialised';
100
+ await transaction.save();
101
+ const errorMessage = (_a = signatures.find(s => !!s.error)) === null || _a === void 0 ? void 0 : _a.error;
102
+ throw new Error(`Not enough signatures` + (errorMessage ? `: ${errorMessage}` : ''));
103
+ }
104
+ console.log(`Executing transaction for execution ${transaction.transactionHash}`);
105
+ const { data: txData } = await safeContract.populateTransaction.execTransaction(gnosisTx.to, gnosisTx.value, gnosisTx.data, gnosisTx.operation, gnosisTx.safeTxGas, gnosisTx.baseGas, gnosisTx.gasPrice, gnosisTx.gasToken, gnosisTx.refundReceiver, (0, utils_1.buildSignatureBytes)(validSignatures));
106
+ console.log({
107
+ from: targetWallet.address,
108
+ gasPrice: ethers_1.BigNumber.from(120 * 10 ** 9).toString(),
109
+ to: safeAddress,
110
+ data: txData,
111
+ });
112
+ const txSent = await targetWallet.sendTransaction({
113
+ from: targetWallet.address,
114
+ gasPrice: ethers_1.BigNumber.from(120 * 10 ** 9),
115
+ to: safeAddress,
116
+ data: txData,
117
+ });
118
+ const receipt = await txSent.wait();
119
+ const parsedLogs = [];
120
+ receipt.logs.forEach((log) => {
121
+ try {
122
+ parsedLogs.push(safeContract.interface.parseLog(log));
123
+ }
124
+ catch (e) { }
125
+ });
126
+ if (parsedLogs.find(e => e.name === 'ExecutionSuccess')) {
127
+ console.log('ExecutionSuccess');
128
+ transaction.targetStatus = 'success';
129
+ transaction.targetTransactionHash = txSent.hash;
130
+ transaction.status = 'success';
131
+ await transaction.save();
132
+ }
133
+ else {
134
+ console.log('ExecutionFailure');
135
+ transaction.targetStatus = 'failed';
136
+ transaction.targetTransactionHash = txSent.hash;
137
+ transaction.status = 'failed';
138
+ await transaction.save();
139
+ }
140
+ }
141
+ async start() {
142
+ this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
143
+ await super.start();
144
+ }
145
+ }
146
+ exports.default = ProcessWithdrawEvents;
@@ -43,10 +43,12 @@ class SyncWithdrawEvents extends BaseTask_1.BaseTask {
43
43
  sourceTransactionHash: event.transactionHash, sourceBlockNumber: event.blockNumber, sourceStatus: "success", targetStatus: "uninitialised", submitEvent: {
44
44
  to,
45
45
  amount: amount.toString(),
46
+ itoken: this.itokenAddress,
46
47
  chainId: chainId.toString()
47
48
  }, sourceEvent: {
48
49
  to,
49
50
  amount: amount.toString(),
51
+ itoken: this.itokenAddress,
50
52
  chainId: chainId.toString(),
51
53
  }, status: "pending" }));
52
54
  this.logger.info(`Withdraw queued: ${event.transactionHash} ${event.blockNumber}`);
@@ -59,7 +61,6 @@ class SyncWithdrawEvents extends BaseTask_1.BaseTask {
59
61
  this.logger.info(`${processedEvents} events processed`);
60
62
  }
61
63
  async start() {
62
- this.logger.info(`Starting execution watcher on interop chain`);
63
64
  this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
64
65
  this.contract = (0, utils_1.getContract)(this.itokenAddress, abi_1.default.interopBridgeToken, new ethers_1.ethers.Wallet(config_1.default.privateKey, this.provider));
65
66
  await super.start();
@@ -126,18 +126,20 @@ class ProcessDepositEvents extends BaseTask_1.BaseTask {
126
126
  if (parsedLogs.find(e => e.name === 'ExecutionSuccess')) {
127
127
  console.log('ExecutionSuccess');
128
128
  transaction.targetStatus = 'success';
129
+ transaction.targetTransactionHash = txSent.hash;
129
130
  transaction.status = 'success';
130
131
  await transaction.save();
131
132
  }
132
133
  else {
133
134
  console.log('ExecutionFailure');
134
135
  transaction.targetStatus = 'failed';
136
+ transaction.targetTransactionHash = txSent.hash;
135
137
  transaction.status = 'failed';
136
138
  await transaction.save();
137
139
  }
140
+ net_1.protocol.sendTransaction(transaction);
138
141
  }
139
142
  async start() {
140
- this.logger.info(`Starting execution watcher on interop chain`);
141
143
  this.contractAddress = constants_1.addresses[this.chainId].interopXGateway;
142
144
  this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
143
145
  this.contract = (0, utils_1.getContract)(this.contractAddress, abi_1.default.interopXGateway, new ethers_1.ethers.Wallet(config_1.default.privateKey, this.provider));
@@ -65,7 +65,6 @@ class SyncDepositEvents extends BaseTask_1.BaseTask {
65
65
  this.logger.info(`${processedEvents} events processed`);
66
66
  }
67
67
  async start() {
68
- this.logger.info(`Starting execution watcher on interop chain`);
69
68
  this.contractAddress = constants_1.addresses[this.chainId].interopXGateway;
70
69
  this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
71
70
  this.contract = (0, utils_1.getContract)(this.contractAddress, abi_1.default.interopXGateway, new ethers_1.ethers.Wallet(config_1.default.privateKey, this.provider));