@instadapp/interop-x 0.0.0-dev.ef78459 → 0.0.0-dev.f0a6281

Sign up to get free protection for your applications and to get access to all the features.
Files changed (98) hide show
  1. package/.env.example +2 -1
  2. package/bin/interop-x +1 -1
  3. package/dist/package.json +73 -0
  4. package/dist/src/abi/erc20.json +350 -0
  5. package/dist/src/abi/gnosisSafe.json +747 -0
  6. package/dist/src/abi/index.js +15 -0
  7. package/dist/src/abi/interopBridgeToken.json +298 -0
  8. package/dist/src/abi/interopXGateway.json +184 -0
  9. package/dist/src/api/index.js +33 -0
  10. package/dist/src/config/index.js +31 -0
  11. package/dist/src/constants/addresses.js +20 -0
  12. package/dist/{constants → src/constants}/index.js +2 -0
  13. package/dist/src/constants/itokens.js +13 -0
  14. package/dist/src/constants/tokens.js +107 -0
  15. package/dist/{db → src/db}/index.js +0 -0
  16. package/dist/{db → src/db}/models/index.js +1 -1
  17. package/dist/src/db/models/transaction.js +54 -0
  18. package/dist/{db → src/db}/sequelize.js +2 -1
  19. package/dist/src/index.js +130 -0
  20. package/dist/{logger → src/logger}/index.js +0 -0
  21. package/dist/{net → src/net}/index.js +0 -0
  22. package/dist/{net → src/net}/peer/index.js +8 -3
  23. package/dist/{net → src/net}/pool/index.js +32 -9
  24. package/dist/{net → src/net}/protocol/dial/BaseDialProtocol.js +0 -0
  25. package/dist/{net → src/net}/protocol/dial/SignatureDialProtocol.js +20 -12
  26. package/dist/src/net/protocol/dial/TransactionStatusDialProtocol.js +28 -0
  27. package/dist/{net → src/net}/protocol/index.js +44 -4
  28. package/dist/src/tasks/AutoUpdateTask.js +70 -0
  29. package/dist/{tasks → src/tasks}/BaseTask.js +13 -5
  30. package/dist/src/tasks/InteropBridge/ProcessWithdrawEvents.js +146 -0
  31. package/dist/src/tasks/InteropBridge/SyncWithdrawEvents.js +71 -0
  32. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +161 -0
  33. package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +74 -0
  34. package/dist/src/tasks/Transactions/SyncTransactionStatusTask.js +53 -0
  35. package/dist/src/tasks/index.js +44 -0
  36. package/dist/src/typechain/Erc20.js +2 -0
  37. package/dist/src/typechain/GnosisSafe.js +2 -0
  38. package/dist/src/typechain/InteropBridgeToken.js +2 -0
  39. package/dist/src/typechain/InteropXGateway.js +2 -0
  40. package/dist/src/typechain/common.js +2 -0
  41. package/dist/src/typechain/factories/Erc20__factory.js +367 -0
  42. package/dist/src/typechain/factories/GnosisSafe__factory.js +1174 -0
  43. package/dist/src/typechain/factories/InteropBridgeToken__factory.js +471 -0
  44. package/dist/src/typechain/factories/InteropXGateway__factory.js +265 -0
  45. package/dist/src/typechain/factories/index.js +14 -0
  46. package/dist/src/typechain/index.js +35 -0
  47. package/dist/{types.js → src/types.js} +0 -0
  48. package/dist/src/utils/index.js +238 -0
  49. package/package.json +18 -10
  50. package/patches/@ethersproject+properties+5.6.0.patch +13 -0
  51. package/src/abi/erc20.json +350 -0
  52. package/src/abi/gnosisSafe.json +747 -0
  53. package/src/abi/index.ts +11 -0
  54. package/src/abi/interopBridgeToken.json +298 -0
  55. package/src/abi/interopXGateway.json +184 -0
  56. package/src/api/index.ts +33 -0
  57. package/src/config/index.ts +17 -1
  58. package/src/constants/addresses.ts +9 -2
  59. package/src/constants/index.ts +2 -0
  60. package/src/constants/itokens.ts +10 -0
  61. package/src/constants/tokens.ts +104 -0
  62. package/src/db/models/index.ts +1 -1
  63. package/src/db/models/transaction.ts +96 -0
  64. package/src/db/sequelize.ts +2 -1
  65. package/src/index.ts +119 -7
  66. package/src/net/peer/index.ts +9 -7
  67. package/src/net/pool/index.ts +41 -11
  68. package/src/net/protocol/dial/SignatureDialProtocol.ts +24 -15
  69. package/src/net/protocol/dial/TransactionStatusDialProtocol.ts +31 -0
  70. package/src/net/protocol/index.ts +60 -4
  71. package/src/tasks/AutoUpdateTask.ts +82 -0
  72. package/src/tasks/BaseTask.ts +15 -6
  73. package/src/tasks/InteropBridge/ProcessWithdrawEvents.ts +231 -0
  74. package/src/tasks/InteropBridge/SyncWithdrawEvents.ts +121 -0
  75. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +256 -0
  76. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +124 -0
  77. package/src/tasks/Transactions/SyncTransactionStatusTask.ts +65 -0
  78. package/src/tasks/index.ts +26 -1
  79. package/src/typechain/Erc20.ts +491 -0
  80. package/src/typechain/GnosisSafe.ts +1728 -0
  81. package/src/typechain/InteropBridgeToken.ts +692 -0
  82. package/src/typechain/InteropXGateway.ts +407 -0
  83. package/src/typechain/common.ts +44 -0
  84. package/src/typechain/factories/Erc20__factory.ts +368 -0
  85. package/src/typechain/factories/GnosisSafe__factory.ts +1178 -0
  86. package/src/typechain/factories/InteropBridgeToken__factory.ts +478 -0
  87. package/src/typechain/factories/InteropXGateway__factory.ts +272 -0
  88. package/src/typechain/factories/index.ts +7 -0
  89. package/src/typechain/index.ts +12 -0
  90. package/src/types.ts +1 -1
  91. package/src/utils/index.ts +206 -3
  92. package/dist/config/index.js +0 -17
  93. package/dist/constants/addresses.js +0 -13
  94. package/dist/db/models/execution.js +0 -38
  95. package/dist/index.js +0 -43
  96. package/dist/tasks/index.js +0 -19
  97. package/dist/utils/index.js +0 -89
  98. package/src/db/models/execution.ts +0 -57
@@ -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;
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.BaseTask = void 0;
7
- const config_1 = __importDefault(require("config"));
7
+ const config_1 = __importDefault(require("@/config"));
8
8
  const events_1 = __importDefault(require("events"));
9
9
  const waait_1 = __importDefault(require("waait"));
10
10
  const logger_1 = __importDefault(require("@/logger"));
@@ -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');
@@ -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;
@@ -0,0 +1,71 @@
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 config_1 = __importDefault(require("@/config"));
13
+ class SyncWithdrawEvents extends BaseTask_1.BaseTask {
14
+ constructor({ chainId, itokenAddress }) {
15
+ super({
16
+ logger: new logger_1.default("InteropBridgeToken::SyncWithdrawEvents"),
17
+ });
18
+ this.chainId = chainId;
19
+ this.itokenAddress = itokenAddress;
20
+ }
21
+ async pollHandler() {
22
+ const currentBlock = await this.provider.getBlockNumber();
23
+ const events = await this.contract.queryFilter(this.contract.filters.Burn(), currentBlock - 2000, currentBlock);
24
+ let processedEvents = 0;
25
+ for (const event of events) {
26
+ try {
27
+ if (!event.args) {
28
+ continue;
29
+ }
30
+ const { to, amount, sourceChainId, targetChainId } = event.args;
31
+ const uniqueIdentifier = {
32
+ action: 'withdraw',
33
+ submitTransactionHash: event.transactionHash,
34
+ sourceChainId: sourceChainId,
35
+ targetChainId: targetChainId,
36
+ };
37
+ if (await db_1.Transaction.findOne({ where: uniqueIdentifier })) {
38
+ continue;
39
+ }
40
+ const tx = await event.getTransaction();
41
+ await db_1.Transaction.create(Object.assign(Object.assign({}, uniqueIdentifier), { transactionHash: (0, utils_1.generateInteropTransactionHash)(uniqueIdentifier), from: tx.from, to, submitTransactionHash: event.transactionHash, submitBlockNumber: event.blockNumber,
42
+ // submit & source are the same
43
+ sourceTransactionHash: event.transactionHash, sourceBlockNumber: event.blockNumber, sourceStatus: "success", targetStatus: "uninitialised", submitEvent: {
44
+ to,
45
+ amount: amount.toString(),
46
+ itoken: this.itokenAddress,
47
+ sourceChainId: sourceChainId,
48
+ targetChainId: targetChainId,
49
+ }, sourceEvent: {
50
+ to,
51
+ amount: amount.toString(),
52
+ itoken: this.itokenAddress,
53
+ sourceChainId: sourceChainId,
54
+ targetChainId: targetChainId,
55
+ }, status: "pending" }));
56
+ this.logger.info(`Withdraw queued: ${event.transactionHash} ${event.blockNumber}`);
57
+ }
58
+ catch (error) {
59
+ this.logger.error(error);
60
+ }
61
+ }
62
+ if (processedEvents > 0)
63
+ this.logger.info(`${processedEvents} events processed`);
64
+ }
65
+ async start() {
66
+ this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
67
+ this.contract = (0, utils_1.getContract)(this.itokenAddress, abi_1.default.interopBridgeToken, new ethers_1.ethers.Wallet(config_1.default.privateKey, this.provider));
68
+ await super.start();
69
+ }
70
+ }
71
+ exports.default = SyncWithdrawEvents;
@@ -0,0 +1,161 @@
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 ProcessDepositEvents extends BaseTask_1.BaseTask {
27
+ constructor({ chainId }) {
28
+ super({
29
+ logger: new logger_1.default("InteropXGateway::ProcessDepositEvents"),
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: 'deposit',
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 data;
72
+ try {
73
+ data = await (0, utils_1.buildDataForTransaction)(transaction);
74
+ }
75
+ catch (error) {
76
+ console.log(error);
77
+ transaction.targetStatus = 'failed';
78
+ transaction.targetErrors = [error.message];
79
+ await transaction.save();
80
+ net_1.protocol.sendTransaction(transaction);
81
+ return;
82
+ }
83
+ let gnosisTx = await generateGnosisTransaction({
84
+ baseGas: "0",
85
+ data,
86
+ gasPrice: "0",
87
+ gasToken: "0x0000000000000000000000000000000000000000",
88
+ nonce: '0',
89
+ operation: "1",
90
+ refundReceiver: "0x0000000000000000000000000000000000000000",
91
+ safeAddress: safeAddress,
92
+ safeTxGas: "79668",
93
+ to: constants_1.addresses[transaction.targetChainId].multisend,
94
+ value: "0",
95
+ }, safeContract);
96
+ const owners = await safeContract.getOwners().then(owners => owners.map(owner => owner.toLowerCase()));
97
+ const ownerPeerIds = net_1.peerPool.activePeers.filter(peer => owners.includes(peer.publicAddress.toLowerCase())).map(peer => peer.id);
98
+ console.log(`Collecting signatures for execution ${transaction.transactionHash}`);
99
+ console.log(ownerPeerIds);
100
+ const signatures = await net_1.protocol.requestSignatures({
101
+ type: 'source',
102
+ transactionHash: transaction.transactionHash,
103
+ safeTxGas: gnosisTx.safeTxGas,
104
+ safeNonce: gnosisTx.nonce
105
+ }, ownerPeerIds);
106
+ const validSignatures = signatures.filter(s => !!s.data && s.data !== '0x');
107
+ console.log({ signatures, validSignatures, ownersThreshold: ownersThreshold.toString() });
108
+ if (validSignatures.length === 0 || ownersThreshold.gt(validSignatures.length)) {
109
+ await transaction.save();
110
+ transaction.targetDelayUntil = new Date(Date.now() + 30 * 1000);
111
+ transaction.targetStatus = 'uninitialised';
112
+ await transaction.save();
113
+ const errorMessage = (_a = signatures.find(s => !!s.error)) === null || _a === void 0 ? void 0 : _a.error;
114
+ throw new Error(`Not enough signatures` + (errorMessage ? `: ${errorMessage}` : ''));
115
+ }
116
+ console.log(`Executing transaction for execution ${transaction.transactionHash}`);
117
+ 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));
118
+ console.log({
119
+ from: targetWallet.address,
120
+ gasPrice: ethers_1.BigNumber.from(120 * 10 ** 9).toString(),
121
+ to: safeAddress,
122
+ data: txData,
123
+ });
124
+ const txSent = await targetWallet.sendTransaction({
125
+ from: targetWallet.address,
126
+ gasPrice: ethers_1.BigNumber.from(120 * 10 ** 9),
127
+ to: safeAddress,
128
+ data: txData,
129
+ });
130
+ const receipt = await txSent.wait();
131
+ const parsedLogs = [];
132
+ receipt.logs.forEach((log) => {
133
+ try {
134
+ parsedLogs.push(safeContract.interface.parseLog(log));
135
+ }
136
+ catch (e) { }
137
+ });
138
+ if (parsedLogs.find(e => e.name === 'ExecutionSuccess')) {
139
+ console.log('ExecutionSuccess');
140
+ transaction.targetStatus = 'success';
141
+ transaction.targetTransactionHash = txSent.hash;
142
+ transaction.status = 'success';
143
+ await transaction.save();
144
+ }
145
+ else {
146
+ console.log('ExecutionFailure');
147
+ transaction.targetStatus = 'failed';
148
+ transaction.targetTransactionHash = txSent.hash;
149
+ transaction.status = 'failed';
150
+ await transaction.save();
151
+ }
152
+ net_1.protocol.sendTransaction(transaction);
153
+ }
154
+ async start() {
155
+ this.contractAddress = constants_1.addresses[this.chainId].interopXGateway;
156
+ this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
157
+ this.contract = (0, utils_1.getContract)(this.contractAddress, abi_1.default.interopXGateway, new ethers_1.ethers.Wallet(config_1.default.privateKey, this.provider));
158
+ await super.start();
159
+ }
160
+ }
161
+ exports.default = ProcessDepositEvents;
@@ -0,0 +1,74 @@
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
+ class SyncDepositEvents extends BaseTask_1.BaseTask {
15
+ constructor({ chainId }) {
16
+ super({
17
+ logger: new logger_1.default("InteropXGateway::SyncDepositEvents"),
18
+ });
19
+ this.chainId = chainId;
20
+ }
21
+ async pollHandler() {
22
+ const currentBlock = await this.provider.getBlockNumber();
23
+ const events = await this.contract.queryFilter(this.contract.filters.LogGatewayDeposit(), currentBlock - 2000, currentBlock);
24
+ let processedEvents = 0;
25
+ for (const event of events) {
26
+ try {
27
+ if (!event.args) {
28
+ continue;
29
+ }
30
+ const { sourceChainId, targetChainId, user, vnonce, amount, token } = event.args;
31
+ const uniqueIdentifier = {
32
+ action: 'deposit',
33
+ submitTransactionHash: event.transactionHash,
34
+ sourceChainId: sourceChainId,
35
+ targetChainId: targetChainId,
36
+ };
37
+ if (await db_1.Transaction.findOne({ where: uniqueIdentifier })) {
38
+ continue;
39
+ }
40
+ const tx = await event.getTransaction();
41
+ await db_1.Transaction.create(Object.assign(Object.assign({}, uniqueIdentifier), { transactionHash: (0, utils_1.generateInteropTransactionHash)(uniqueIdentifier), from: tx.from, to: user, submitTransactionHash: event.transactionHash, submitBlockNumber: event.blockNumber,
42
+ // submit & source are the same
43
+ sourceTransactionHash: event.transactionHash, sourceBlockNumber: event.blockNumber, sourceStatus: "success", targetStatus: "uninitialised", submitEvent: {
44
+ user,
45
+ sourceChainId: sourceChainId.toString(),
46
+ targetChainId: targetChainId.toString(),
47
+ token: token,
48
+ amount: amount.toString(),
49
+ vnonce: vnonce.toString(),
50
+ }, sourceEvent: {
51
+ user,
52
+ sourceChainId: sourceChainId.toString(),
53
+ targetChainId: targetChainId.toString(),
54
+ token: token,
55
+ amount: amount.toString(),
56
+ vnonce: vnonce.toString(),
57
+ }, status: "pending" }));
58
+ this.logger.info(`Deposit queued: ${event.transactionHash} ${event.blockNumber}`);
59
+ }
60
+ catch (error) {
61
+ this.logger.error(error);
62
+ }
63
+ }
64
+ if (processedEvents > 0)
65
+ this.logger.info(`${processedEvents} events processed`);
66
+ }
67
+ async start() {
68
+ this.contractAddress = constants_1.addresses[this.chainId].interopXGateway;
69
+ this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
70
+ this.contract = (0, utils_1.getContract)(this.contractAddress, abi_1.default.interopXGateway, new ethers_1.ethers.Wallet(config_1.default.privateKey, this.provider));
71
+ await super.start();
72
+ }
73
+ }
74
+ exports.default = SyncDepositEvents;
@@ -0,0 +1,53 @@
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 net_1 = require("@/net");
9
+ const db_1 = require("@/db");
10
+ const sequelize_1 = require("sequelize");
11
+ class SyncTransactionStatusTask extends BaseTask_1.BaseTask {
12
+ constructor() {
13
+ super({
14
+ logger: new logger_1.default("SyncTransactionStatusTask"),
15
+ });
16
+ this.pollIntervalMs = 60 * 1000;
17
+ this.exceptLeadNode = true;
18
+ }
19
+ async pollHandler() {
20
+ // if transaction is pending for more than 1 hour, check lead node for status
21
+ const leadNode = net_1.peerPool.getLeadPeer();
22
+ if (!leadNode) {
23
+ return;
24
+ }
25
+ const transaction = await db_1.Transaction.findOne({
26
+ where: {
27
+ status: 'pending',
28
+ sourceCreatedAt: {
29
+ [sequelize_1.Op.gte]: new Date(Date.now() - 60 * 60 * 1000),
30
+ },
31
+ }
32
+ });
33
+ if (!transaction) {
34
+ return;
35
+ }
36
+ this.logger.info(`Requesting transaction status for ${transaction.transactionHash}`);
37
+ const transactionStatus = await net_1.protocol.requestTransactionStatus(transaction.transactionHash, leadNode.id);
38
+ if (!transactionStatus) {
39
+ return;
40
+ }
41
+ this.logger.info(`Received transaction status for ${transaction.transactionHash}`);
42
+ transaction.sourceStatus = transactionStatus.sourceStatus;
43
+ transaction.sourceTransactionHash = transactionStatus.sourceTransactionHash;
44
+ transaction.sourceErrors = transactionStatus.sourceErrors;
45
+ transaction.targetStatus = transactionStatus.targetStatus;
46
+ transaction.targetTransactionHash = transactionStatus.targetTransactionHash;
47
+ transaction.targetErrors = transactionStatus.targetErrors;
48
+ transaction.status = transactionStatus.status;
49
+ await transaction.save();
50
+ this.logger.info(`Updated transaction status for ${transaction.transactionHash}`);
51
+ }
52
+ }
53
+ exports.default = SyncTransactionStatusTask;
@@ -0,0 +1,44 @@
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.Tasks = void 0;
7
+ const ProcessDepositEvents_1 = __importDefault(require("./InteropXGateway/ProcessDepositEvents"));
8
+ const SyncDepositEvents_1 = __importDefault(require("./InteropXGateway/SyncDepositEvents"));
9
+ const SyncWithdrawEvents_1 = __importDefault(require("./InteropBridge/SyncWithdrawEvents"));
10
+ const ProcessWithdrawEvents_1 = __importDefault(require("./InteropBridge/ProcessWithdrawEvents"));
11
+ const AutoUpdateTask_1 = __importDefault(require("./AutoUpdateTask"));
12
+ const SyncTransactionStatusTask_1 = __importDefault(require("./Transactions/SyncTransactionStatusTask"));
13
+ class Tasks {
14
+ constructor() {
15
+ this.tasks = [
16
+ new SyncTransactionStatusTask_1.default(),
17
+ new AutoUpdateTask_1.default(),
18
+ new SyncDepositEvents_1.default({
19
+ chainId: 43114
20
+ }),
21
+ new ProcessDepositEvents_1.default({
22
+ chainId: 43114
23
+ }),
24
+ new SyncWithdrawEvents_1.default({
25
+ chainId: 137,
26
+ itokenAddress: '0xEab02fe1F016eE3e4106c1C6aad35FeEe657268E',
27
+ }),
28
+ new ProcessWithdrawEvents_1.default({
29
+ chainId: 137,
30
+ })
31
+ ];
32
+ }
33
+ async start() {
34
+ for (const task of this.tasks) {
35
+ try {
36
+ task.start();
37
+ }
38
+ catch (error) {
39
+ console.error(`Error starting task: ${task.constructor.name}`);
40
+ }
41
+ }
42
+ }
43
+ }
44
+ exports.Tasks = Tasks;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });