@instadapp/interop-x 0.0.0-dev.73da8c9 → 0.0.0-dev.73e5298

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 (82) hide show
  1. package/dist/package.json +18 -16
  2. package/dist/src/abi/index.js +2 -4
  3. package/dist/src/abi/interopXContract.json +454 -0
  4. package/dist/src/alias.js +10 -0
  5. package/dist/src/api/index.js +6 -3
  6. package/dist/src/config/index.js +11 -1
  7. package/dist/src/constants/addresses.js +7 -7
  8. package/dist/src/constants/index.js +0 -1
  9. package/dist/src/constants/tokens.js +62 -39
  10. package/dist/src/db/models/transaction.js +27 -11
  11. package/dist/src/gnosis/actions/index.js +9 -0
  12. package/dist/src/gnosis/actions/withdraw/index.js +115 -0
  13. package/dist/src/gnosis/index.js +20 -0
  14. package/dist/src/index.js +75 -24
  15. package/dist/src/net/peer/index.js +2 -1
  16. package/dist/src/net/pool/index.js +18 -2
  17. package/dist/src/net/protocol/dial/SignatureDialProtocol.js +8 -2
  18. package/dist/src/net/protocol/dial/TransactionStatusDialProtocol.js +30 -0
  19. package/dist/src/net/protocol/index.js +51 -1
  20. package/dist/src/tasks/AutoUpdateTask.js +70 -0
  21. package/dist/src/tasks/BaseTask.js +11 -3
  22. package/dist/src/tasks/InteropXContract/ProcessBridgeRequestEvents.js +158 -0
  23. package/dist/src/tasks/InteropXContract/SyncBridgeCommittedEvents.js +93 -0
  24. package/dist/src/tasks/InteropXContract/SyncBridgeRequestEvents.js +78 -0
  25. package/dist/src/tasks/InteropXContract/SyncBridgeRequestSentEvents.js +90 -0
  26. package/dist/src/tasks/Transactions/SyncTransactionStatusTask.js +57 -0
  27. package/dist/src/tasks/index.js +18 -8
  28. package/dist/src/typechain/{InteropBridgeToken.js → InteropXContract.js} +0 -0
  29. package/dist/src/typechain/factories/InteropXContract__factory.js +635 -0
  30. package/dist/src/typechain/factories/index.js +3 -5
  31. package/dist/src/typechain/index.js +3 -5
  32. package/dist/src/utils/index.js +62 -47
  33. package/package.json +18 -16
  34. package/src/abi/index.ts +2 -4
  35. package/src/abi/interopXContract.json +454 -0
  36. package/src/alias.ts +6 -0
  37. package/src/api/index.ts +5 -2
  38. package/src/config/index.ts +11 -1
  39. package/src/constants/addresses.ts +8 -8
  40. package/src/constants/index.ts +0 -1
  41. package/src/constants/tokens.ts +63 -40
  42. package/src/db/models/transaction.ts +76 -27
  43. package/src/gnosis/actions/index.ts +5 -0
  44. package/src/gnosis/actions/withdraw/index.ts +155 -0
  45. package/src/gnosis/index.ts +19 -0
  46. package/src/index.ts +96 -26
  47. package/src/net/peer/index.ts +2 -1
  48. package/src/net/pool/index.ts +25 -5
  49. package/src/net/protocol/dial/SignatureDialProtocol.ts +10 -4
  50. package/src/net/protocol/dial/TransactionStatusDialProtocol.ts +33 -0
  51. package/src/net/protocol/index.ts +67 -1
  52. package/src/tasks/AutoUpdateTask.ts +82 -0
  53. package/src/tasks/BaseTask.ts +13 -3
  54. package/src/tasks/InteropXContract/ProcessBridgeRequestEvents.ts +226 -0
  55. package/src/tasks/InteropXContract/SyncBridgeCommittedEvents.ts +125 -0
  56. package/src/tasks/InteropXContract/SyncBridgeRequestEvents.ts +115 -0
  57. package/src/tasks/InteropXContract/SyncBridgeRequestSentEvents.ts +121 -0
  58. package/src/tasks/Transactions/SyncTransactionStatusTask.ts +69 -0
  59. package/src/tasks/index.ts +27 -9
  60. package/src/typechain/InteropXContract.ts +680 -0
  61. package/src/typechain/factories/InteropXContract__factory.ts +642 -0
  62. package/src/typechain/factories/index.ts +1 -2
  63. package/src/typechain/index.ts +2 -4
  64. package/src/utils/index.ts +103 -66
  65. package/tsconfig.json +7 -2
  66. package/dist/src/abi/interopBridgeToken.json +0 -286
  67. package/dist/src/abi/interopXGateway.json +0 -184
  68. package/dist/src/constants/itokens.js +0 -13
  69. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +0 -158
  70. package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +0 -75
  71. package/dist/src/typechain/InteropXGateway.js +0 -2
  72. package/dist/src/typechain/factories/InteropBridgeToken__factory.js +0 -459
  73. package/dist/src/typechain/factories/InteropXGateway__factory.js +0 -265
  74. package/src/abi/interopBridgeToken.json +0 -286
  75. package/src/abi/interopXGateway.json +0 -184
  76. package/src/constants/itokens.ts +0 -10
  77. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +0 -253
  78. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +0 -126
  79. package/src/typechain/InteropBridgeToken.ts +0 -686
  80. package/src/typechain/InteropXGateway.ts +0 -407
  81. package/src/typechain/factories/InteropBridgeToken__factory.ts +0 -466
  82. package/src/typechain/factories/InteropXGateway__factory.ts +0 -272
@@ -2,102 +2,125 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.tokens = void 0;
4
4
  exports.tokens = {
5
- 1: [
6
- {
7
- symbol: "ETH",
8
- name: "Ethereum",
9
- address: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
10
- decimals: 18,
11
- },
12
- {
13
- symbol: "DAI",
14
- name: "DAI Stable",
15
- address: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
16
- decimals: 18,
17
- },
18
- {
19
- symbol: "USDC",
20
- name: "USD Coin",
21
- address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
22
- decimals: 6,
23
- },
24
- {
25
- symbol: "USDT",
26
- name: "Tether USD Coin",
27
- address: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
28
- decimals: 6,
29
- },
30
- {
31
- symbol: "WBTC",
32
- name: "Wrapped BTC",
33
- address: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",
34
- decimals: 8,
35
- },
36
- ],
5
+ // 1: [
6
+ // {
7
+ // aliases: ['eth'],
8
+ // symbol: "ETH",
9
+ // name: "Ethereum",
10
+ // address: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
11
+ // decimals: 18,
12
+ // },
13
+ // {
14
+ // aliases: ['weth'],
15
+ // symbol: "WETH",
16
+ // name: "Wrapped Ethereum",
17
+ // address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
18
+ // decimals: 18,
19
+ // },
20
+ // {
21
+ // aliases: ['dai'],
22
+ // symbol: "DAI",
23
+ // name: "DAI Stable",
24
+ // address: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
25
+ // decimals: 18,
26
+ // },
27
+ // {
28
+ // aliases: ['usdc'],
29
+ // symbol: "USDC",
30
+ // name: "USD Coin",
31
+ // address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
32
+ // decimals: 6,
33
+ // },
34
+ // {
35
+ // aliases: ['usdt'],
36
+ // symbol: "USDT",
37
+ // name: "Tether USD Coin",
38
+ // address: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
39
+ // decimals: 6,
40
+ // },
41
+ // {
42
+ // aliases: ['wbtc'],
43
+ // symbol: "WBTC",
44
+ // name: "Wrapped BTC",
45
+ // address: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",
46
+ // decimals: 8,
47
+ // },
48
+ // ],
37
49
  137: [
38
50
  {
51
+ aliases: ['eth', 'weth'],
39
52
  symbol: "ETH",
40
53
  name: "Ethereum",
41
54
  address: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
42
55
  decimals: 18,
43
56
  },
44
57
  {
58
+ aliases: ['dai'],
45
59
  symbol: "DAI",
46
60
  name: "DAI Stable",
47
61
  address: "0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063",
48
62
  decimals: 18,
49
63
  },
50
64
  {
65
+ aliases: ['usdc'],
51
66
  symbol: "USDC",
52
67
  name: "USD Coin",
53
68
  address: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
54
69
  decimals: 6,
55
70
  },
56
71
  {
72
+ aliases: ['usdt'],
57
73
  symbol: "USDT",
58
74
  name: "Tether USD Coin",
59
75
  address: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F",
60
76
  decimals: 6,
61
77
  },
62
78
  {
79
+ aliases: ['wbtc'],
63
80
  symbol: "WBTC",
64
81
  name: "Wrapped BTC",
65
82
  address: "0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6",
66
83
  decimals: 8,
67
84
  },
68
- {
69
- symbol: "AVAX",
70
- name: "Avalanche Token",
71
- address: "0x2C89bbc92BD86F8075d1DEcc58C7F4E0107f286b",
72
- decimals: 18,
73
- },
74
85
  ],
75
86
  43114: [
76
87
  {
88
+ aliases: ['eth', 'weth'],
77
89
  symbol: "ETH",
78
90
  name: "Ethereum",
79
91
  address: "0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB",
80
92
  decimals: 18,
81
93
  },
82
94
  {
95
+ aliases: ['dai'],
83
96
  symbol: "DAI",
84
97
  name: "DAI Stable",
85
98
  address: "0xd586E7F844cEa2F87f50152665BCbc2C279D8d70",
86
99
  decimals: 18,
87
100
  },
88
101
  {
102
+ aliases: ['usdc'],
89
103
  symbol: "USDC",
90
104
  name: "USD Coin",
91
105
  address: "0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664",
92
106
  decimals: 6,
93
107
  },
94
108
  {
95
- symbol: "USDT",
109
+ aliases: ['usdt'],
110
+ symbol: "USDt",
96
111
  name: "Tether USD Coin",
112
+ address: "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",
113
+ decimals: 6,
114
+ },
115
+ {
116
+ aliases: ['usdt'],
117
+ symbol: "USDT.e",
118
+ name: "Tether USD",
97
119
  address: "0xc7198437980c041c805A1EDcbA50c1Ce5db95118",
98
120
  decimals: 6,
99
121
  },
100
122
  {
123
+ aliases: ["wbtc"],
101
124
  symbol: "WBTC",
102
125
  name: "Wrapped BTC",
103
126
  address: "0x50b7545627a5162F82A992c33b87aDc75187B218",
@@ -12,20 +12,26 @@ 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
+ requestTransactionHash: sequelize_2.DataTypes.NUMBER,
16
+ requestBlockNumber: sequelize_2.DataTypes.NUMBER,
17
17
  transactionHash: sequelize_2.DataTypes.STRING,
18
- action: sequelize_2.DataTypes.STRING,
19
- from: sequelize_2.DataTypes.STRING,
20
- to: sequelize_2.DataTypes.STRING,
18
+ actionId: sequelize_2.DataTypes.STRING,
19
+ bridger: sequelize_2.DataTypes.STRING,
21
20
  sourceChainId: sequelize_2.DataTypes.NUMBER,
22
21
  sourceTransactionHash: sequelize_2.DataTypes.STRING,
23
22
  sourceBlockNumber: sequelize_2.DataTypes.NUMBER,
24
- sourceStatus: sequelize_2.DataTypes.STRING,
23
+ sourceStatus: {
24
+ type: sequelize_2.DataTypes.STRING,
25
+ defaultValue: 'uninitialised'
26
+ },
25
27
  sourceErrors: {
26
28
  type: sequelize_2.DataTypes.JSON,
27
29
  // defaultValue: [],
28
30
  },
31
+ sourceLogs: {
32
+ type: sequelize_2.DataTypes.JSON,
33
+ // defaultValue: [],
34
+ },
29
35
  sourceCreatedAt: {
30
36
  type: sequelize_2.DataTypes.DATE,
31
37
  defaultValue: Date.now()
@@ -34,17 +40,27 @@ Transaction.init({
34
40
  targetChainId: sequelize_2.DataTypes.NUMBER,
35
41
  targetTransactionHash: sequelize_2.DataTypes.STRING,
36
42
  targetBlockNumber: sequelize_2.DataTypes.NUMBER,
37
- targetStatus: sequelize_2.DataTypes.STRING,
43
+ targetStatus: {
44
+ type: sequelize_2.DataTypes.STRING,
45
+ defaultValue: 'uninitialised'
46
+ },
38
47
  targetErrors: {
39
48
  type: sequelize_2.DataTypes.JSON,
40
49
  // defaultValue: [],
41
50
  },
51
+ targetLogs: {
52
+ type: sequelize_2.DataTypes.JSON,
53
+ // defaultValue: [],
54
+ },
42
55
  targetCreatedAt: sequelize_2.DataTypes.DATE,
43
56
  targetDelayUntil: sequelize_2.DataTypes.DATE,
44
- submitEvent: sequelize_2.DataTypes.JSON,
45
- sourceEvent: sequelize_2.DataTypes.JSON,
46
- targetEvent: sequelize_2.DataTypes.JSON,
47
- metadata: sequelize_2.DataTypes.JSON,
57
+ requestEvent: {
58
+ type: sequelize_2.DataTypes.JSON,
59
+ allowNull: false
60
+ },
61
+ requestSentEvent: sequelize_2.DataTypes.JSON,
62
+ committedEvent: sequelize_2.DataTypes.JSON,
63
+ completedEvent: sequelize_2.DataTypes.JSON,
48
64
  status: {
49
65
  type: sequelize_2.DataTypes.STRING,
50
66
  defaultValue: 'pending'
@@ -0,0 +1,9 @@
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 withdraw_1 = __importDefault(require("./withdraw"));
7
+ exports.default = {
8
+ withdraw: withdraw_1.default,
9
+ };
@@ -0,0 +1,115 @@
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 abi_1 = __importDefault(require("@/abi"));
7
+ const config_1 = __importDefault(require("@/config"));
8
+ const constants_1 = require("@/constants");
9
+ const utils_1 = require("@/utils");
10
+ const ethers_1 = require("ethers");
11
+ const ethers_multisend_1 = require("ethers-multisend");
12
+ const getBridgeAmounts = async (user, tokens, chainId) => {
13
+ const sourceChainProvider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(chainId));
14
+ const sourceWallet = new ethers_1.ethers.Wallet(config_1.default.privateKey, sourceChainProvider);
15
+ const contractAddress = constants_1.addresses[chainId].interopXContract;
16
+ const contract = (0, utils_1.getContract)(contractAddress, abi_1.default.interopXContract, sourceWallet);
17
+ const data = await contract.getBridgeAmounts(user, tokens);
18
+ return data.map((item, index) => ({
19
+ token: tokens[index],
20
+ deposit: item.deposit,
21
+ withdraw: item.withdraw,
22
+ }));
23
+ };
24
+ async function default_1(transaction, type) {
25
+ const transactions = [];
26
+ const logs = [];
27
+ if (transaction.actionId !== 'withdraw') {
28
+ throw new Error(`Invalid action: ${transaction.actionId}`);
29
+ }
30
+ if (type !== 'source') {
31
+ throw new Error(`[WIP] Type not supported: ${type}`);
32
+ }
33
+ if (transaction.sourceStatus === 'pending') {
34
+ throw Error('Source transaction already processesing');
35
+ }
36
+ if (transaction.sourceStatus === 'pending') {
37
+ throw Error('Source transaction already processed');
38
+ }
39
+ if (!transaction.requestEvent) {
40
+ throw Error('Something went wrong, source transaction has no request event');
41
+ }
42
+ const { actionId, bridger, position, sourceChainId, targetChainId, metadata } = transaction.requestEvent;
43
+ const sourceChainProvider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(sourceChainId));
44
+ const sourceWallet = new ethers_1.ethers.Wallet(config_1.default.privateKey, sourceChainProvider);
45
+ const contractAddress = constants_1.addresses[sourceChainId].interopXContract;
46
+ const contract = (0, utils_1.getContract)(contractAddress, abi_1.default.interopXContract, sourceWallet);
47
+ const sourceToken = constants_1.tokens[sourceChainId].find(t => t.address.toLowerCase() === position.withdraw[0].sourceToken.toLowerCase());
48
+ if (!sourceToken) {
49
+ throw Error('Source token not found');
50
+ }
51
+ const targetToken = constants_1.tokens[targetChainId].find(t => t.address.toLowerCase() === position.withdraw[0].targetToken.toLowerCase());
52
+ if (!targetToken) {
53
+ throw Error('Target token not found');
54
+ }
55
+ if (!sourceToken.aliases.some(alias => targetToken.aliases.includes(alias))) {
56
+ throw Error('Source and target token must be the same');
57
+ }
58
+ const networks = [137, 43114];
59
+ const networkUserData = {};
60
+ for (const network of networks) {
61
+ networkUserData[network] = await getBridgeAmounts(bridger, constants_1.tokens[network].map(t => t.address), network);
62
+ }
63
+ for (const tokenSymbol of ["dai", "usdc", "usdt", "eth", "wbtc"]) {
64
+ let totalDeposit = ethers_1.BigNumber.from(0);
65
+ let totalWithdraw = ethers_1.BigNumber.from(0);
66
+ for (const network of networks) {
67
+ // on avax might we have 2 usdc/usdt tokens
68
+ const matchedTokens = constants_1.tokens[network].filter(t => t.aliases.includes(tokenSymbol));
69
+ for (const matchedToken of matchedTokens) {
70
+ const data = networkUserData[network].find(t => t.token.toLowerCase() === matchedToken.address.toLowerCase());
71
+ if (data) {
72
+ totalDeposit = totalDeposit.add(data.deposit);
73
+ totalWithdraw = totalWithdraw.add(data.withdraw);
74
+ }
75
+ }
76
+ // on Mainent add weth too
77
+ if (tokenSymbol === "eth" && network === 1) {
78
+ const weth = constants_1.tokens[1].find(t => t.symbol === 'WETH');
79
+ if (weth) {
80
+ const data = networkUserData[1].find(t => t.token.toLowerCase() === weth.address.toLowerCase());
81
+ if (data) {
82
+ totalDeposit = totalDeposit.add(data.deposit);
83
+ totalWithdraw = totalWithdraw.add(data.withdraw);
84
+ }
85
+ }
86
+ }
87
+ }
88
+ if (totalWithdraw.gt(totalDeposit)) {
89
+ throw Error(`if withdraw > deposit, user has debt and we can't process the withdraw and reject it`);
90
+ }
91
+ if (totalWithdraw.lt(totalDeposit)) {
92
+ throw Error('Something went wrong');
93
+ }
94
+ }
95
+ let balance = ethers_1.BigNumber.from(0);
96
+ if (position.withdraw[0].sourceToken.toLowerCase() === '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'.toLowerCase()) {
97
+ balance = await sourceChainProvider.getBalance(bridger);
98
+ }
99
+ else {
100
+ const erc20 = (0, utils_1.getContract)(position.withdraw[0].sourceToken, abi_1.default.erc20, sourceChainProvider);
101
+ balance = await erc20.balanceOf(constants_1.addresses[sourceChainId].gnosisSafe);
102
+ }
103
+ if (balance.lt(position.withdraw[0].amount)) {
104
+ throw new utils_1.LiquidityError();
105
+ }
106
+ const { data } = await contract.populateTransaction.withdrawRequested(actionId, bridger, position.withdraw[0].sourceToken, position.withdraw[0].targetToken, position.withdraw[0].amount, targetChainId, transaction.requestTransactionHash, metadata);
107
+ transactions.push({
108
+ to: contractAddress,
109
+ data: data,
110
+ value: '0',
111
+ operation: ethers_multisend_1.OperationType.Call,
112
+ });
113
+ return { transactions, logs };
114
+ }
115
+ exports.default = default_1;
@@ -0,0 +1,20 @@
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.buildGnosisAction = void 0;
7
+ const ethers_multisend_1 = require("ethers-multisend");
8
+ const actions_1 = __importDefault(require("./actions"));
9
+ const buildGnosisAction = async (transaction, type) => {
10
+ // type = type || (transaction.sourceStatus === 'success' ? 'target' : 'source')
11
+ if (actions_1.default.hasOwnProperty(transaction.actionId)) {
12
+ const { transactions, logs } = await actions_1.default[transaction.actionId](transaction, type);
13
+ return {
14
+ data: (0, ethers_multisend_1.encodeMulti)(transactions).data,
15
+ logs
16
+ };
17
+ }
18
+ throw new Error(`Unknown action: ${transaction.actionId}`);
19
+ };
20
+ exports.buildGnosisAction = buildGnosisAction;
package/dist/src/index.js CHANGED
@@ -3,52 +3,103 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
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 assert_1 = __importDefault(require("assert"));
6
+ require("./alias");
7
+ const expand_home_dir_1 = __importDefault(require("expand-home-dir"));
8
+ const fs_extra_1 = __importDefault(require("fs-extra"));
23
9
  const dotenv_1 = __importDefault(require("dotenv"));
10
+ const chalk_1 = __importDefault(require("chalk"));
24
11
  const ethers_1 = require("ethers");
25
12
  const package_json_1 = __importDefault(require("../package.json"));
26
13
  dotenv_1.default.config();
27
14
  const logger_1 = __importDefault(require("@/logger"));
28
15
  const logger = new logger_1.default('Process');
29
- if (process.argv.at(-1) === 'help') {
16
+ const GIT_SHORT_HASH = '73e5298';
17
+ const printUsage = () => {
18
+ console.log();
19
+ console.log(`Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
20
+ console.log();
30
21
  console.log('Usage:');
31
- console.log(' PRIVATE_KEY=abcd1234 interop-x');
32
- console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x');
22
+ console.log(' interop-x help Show this message');
23
+ console.log(' interop-x version Print out the installed version of Interop X');
24
+ console.log();
25
+ console.log(' interop-x down Put the node into maintenance mode');
26
+ console.log(' interop-x up Take the node out of maintenance mode');
27
+ console.log();
28
+ console.log(' PRIVATE_KEY=abcd1234 interop-x Start the node with the given private key');
29
+ console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x Start the node in staging mode');
30
+ console.log(' PRIVATE_KEY=abcd1234 AUTO_UPDATE=true interop-x Start the node in auto update mode');
31
+ 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');
32
+ console.log();
33
+ };
34
+ if (process.argv.at(-1) === 'help') {
35
+ printUsage();
36
+ process.exit(0);
37
+ }
38
+ const basePath = (0, expand_home_dir_1.default)(`~/.interop-x`);
39
+ if (process.argv.at(-1) === 'down') {
40
+ fs_extra_1.default.outputFileSync(basePath + '/maintenance', Date.now().toString());
41
+ console.log(chalk_1.default.red('Maintenance mode enabled'));
33
42
  process.exit(0);
34
43
  }
35
- (0, assert_1.default)(process.env.PRIVATE_KEY, "PRIVATE_KEY is not defined");
44
+ if (process.argv.at(-1) === 'up') {
45
+ fs_extra_1.default.removeSync(basePath + '/maintenance');
46
+ console.log(chalk_1.default.green('Maintenance mode disabled'));
47
+ process.exit(0);
48
+ }
49
+ if (process.argv.at(-1) === 'version') {
50
+ console.log(`Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
51
+ process.exit(0);
52
+ }
53
+ if (!process.env.PRIVATE_KEY) {
54
+ console.error(chalk_1.default.bgRed.white.bold('Please provide a private key\n'));
55
+ printUsage();
56
+ process.exit(1);
57
+ }
36
58
  try {
37
59
  new ethers_1.ethers.Wallet(process.env.PRIVATE_KEY);
38
60
  }
39
61
  catch (e) {
40
- logger.error('Invalid private key');
62
+ console.error(chalk_1.default.bgRed.white('Invalid private key\n'));
63
+ printUsage();
41
64
  process.exit(1);
42
65
  }
43
- logger.debug(`Starting Interop X Node (v${package_json_1.default.version} - rev.73da8c9)`);
66
+ logger.debug(`Starting Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
44
67
  const tasks_1 = require("@/tasks");
45
68
  const net_1 = require("@/net");
46
69
  const api_1 = require("@/api");
70
+ const db_1 = require("./db");
71
+ const utils_1 = require("./utils");
47
72
  async function main() {
48
73
  (0, net_1.startPeer)({});
49
74
  const tasks = new tasks_1.Tasks();
50
- tasks.start();
75
+ setTimeout(() => {
76
+ tasks.start();
77
+ }, 10000);
51
78
  (0, api_1.startApiServer)();
79
+ net_1.protocol.on('TransactionStatus', async (payload) => {
80
+ if (!net_1.peerPool.isLeadNode(payload.peerId)) {
81
+ const peer = net_1.peerPool.getPeer(payload.peerId);
82
+ if (!peer) {
83
+ return;
84
+ }
85
+ logger.info(`ignored transaction status from ${payload.peerId} ${(0, utils_1.shortenHash)(peer.publicAddress)} `);
86
+ return;
87
+ }
88
+ const transaction = await db_1.Transaction.findOne({ where: { transactionHash: payload.data.transactionHash } });
89
+ if (!transaction) {
90
+ return;
91
+ }
92
+ transaction.sourceStatus = payload.data.sourceStatus;
93
+ transaction.sourceTransactionHash = payload.data.sourceTransactionHash;
94
+ transaction.sourceErrors = payload.data.sourceErrors;
95
+ transaction.sourceLogs = payload.data.sourceLogs;
96
+ transaction.targetStatus = payload.data.targetStatus;
97
+ transaction.targetTransactionHash = payload.data.targetTransactionHash;
98
+ transaction.targetErrors = payload.data.targetErrors;
99
+ transaction.targetLogs = payload.data.targetLogs;
100
+ transaction.status = payload.data.status;
101
+ await transaction.save();
102
+ });
52
103
  }
53
104
  main()
54
105
  .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) => {
@@ -10,12 +10,17 @@ const config_1 = __importDefault(require("@/config"));
10
10
  const db_1 = require("@/db");
11
11
  const utils_1 = require("@/utils");
12
12
  const constants_1 = require("@/constants");
13
+ const gnosis_1 = require("@/gnosis");
13
14
  class SignatureDialProtocol extends BaseDialProtocol_1.BaseDialProtocol {
14
15
  constructor(libp2p) {
15
16
  super(libp2p, '/interop-x/signatures');
16
17
  this.timeout = 30000;
17
18
  }
18
19
  async response(data) {
20
+ console.log({
21
+ tag: 'SignatureDialProtocol',
22
+ data
23
+ });
19
24
  const signer = config_1.default.wallet;
20
25
  let transaction;
21
26
  let maxTimeout = 20000;
@@ -33,12 +38,13 @@ class SignatureDialProtocol extends BaseDialProtocol_1.BaseDialProtocol {
33
38
  error: 'Event not found'
34
39
  };
35
40
  }
41
+ const { data: gnosisData } = await (0, gnosis_1.buildGnosisAction)(transaction, data.type);
36
42
  const signedData = await (0, utils_1.signGnosisSafeTx)({
37
- //TODO: chain id depends on event type
38
43
  to: constants_1.addresses[transaction.sourceChainId].multisend,
39
- data: await (0, utils_1.buildDataForTransaction)(transaction, data.type),
44
+ data: gnosisData,
40
45
  chainId: transaction.sourceChainId,
41
46
  safeTxGas: data.safeTxGas,
47
+ nonce: data.safeNonce,
42
48
  }, { signer });
43
49
  return {
44
50
  signer: signer.address,
@@ -0,0 +1,30 @@
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
+ sourceLogs: transaction.sourceLogs,
22
+ targetStatus: transaction.targetStatus,
23
+ targetTransactionHash: transaction.targetTransactionHash,
24
+ targetErrors: transaction.targetErrors,
25
+ targetLogs: transaction.targetLogs,
26
+ status: transaction.status,
27
+ };
28
+ }
29
+ }
30
+ exports.TransactionStatusDialProtocol = TransactionStatusDialProtocol;