@instadapp/interop-x 0.0.0-dev.3e0fb42 → 0.0.0-dev.40b2517

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 (100) hide show
  1. package/.env.example +2 -1
  2. package/dist/package.json +74 -0
  3. package/dist/src/abi/erc20.json +350 -0
  4. package/dist/src/abi/gnosisSafe.json +747 -0
  5. package/dist/src/abi/index.js +13 -0
  6. package/dist/src/abi/interopXContract.json +454 -0
  7. package/dist/src/alias.js +10 -0
  8. package/dist/src/api/index.js +36 -0
  9. package/dist/src/config/index.js +31 -0
  10. package/dist/src/constants/addresses.js +20 -0
  11. package/dist/{constants → src/constants}/index.js +1 -0
  12. package/dist/src/constants/tokens.js +130 -0
  13. package/dist/{db → src/db}/index.js +0 -0
  14. package/dist/{db → src/db}/models/index.js +1 -1
  15. package/dist/src/db/models/transaction.js +70 -0
  16. package/dist/{db → src/db}/sequelize.js +2 -1
  17. package/dist/src/gnosis/actions/index.js +9 -0
  18. package/dist/src/gnosis/actions/withdraw/index.js +115 -0
  19. package/dist/src/gnosis/index.js +20 -0
  20. package/dist/src/index.js +119 -0
  21. package/dist/{logger → src/logger}/index.js +0 -0
  22. package/dist/{net → src/net}/index.js +0 -0
  23. package/dist/{net → src/net}/peer/index.js +15 -6
  24. package/dist/{net → src/net}/pool/index.js +34 -11
  25. package/dist/{net → src/net}/protocol/dial/BaseDialProtocol.js +1 -1
  26. package/dist/{net → src/net}/protocol/dial/SignatureDialProtocol.js +21 -14
  27. package/dist/src/net/protocol/dial/TransactionStatusDialProtocol.js +30 -0
  28. package/dist/{net → src/net}/protocol/index.js +54 -4
  29. package/dist/src/tasks/AutoUpdateTask.js +70 -0
  30. package/dist/{tasks → src/tasks}/BaseTask.js +14 -6
  31. package/dist/src/tasks/InteropXContract/ProcessBridgeRequestEvents.js +158 -0
  32. package/dist/src/tasks/InteropXContract/SyncBridgeCommittedEvents.js +93 -0
  33. package/dist/src/tasks/InteropXContract/SyncBridgeRequestEvents.js +78 -0
  34. package/dist/src/tasks/InteropXContract/SyncBridgeRequestSentEvents.js +90 -0
  35. package/dist/src/tasks/Transactions/SyncTransactionStatusTask.js +55 -0
  36. package/dist/src/tasks/index.js +41 -0
  37. package/dist/src/typechain/Erc20.js +2 -0
  38. package/dist/src/typechain/GnosisSafe.js +2 -0
  39. package/dist/src/typechain/InteropXContract.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/InteropXContract__factory.js +635 -0
  44. package/dist/src/typechain/factories/index.js +12 -0
  45. package/dist/src/typechain/index.js +33 -0
  46. package/dist/{types.js → src/types.js} +0 -0
  47. package/dist/src/utils/index.js +193 -0
  48. package/package.json +30 -15
  49. package/patches/@ethersproject+properties+5.6.0.patch +13 -0
  50. package/src/abi/erc20.json +350 -0
  51. package/src/abi/gnosisSafe.json +747 -0
  52. package/src/abi/index.ts +9 -0
  53. package/src/abi/interopXContract.json +454 -0
  54. package/src/alias.ts +6 -0
  55. package/src/api/index.ts +36 -0
  56. package/src/config/index.ts +18 -2
  57. package/src/constants/addresses.ts +13 -6
  58. package/src/constants/index.ts +1 -0
  59. package/src/constants/tokens.ts +127 -0
  60. package/src/db/index.ts +1 -1
  61. package/src/db/models/index.ts +1 -1
  62. package/src/db/models/transaction.ts +145 -0
  63. package/src/db/sequelize.ts +2 -1
  64. package/src/gnosis/actions/index.ts +5 -0
  65. package/src/gnosis/actions/withdraw/index.ts +155 -0
  66. package/src/gnosis/index.ts +19 -0
  67. package/src/index.ts +118 -7
  68. package/src/net/peer/index.ts +17 -9
  69. package/src/net/pool/index.ts +43 -13
  70. package/src/net/protocol/dial/BaseDialProtocol.ts +1 -1
  71. package/src/net/protocol/dial/SignatureDialProtocol.ts +24 -17
  72. package/src/net/protocol/dial/TransactionStatusDialProtocol.ts +33 -0
  73. package/src/net/protocol/index.ts +71 -5
  74. package/src/tasks/AutoUpdateTask.ts +82 -0
  75. package/src/tasks/BaseTask.ts +16 -7
  76. package/src/tasks/InteropXContract/ProcessBridgeRequestEvents.ts +226 -0
  77. package/src/tasks/InteropXContract/SyncBridgeCommittedEvents.ts +125 -0
  78. package/src/tasks/InteropXContract/SyncBridgeRequestEvents.ts +115 -0
  79. package/src/tasks/InteropXContract/SyncBridgeRequestSentEvents.ts +121 -0
  80. package/src/tasks/Transactions/SyncTransactionStatusTask.ts +67 -0
  81. package/src/tasks/index.ts +28 -2
  82. package/src/typechain/Erc20.ts +491 -0
  83. package/src/typechain/GnosisSafe.ts +1728 -0
  84. package/src/typechain/InteropXContract.ts +680 -0
  85. package/src/typechain/common.ts +44 -0
  86. package/src/typechain/factories/Erc20__factory.ts +368 -0
  87. package/src/typechain/factories/GnosisSafe__factory.ts +1178 -0
  88. package/src/typechain/factories/InteropXContract__factory.ts +642 -0
  89. package/src/typechain/factories/index.ts +6 -0
  90. package/src/typechain/index.ts +10 -0
  91. package/src/types.ts +2 -2
  92. package/src/utils/index.ts +163 -4
  93. package/tsconfig.json +8 -0
  94. package/dist/config/index.js +0 -17
  95. package/dist/constants/addresses.js +0 -13
  96. package/dist/db/models/execution.js +0 -38
  97. package/dist/index.js +0 -34
  98. package/dist/tasks/index.js +0 -19
  99. package/dist/utils/index.js +0 -89
  100. package/src/db/models/execution.ts +0 -57
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tokens = void 0;
4
+ exports.tokens = {
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
+ // ],
49
+ 137: [
50
+ {
51
+ aliases: ['eth', 'weth'],
52
+ symbol: "ETH",
53
+ name: "Ethereum",
54
+ address: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
55
+ decimals: 18,
56
+ },
57
+ {
58
+ aliases: ['dai'],
59
+ symbol: "DAI",
60
+ name: "DAI Stable",
61
+ address: "0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063",
62
+ decimals: 18,
63
+ },
64
+ {
65
+ aliases: ['usdc'],
66
+ symbol: "USDC",
67
+ name: "USD Coin",
68
+ address: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
69
+ decimals: 6,
70
+ },
71
+ {
72
+ aliases: ['usdt'],
73
+ symbol: "USDT",
74
+ name: "Tether USD Coin",
75
+ address: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F",
76
+ decimals: 6,
77
+ },
78
+ {
79
+ aliases: ['wbtc'],
80
+ symbol: "WBTC",
81
+ name: "Wrapped BTC",
82
+ address: "0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6",
83
+ decimals: 8,
84
+ },
85
+ ],
86
+ 43114: [
87
+ {
88
+ aliases: ['eth', 'weth'],
89
+ symbol: "ETH",
90
+ name: "Ethereum",
91
+ address: "0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB",
92
+ decimals: 18,
93
+ },
94
+ {
95
+ aliases: ['dai'],
96
+ symbol: "DAI",
97
+ name: "DAI Stable",
98
+ address: "0xd586E7F844cEa2F87f50152665BCbc2C279D8d70",
99
+ decimals: 18,
100
+ },
101
+ {
102
+ aliases: ['usdc'],
103
+ symbol: "USDC",
104
+ name: "USD Coin",
105
+ address: "0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664",
106
+ decimals: 6,
107
+ },
108
+ {
109
+ aliases: ['usdt'],
110
+ symbol: "USDt",
111
+ name: "Tether USD Coin",
112
+ address: "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",
113
+ decimals: 6,
114
+ },
115
+ {
116
+ aliases: ['usdt'],
117
+ symbol: "USDT.e",
118
+ name: "Tether USD",
119
+ address: "0xc7198437980c041c805A1EDcbA50c1Ce5db95118",
120
+ decimals: 6,
121
+ },
122
+ {
123
+ aliases: ["wbtc"],
124
+ symbol: "WBTC",
125
+ name: "Wrapped BTC",
126
+ address: "0x50b7545627a5162F82A992c33b87aDc75187B218",
127
+ decimals: 8,
128
+ },
129
+ ],
130
+ };
File without changes
@@ -14,4 +14,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./execution"), exports);
17
+ __exportStar(require("./transaction"), exports);
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transaction = void 0;
4
+ const sequelize_1 = require("@/db/sequelize");
5
+ const sequelize_2 = require("sequelize");
6
+ class Transaction extends sequelize_2.Model {
7
+ }
8
+ exports.Transaction = Transaction;
9
+ Transaction.init({
10
+ id: {
11
+ type: sequelize_2.DataTypes.INTEGER,
12
+ autoIncrement: true,
13
+ primaryKey: true
14
+ },
15
+ requestTransactionHash: sequelize_2.DataTypes.NUMBER,
16
+ requestBlockNumber: sequelize_2.DataTypes.NUMBER,
17
+ transactionHash: sequelize_2.DataTypes.STRING,
18
+ actionId: sequelize_2.DataTypes.STRING,
19
+ bridger: sequelize_2.DataTypes.STRING,
20
+ sourceChainId: sequelize_2.DataTypes.NUMBER,
21
+ sourceTransactionHash: sequelize_2.DataTypes.STRING,
22
+ sourceBlockNumber: sequelize_2.DataTypes.NUMBER,
23
+ sourceStatus: {
24
+ type: sequelize_2.DataTypes.STRING,
25
+ defaultValue: 'uninitialised'
26
+ },
27
+ sourceErrors: {
28
+ type: sequelize_2.DataTypes.JSON,
29
+ // defaultValue: [],
30
+ },
31
+ sourceLogs: {
32
+ type: sequelize_2.DataTypes.JSON,
33
+ // defaultValue: [],
34
+ },
35
+ sourceCreatedAt: {
36
+ type: sequelize_2.DataTypes.DATE,
37
+ defaultValue: Date.now()
38
+ },
39
+ sourceDelayUntil: sequelize_2.DataTypes.STRING,
40
+ targetChainId: sequelize_2.DataTypes.NUMBER,
41
+ targetTransactionHash: sequelize_2.DataTypes.STRING,
42
+ targetBlockNumber: sequelize_2.DataTypes.NUMBER,
43
+ targetStatus: {
44
+ type: sequelize_2.DataTypes.STRING,
45
+ defaultValue: 'uninitialised'
46
+ },
47
+ targetErrors: {
48
+ type: sequelize_2.DataTypes.JSON,
49
+ // defaultValue: [],
50
+ },
51
+ targetLogs: {
52
+ type: sequelize_2.DataTypes.JSON,
53
+ // defaultValue: [],
54
+ },
55
+ targetCreatedAt: sequelize_2.DataTypes.DATE,
56
+ targetDelayUntil: sequelize_2.DataTypes.DATE,
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,
64
+ status: {
65
+ type: sequelize_2.DataTypes.STRING,
66
+ defaultValue: 'pending'
67
+ },
68
+ createdAt: sequelize_2.DataTypes.DATE,
69
+ updatedAt: sequelize_2.DataTypes.DATE,
70
+ }, { sequelize: sequelize_1.sequelize, tableName: 'transactions' });
@@ -5,9 +5,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.sequelize = void 0;
7
7
  //@ts-ignore
8
+ const config_1 = __importDefault(require("@/config"));
8
9
  const expand_home_dir_1 = __importDefault(require("expand-home-dir"));
9
10
  const sequelize_1 = require("sequelize");
10
- const basePath = (0, expand_home_dir_1.default)('~/.interop-x/data');
11
+ const basePath = (0, expand_home_dir_1.default)(`~/.interop-x/data/${config_1.default.publicAddress}/${config_1.default.staging ? 'staging' : ''}`);
11
12
  exports.sequelize = new sequelize_1.Sequelize({
12
13
  dialect: 'sqlite',
13
14
  storage: `${basePath}/localDB.sqlite`,
@@ -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
+ if (totalWithdraw.gt(totalDeposit)) {
88
+ throw Error(`if withdraw > deposit, user has debt and we can't process the withdraw and reject it`);
89
+ }
90
+ if (totalWithdraw.lt(totalDeposit)) {
91
+ throw Error('Something went wrong');
92
+ }
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;
@@ -0,0 +1,119 @@
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
+ require("./alias");
7
+ const expand_home_dir_1 = __importDefault(require("expand-home-dir"));
8
+ const fs_extra_1 = __importDefault(require("fs-extra"));
9
+ const dotenv_1 = __importDefault(require("dotenv"));
10
+ const chalk_1 = __importDefault(require("chalk"));
11
+ const ethers_1 = require("ethers");
12
+ const package_json_1 = __importDefault(require("../package.json"));
13
+ dotenv_1.default.config();
14
+ const logger_1 = __importDefault(require("@/logger"));
15
+ const logger = new logger_1.default('Process');
16
+ const GIT_SHORT_HASH = '40b2517';
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();
21
+ console.log('Usage:');
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'));
42
+ process.exit(0);
43
+ }
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
+ }
58
+ try {
59
+ new ethers_1.ethers.Wallet(process.env.PRIVATE_KEY);
60
+ }
61
+ catch (e) {
62
+ console.error(chalk_1.default.bgRed.white('Invalid private key\n'));
63
+ printUsage();
64
+ process.exit(1);
65
+ }
66
+ logger.debug(`Starting Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
67
+ const tasks_1 = require("@/tasks");
68
+ const net_1 = require("@/net");
69
+ const api_1 = require("@/api");
70
+ const db_1 = require("./db");
71
+ const utils_1 = require("./utils");
72
+ async function main() {
73
+ (0, net_1.startPeer)({});
74
+ const tasks = new tasks_1.Tasks();
75
+ setTimeout(() => {
76
+ tasks.start();
77
+ }, 10000);
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
+ });
103
+ }
104
+ main()
105
+ .then(() => {
106
+ }).catch(err => {
107
+ console.error(err);
108
+ });
109
+ process.on('SIGINT', () => {
110
+ logger.debug('received SIGINT signal. exiting.');
111
+ process.exit(0);
112
+ });
113
+ process.on('SIGTERM', () => {
114
+ logger.debug('received SIGTERM signal. exiting.');
115
+ process.exit(0);
116
+ });
117
+ process.on('unhandledRejection', (reason, p) => {
118
+ logger.error('unhandled rejection: promise:', p, 'reason:', reason);
119
+ });
File without changes
File without changes
@@ -11,7 +11,7 @@ const libp2p_websockets_1 = __importDefault(require("libp2p-websockets"));
11
11
  //@ts-ignore
12
12
  const libp2p_mplex_1 = __importDefault(require("libp2p-mplex"));
13
13
  const libp2p_noise_1 = require("libp2p-noise");
14
- const logger_1 = __importDefault(require("../../logger"));
14
+ const logger_1 = __importDefault(require("@/logger"));
15
15
  const libp2p_bootstrap_1 = __importDefault(require("libp2p-bootstrap"));
16
16
  const waait_1 = __importDefault(require("waait"));
17
17
  const libp2p_gossipsub_1 = __importDefault(require("@achingbrain/libp2p-gossipsub"));
@@ -21,7 +21,9 @@ const libp2p_mdns_1 = __importDefault(require("libp2p-mdns"));
21
21
  const libp2p_kad_dht_1 = __importDefault(require("libp2p-kad-dht"));
22
22
  //@ts-ignore
23
23
  const libp2p_pubsub_peer_discovery_1 = __importDefault(require("libp2p-pubsub-peer-discovery"));
24
- const protocol_1 = require("../protocol");
24
+ const net_1 = require("@/net");
25
+ const config_1 = __importDefault(require("@/config"));
26
+ const chalk_1 = __importDefault(require("chalk"));
25
27
  const logger = new logger_1.default("Peer");
26
28
  let node;
27
29
  // Known peers addresses
@@ -76,15 +78,22 @@ const startPeer = async ({}) => {
76
78
  persistence: true,
77
79
  },
78
80
  });
79
- logger.info("Peer ID:", node.peerId.toB58String());
81
+ logger.info("Peer ID:", chalk_1.default.bold(node.peerId.toB58String()));
80
82
  await node.start();
81
- protocol_1.protocol.start({
83
+ net_1.protocol.start({
82
84
  libp2p: node
83
85
  });
84
- node.on("peer:discovery", (peer) => logger.log(`Discovered peer ${peer}`)); // peer disc.
85
- node.connectionManager.on("peer:connect", (connection) => logger.log(`Connected to ${connection.remotePeer.toB58String()}`));
86
+ node.on("peer:discovery", (peer) => {
87
+ // logger.log(`Discovered peer ${peer}`)
88
+ }); // peer disc.
89
+ node.connectionManager.on("peer:connect", (connection) => {
90
+ // logger.log(`Connected to ${connection.remotePeer.toB58String()}`)
91
+ });
86
92
  logger.log("Peer discovery started");
87
93
  await (0, waait_1.default)(1000);
94
+ setInterval(() => net_1.protocol.sendPeerInfo({
95
+ publicAddress: config_1.default.wallet.address,
96
+ }), 5000);
88
97
  };
89
98
  exports.startPeer = startPeer;
90
99
  const stopPeer = async () => {
@@ -4,8 +4,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.peerPool = exports.PeerPool = void 0;
7
- const types_1 = require("../../types");
8
- const config_1 = __importDefault(require("../../config"));
7
+ const types_1 = require("@/types");
8
+ const config_1 = __importDefault(require("@/config"));
9
+ const logger_1 = __importDefault(require("@/logger"));
10
+ const utils_1 = require("ethers/lib/utils");
11
+ const utils_2 = require("@/utils");
12
+ const chalk_1 = __importDefault(require("chalk"));
13
+ const logger = new logger_1.default('PeerPool');
9
14
  class PeerPool {
10
15
  constructor() {
11
16
  this.PEERS_CLEANUP_TIME_LIMIT = 1;
@@ -62,10 +67,14 @@ class PeerPool {
62
67
  * @emits {@link Event.POOL_PEER_ADDED}
63
68
  */
64
69
  add(peer) {
65
- if (peer && peer.id && !this.pool.get(peer.id)) {
70
+ if (peer && peer.id) {
71
+ const newPeer = !this.pool.get(peer.id);
66
72
  this.pool.set(peer.id, peer);
67
73
  peer.pooled = true;
68
- config_1.default.events.emit(types_1.Event.POOL_PEER_ADDED, peer);
74
+ if (newPeer) {
75
+ config_1.default.events.emit(types_1.Event.POOL_PEER_ADDED, peer);
76
+ logger.info(`Peer ${chalk_1.default.bold((0, utils_2.shortenHash)(peer.id, 16))} with address ${chalk_1.default.bold((0, utils_2.shortenHash)(peer.publicAddress))} added to pool`);
77
+ }
69
78
  }
70
79
  }
71
80
  /**
@@ -78,6 +87,7 @@ class PeerPool {
78
87
  if (this.pool.delete(peer.id)) {
79
88
  peer.pooled = false;
80
89
  config_1.default.events.emit(types_1.Event.POOL_PEER_REMOVED, peer);
90
+ logger.info(`Peer ${chalk_1.default.bold((0, utils_2.shortenHash)(peer.id, 16))} with address ${chalk_1.default.bold((0, utils_2.shortenHash)(peer.publicAddress))} removed from pool`);
81
91
  }
82
92
  }
83
93
  }
@@ -93,14 +103,27 @@ class PeerPool {
93
103
  get activePeerIds() {
94
104
  return this.activePeers.map((p) => p.id);
95
105
  }
106
+ getPeer(id) {
107
+ return this.pool.get(id);
108
+ }
109
+ isLeadNode(id) {
110
+ const peer = this.pool.get(id);
111
+ if (!peer) {
112
+ return false;
113
+ }
114
+ return (0, utils_1.getAddress)(peer.publicAddress) === (0, utils_1.getAddress)(config_1.default.leadNodeAddress);
115
+ }
116
+ getLeadPeer() {
117
+ return this.peers.find((p) => this.isLeadNode(p.id));
118
+ }
96
119
  cleanup() {
97
- let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60;
98
- this.peers.forEach((peerInfo) => {
99
- if (peerInfo.updated.getTime() < compDate) {
100
- console.log(`Peer ${peerInfo.id} idle for ${this.PEERS_CLEANUP_TIME_LIMIT} minutes`);
101
- this.remove(peerInfo);
102
- }
103
- });
120
+ // let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
121
+ // this.peers.forEach((peerInfo) => {
122
+ // if (peerInfo.updated.getTime() < compDate) {
123
+ // console.log(`Peer ${peerInfo.id} idle for ${this.PEERS_CLEANUP_TIME_LIMIT} minutes`)
124
+ // this.remove(peerInfo)
125
+ // }
126
+ // })
104
127
  }
105
128
  }
106
129
  exports.PeerPool = PeerPool;
@@ -13,7 +13,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.BaseDialProtocol = void 0;
14
14
  const it_pipe_1 = __importDefault(require("it-pipe"));
15
15
  const peer_id_1 = __importDefault(require("peer-id"));
16
- const utils_1 = require("../../../utils");
16
+ const utils_1 = require("@/utils");
17
17
  const waait_1 = __importDefault(require("waait"));
18
18
  class BaseDialProtocol {
19
19
  constructor(libp2p, protocol) {