@instadapp/interop-x 0.0.0-dev.868731f → 0.0.0-dev.8965b57

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 (80) hide show
  1. package/dist/package.json +8 -7
  2. package/dist/src/abi/index.js +2 -4
  3. package/dist/src/abi/interopXContract.json +391 -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 +3 -3
  8. package/dist/src/constants/index.js +0 -1
  9. package/dist/src/constants/tokens.js +31 -1
  10. package/dist/src/db/models/transaction.js +26 -10
  11. package/dist/src/gnosis/actions/index.js +9 -0
  12. package/dist/src/gnosis/actions/withdraw/index.js +55 -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 +25 -9
  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 +152 -0
  23. package/dist/src/tasks/InteropXContract/SyncBridgeRequestEvents.js +77 -0
  24. package/dist/src/tasks/InteropXContract/SyncBridgeRequestSentEvents.js +89 -0
  25. package/dist/src/tasks/Transactions/SyncTransactionStatusTask.js +55 -0
  26. package/dist/src/tasks/index.js +15 -8
  27. package/dist/src/typechain/{InteropBridgeToken.js → InteropXContract.js} +0 -0
  28. package/dist/src/typechain/factories/InteropXContract__factory.js +526 -0
  29. package/dist/src/typechain/factories/index.js +3 -5
  30. package/dist/src/typechain/index.js +3 -5
  31. package/dist/src/utils/index.js +32 -42
  32. package/package.json +8 -7
  33. package/src/abi/index.ts +2 -4
  34. package/src/abi/interopXContract.json +391 -0
  35. package/src/alias.ts +6 -0
  36. package/src/api/index.ts +5 -2
  37. package/src/config/index.ts +11 -1
  38. package/src/constants/addresses.ts +3 -3
  39. package/src/constants/index.ts +0 -1
  40. package/src/constants/tokens.ts +32 -2
  41. package/src/db/models/transaction.ts +64 -25
  42. package/src/gnosis/actions/index.ts +5 -0
  43. package/src/gnosis/actions/withdraw/index.ts +76 -0
  44. package/src/gnosis/index.ts +19 -0
  45. package/src/index.ts +96 -26
  46. package/src/net/peer/index.ts +2 -1
  47. package/src/net/pool/index.ts +33 -13
  48. package/src/net/protocol/dial/SignatureDialProtocol.ts +10 -4
  49. package/src/net/protocol/dial/TransactionStatusDialProtocol.ts +33 -0
  50. package/src/net/protocol/index.ts +67 -1
  51. package/src/tasks/AutoUpdateTask.ts +82 -0
  52. package/src/tasks/BaseTask.ts +13 -3
  53. package/src/tasks/InteropXContract/ProcessBridgeRequestEvents.ts +216 -0
  54. package/src/tasks/InteropXContract/SyncBridgeRequestEvents.ts +114 -0
  55. package/src/tasks/InteropXContract/SyncBridgeRequestSentEvents.ts +120 -0
  56. package/src/tasks/Transactions/SyncTransactionStatusTask.ts +67 -0
  57. package/src/tasks/index.ts +23 -9
  58. package/src/typechain/InteropXContract.ts +524 -0
  59. package/src/typechain/factories/InteropXContract__factory.ts +533 -0
  60. package/src/typechain/factories/index.ts +1 -2
  61. package/src/typechain/index.ts +2 -4
  62. package/src/utils/index.ts +67 -65
  63. package/tsconfig.json +7 -2
  64. package/dist/src/abi/interopBridgeToken.json +0 -286
  65. package/dist/src/abi/interopXGateway.json +0 -184
  66. package/dist/src/constants/itokens.js +0 -13
  67. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +0 -152
  68. package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +0 -75
  69. package/dist/src/typechain/InteropXGateway.js +0 -2
  70. package/dist/src/typechain/factories/InteropBridgeToken__factory.js +0 -459
  71. package/dist/src/typechain/factories/InteropXGateway__factory.js +0 -265
  72. package/src/abi/interopBridgeToken.json +0 -286
  73. package/src/abi/interopXGateway.json +0 -184
  74. package/src/constants/itokens.ts +0 -10
  75. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +0 -247
  76. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +0 -126
  77. package/src/typechain/InteropBridgeToken.ts +0 -686
  78. package/src/typechain/InteropXGateway.ts +0 -407
  79. package/src/typechain/factories/InteropBridgeToken__factory.ts +0 -466
  80. package/src/typechain/factories/InteropXGateway__factory.ts +0 -272
@@ -1,30 +1,42 @@
1
1
  export const tokens = {
2
2
  1: [
3
3
  {
4
+ aliases: ['eth'],
4
5
  symbol: "ETH",
5
6
  name: "Ethereum",
6
7
  address: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
7
8
  decimals: 18,
8
9
  },
9
10
  {
11
+ aliases: ['weth'],
12
+ symbol: "WETH",
13
+ name: "Wrapped Ethereum",
14
+ address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
15
+ decimals: 18,
16
+ },
17
+ {
18
+ aliases: ['dai'],
10
19
  symbol: "DAI",
11
20
  name: "DAI Stable",
12
21
  address: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
13
22
  decimals: 18,
14
23
  },
15
24
  {
25
+ aliases: ['usdc'],
16
26
  symbol: "USDC",
17
27
  name: "USD Coin",
18
28
  address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
19
29
  decimals: 6,
20
30
  },
21
31
  {
32
+ aliases: ['usdt'],
22
33
  symbol: "USDT",
23
34
  name: "Tether USD Coin",
24
35
  address: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
25
36
  decimals: 6,
26
37
  },
27
38
  {
39
+ aliases: ['wbtc'],
28
40
  symbol: "WBTC",
29
41
  name: "Wrapped BTC",
30
42
  address: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",
@@ -33,36 +45,42 @@ export const tokens = {
33
45
  ],
34
46
  137: [
35
47
  {
48
+ aliases: ['eth', 'weth'],
36
49
  symbol: "ETH",
37
50
  name: "Ethereum",
38
51
  address: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
39
52
  decimals: 18,
40
53
  },
41
54
  {
55
+ aliases: ['dai'],
42
56
  symbol: "DAI",
43
57
  name: "DAI Stable",
44
58
  address: "0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063",
45
59
  decimals: 18,
46
60
  },
47
61
  {
62
+ aliases: ['usdc'],
48
63
  symbol: "USDC",
49
64
  name: "USD Coin",
50
65
  address: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
51
66
  decimals: 6,
52
67
  },
53
68
  {
69
+ aliases: ['usdt'],
54
70
  symbol: "USDT",
55
71
  name: "Tether USD Coin",
56
72
  address: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F",
57
73
  decimals: 6,
58
74
  },
59
75
  {
76
+ aliases: ['wbtc'],
60
77
  symbol: "WBTC",
61
78
  name: "Wrapped BTC",
62
79
  address: "0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6",
63
80
  decimals: 8,
64
81
  },
65
82
  {
83
+ aliases: ['avax'],
66
84
  symbol: "AVAX",
67
85
  name: "Avalanche Token",
68
86
  address: "0x2C89bbc92BD86F8075d1DEcc58C7F4E0107f286b",
@@ -71,34 +89,46 @@ export const tokens = {
71
89
  ],
72
90
  43114: [
73
91
  {
92
+ aliases: ['eth', 'weth'],
74
93
  symbol: "ETH",
75
94
  name: "Ethereum",
76
95
  address: "0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB",
77
96
  decimals: 18,
78
97
  },
79
98
  {
99
+ aliases: ['dai'],
80
100
  symbol: "DAI",
81
101
  name: "DAI Stable",
82
102
  address: "0xd586E7F844cEa2F87f50152665BCbc2C279D8d70",
83
103
  decimals: 18,
84
104
  },
85
105
  {
106
+ aliases: ['usdc'],
86
107
  symbol: "USDC",
87
108
  name: "USD Coin",
88
109
  address: "0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664",
89
110
  decimals: 6,
90
111
  },
91
112
  {
92
- symbol: "USDT",
113
+ aliases: ['usdt'],
114
+ symbol: "USDt",
93
115
  name: "Tether USD Coin",
116
+ address: "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",
117
+ decimals: 6,
118
+ },
119
+ {
120
+ aliases: ['usdt'],
121
+ symbol: "USDT.e",
122
+ name: "Tether USD",
94
123
  address: "0xc7198437980c041c805A1EDcbA50c1Ce5db95118",
95
124
  decimals: 6,
96
125
  },
97
126
  {
127
+ aliases: ["wbtc"],
98
128
  symbol: "WBTC",
99
129
  name: "Wrapped BTC",
100
130
  address: "0x50b7545627a5162F82A992c33b87aDc75187B218",
101
131
  decimals: 8,
102
132
  },
103
133
  ],
104
- };
134
+ } as Record<number, { aliases: string[], symbol: string, name: string, address: string, decimals: number }[]>;
@@ -1,40 +1,65 @@
1
1
  import { sequelize } from '@/db/sequelize'
2
2
  import { CreationOptional, InferAttributes, InferCreationAttributes, Model, DataTypes } from 'sequelize';
3
3
 
4
+ export interface IPositionTokenInfo{
5
+ amount: string;
6
+ sourceToken: string;
7
+ targetToken: string;
8
+ }
9
+
10
+ export interface IPosition {
11
+ supply: IPositionTokenInfo[];
12
+ withdraw: IPositionTokenInfo[];
13
+ }
14
+
4
15
  export class Transaction extends Model<InferAttributes<Transaction>, InferCreationAttributes<Transaction>> {
5
16
  declare id: CreationOptional<number>;
6
17
 
7
18
  declare transactionHash: string;
19
+
8
20
  declare action: string;
9
- declare from: string;
10
- declare to: string;
21
+ declare bridger: string;
22
+ declare requestTransactionHash: string;
11
23
 
12
- declare submitTransactionHash: string;
13
- declare submitBlockNumber: number;
24
+ declare requestBlockNumber: number;
14
25
 
15
26
  declare sourceChainId: number;
16
27
  declare sourceTransactionHash: CreationOptional<string>;
17
28
  declare sourceBlockNumber: CreationOptional<number>;
18
- declare sourceStatus: string;
29
+ declare sourceStatus: CreationOptional<string>;
19
30
  declare sourceErrors: CreationOptional<string[]>;
31
+ declare sourceLogs: CreationOptional<any[]>;
20
32
  declare sourceCreatedAt: CreationOptional<Date>;
21
33
  declare sourceDelayUntil: CreationOptional<Date>;
22
34
 
23
35
  declare targetChainId: number;
24
36
  declare targetTransactionHash: CreationOptional<string>;
25
37
  declare targetBlockNumber: CreationOptional<number>;
26
- declare targetStatus: string;
38
+ declare targetStatus: CreationOptional<string>;
27
39
  declare targetErrors: CreationOptional<string[]>;
40
+ declare targetLogs: CreationOptional<any[]>;
28
41
  declare targetCreatedAt: CreationOptional<Date>;
29
42
  declare targetDelayUntil: CreationOptional<Date>;
30
43
 
31
- declare submitEvent: any;
32
- declare sourceEvent: CreationOptional<any>;
33
- declare targetEvent: CreationOptional<any>;
34
-
35
- declare metadata: CreationOptional<any>;
36
-
37
- declare status: string;
44
+ declare requestEvent: {
45
+ bridger: string;
46
+ metadata: string;
47
+ position: IPosition;
48
+ sourceChainId: number;
49
+ targetChainId: number;
50
+ };
51
+ declare requestSentEvent: CreationOptional<{
52
+ bridger: string;
53
+ metadata: string;
54
+ position: IPosition;
55
+ sourceChainId: number;
56
+ targetChainId: number;
57
+ requestTransactionHash: string;
58
+ }>;
59
+ declare committedEvent: CreationOptional<any>;
60
+ declare completedEvent: CreationOptional<any>;
61
+
62
+ declare status: CreationOptional<string>;
38
63
 
39
64
  declare createdAt: CreationOptional<Date>;
40
65
  declare updatedAt: CreationOptional<Date>;
@@ -47,23 +72,28 @@ Transaction.init({
47
72
  primaryKey: true
48
73
  },
49
74
 
50
- submitTransactionHash: DataTypes.NUMBER,
51
- submitBlockNumber: DataTypes.NUMBER,
75
+ requestTransactionHash: DataTypes.NUMBER,
76
+ requestBlockNumber: DataTypes.NUMBER,
52
77
 
53
78
  transactionHash: DataTypes.STRING,
54
79
  action: DataTypes.STRING,
55
-
56
- from: DataTypes.STRING,
57
- to: DataTypes.STRING,
80
+ bridger: DataTypes.STRING,
58
81
 
59
82
  sourceChainId: DataTypes.NUMBER,
60
83
  sourceTransactionHash: DataTypes.STRING,
61
84
  sourceBlockNumber: DataTypes.NUMBER,
62
- sourceStatus: DataTypes.STRING,
85
+ sourceStatus: {
86
+ type: DataTypes.STRING,
87
+ defaultValue: 'uninitialised'
88
+ },
63
89
  sourceErrors: {
64
90
  type: DataTypes.JSON,
65
91
  // defaultValue: [],
66
92
  },
93
+ sourceLogs: {
94
+ type: DataTypes.JSON,
95
+ // defaultValue: [],
96
+ },
67
97
  sourceCreatedAt: {
68
98
  type: DataTypes.DATE,
69
99
  defaultValue: Date.now()
@@ -73,19 +103,28 @@ Transaction.init({
73
103
  targetChainId: DataTypes.NUMBER,
74
104
  targetTransactionHash: DataTypes.STRING,
75
105
  targetBlockNumber: DataTypes.NUMBER,
76
- targetStatus: DataTypes.STRING,
106
+ targetStatus: {
107
+ type: DataTypes.STRING,
108
+ defaultValue: 'uninitialised'
109
+ },
77
110
  targetErrors: {
78
111
  type: DataTypes.JSON,
79
112
  // defaultValue: [],
80
113
  },
114
+ targetLogs: {
115
+ type: DataTypes.JSON,
116
+ // defaultValue: [],
117
+ },
81
118
  targetCreatedAt: DataTypes.DATE,
82
119
  targetDelayUntil: DataTypes.DATE,
83
120
 
84
- submitEvent: DataTypes.JSON,
85
- sourceEvent: DataTypes.JSON,
86
- targetEvent: DataTypes.JSON,
87
-
88
- metadata: DataTypes.JSON,
121
+ requestEvent: {
122
+ type: DataTypes.JSON,
123
+ allowNull: false
124
+ },
125
+ requestSentEvent: DataTypes.JSON,
126
+ committedEvent: DataTypes.JSON,
127
+ completedEvent: DataTypes.JSON,
89
128
 
90
129
  status: {
91
130
  type: DataTypes.STRING,
@@ -0,0 +1,5 @@
1
+ import withdraw from "./withdraw"
2
+
3
+ export default {
4
+ withdraw,
5
+ }
@@ -0,0 +1,76 @@
1
+ import abi from "@/abi";
2
+ import config from "@/config";
3
+ import { addresses, tokens } from "@/constants";
4
+ import { Transaction } from "@/db";
5
+ import { InteropXContract } from "@/typechain";
6
+ import { ChainId } from "@/types";
7
+ import { getContract, getRpcProviderUrl } from "@/utils";
8
+ import { ethers } from "ethers";
9
+ import { MetaTransaction, OperationType } from "ethers-multisend";
10
+
11
+ export default async function (transaction: Transaction, type: 'source' | 'target') {
12
+ const transactions: MetaTransaction[] = [];
13
+ const logs: any[] = [];
14
+
15
+ if (transaction.action !== 'withdraw') {
16
+ throw new Error(`Invalid action: ${transaction.action}`)
17
+ }
18
+
19
+ if (type !== 'source') {
20
+ throw new Error(`[WIP] Type not supported: ${type}`)
21
+ }
22
+
23
+ if (transaction.sourceStatus === 'pending') {
24
+ throw Error('Source transaction already processesing')
25
+ }
26
+
27
+ if (transaction.sourceStatus === 'pending') {
28
+ throw Error('Source transaction already processed')
29
+ }
30
+
31
+ if (!transaction.requestEvent) {
32
+ throw Error('Something went wrong, source transaction has no request event')
33
+ }
34
+
35
+ const { bridger, position, sourceChainId, targetChainId, metadata, } = transaction.requestEvent;
36
+
37
+ const sourceChainProvider = new ethers.providers.JsonRpcProvider(getRpcProviderUrl(targetChainId as ChainId));
38
+ const sourceWallet = new ethers.Wallet(config.privateKey, sourceChainProvider);
39
+ const contractAddress = addresses[sourceChainId].interopXContract;
40
+ const contract = getContract<InteropXContract>(contractAddress, abi.interopXContract, sourceWallet);
41
+
42
+ const sourceToken = tokens[sourceChainId].find( t => t.address.toLowerCase() === position.withdraw[0].sourceToken.toLowerCase());
43
+
44
+ if(!sourceToken) {
45
+ throw Error('Source token not found')
46
+ }
47
+
48
+ const targetToken = tokens[targetChainId].find( t => t.address.toLowerCase() === position.withdraw[0].targetToken.toLowerCase());
49
+
50
+ if(!targetToken) {
51
+ throw Error('Target token not found')
52
+ }
53
+
54
+ if(sourceToken.aliases.some(alias => targetToken.aliases.includes(alias))) {
55
+ throw Error('Source and target token must be the same')
56
+ }
57
+
58
+ const { data } = await contract.populateTransaction.withdrawRequested(
59
+ bridger,
60
+ position.withdraw[0].sourceToken,
61
+ position.withdraw[0].targetToken,
62
+ position.withdraw[0].amount,
63
+ targetChainId,
64
+ transaction.requestTransactionHash,
65
+ metadata,
66
+ );
67
+
68
+ transactions.push({
69
+ to: contractAddress,
70
+ data: data!,
71
+ value: '0',
72
+ operation: OperationType.Call,
73
+ });
74
+
75
+ return { transactions, logs }
76
+ }
@@ -0,0 +1,19 @@
1
+ import { Transaction } from "@/db";
2
+ import { encodeMulti } from "ethers-multisend";
3
+ import actions from "./actions";
4
+
5
+ export const buildGnosisAction = async (transaction: Transaction, type: 'source' | 'target') => {
6
+ // type = type || (transaction.sourceStatus === 'success' ? 'target' : 'source')
7
+
8
+ if (actions.hasOwnProperty(transaction.action)) {
9
+
10
+ const { transactions, logs } = await actions[transaction.action](transaction, type);
11
+
12
+ return {
13
+ data: encodeMulti(transactions).data,
14
+ logs
15
+ };
16
+ }
17
+
18
+ throw new Error(`Unknown action: ${transaction.action}`);
19
+ }
package/src/index.ts CHANGED
@@ -1,23 +1,9 @@
1
- import moduleAlias from 'module-alias';
2
-
3
- moduleAlias.addAliases({
4
- "@/": __dirname + "/",
5
- "@/logger": __dirname + "/logger",
6
- "@/tasks": __dirname + "/tasks",
7
- "@/utils": __dirname + "/utils",
8
- "@/api": __dirname + "/api",
9
- "@/net": __dirname + "/net",
10
- "@/db": __dirname + "/db",
11
- "@/config": __dirname + "/config",
12
- "@/types": __dirname + "/types",
13
- "@/abi": __dirname + "/abi",
14
- "@/constants": __dirname + "/constants",
15
- "@/typechain": __dirname + "/typechain"
16
- })
1
+ import './alias'
2
+ import expandHomeDir from "expand-home-dir";
3
+ import fs from 'fs-extra'
17
4
 
18
- moduleAlias();
19
- import assert from "assert";
20
5
  import dotenv from "dotenv";
6
+ import chalk from 'chalk';
21
7
  import { ethers } from "ethers";
22
8
  import packageJson from '../package.json'
23
9
  dotenv.config();
@@ -25,28 +11,77 @@ dotenv.config();
25
11
  import Logger from "@/logger";
26
12
  const logger = new Logger('Process')
27
13
 
14
+ const GIT_SHORT_HASH = '@GIT_SHORT_HASH@';
15
+
16
+ const printUsage = () => {
17
+ console.log()
18
+ console.log(`Interop X Node (v${packageJson.version} - rev.${GIT_SHORT_HASH})`)
19
+ console.log()
28
20
 
29
- if (process.argv.at(-1) === 'help') {
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
+
25
+ console.log()
26
+
27
+ console.log(' interop-x down Put the node into maintenance mode')
28
+ console.log(' interop-x up Take the node out of maintenance mode')
29
+
30
+ console.log()
31
+
32
+ console.log(' PRIVATE_KEY=abcd1234 interop-x Start the node with the given private key')
33
+ console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x Start the node in staging mode')
34
+ console.log(' PRIVATE_KEY=abcd1234 AUTO_UPDATE=true interop-x Start the node in auto update mode')
35
+ 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')
36
+ console.log()
37
+
38
+ }
39
+
40
+ if (process.argv.at(-1) === 'help') {
41
+ printUsage()
42
+ process.exit(0)
43
+ }
44
+
45
+ const basePath = expandHomeDir(`~/.interop-x`);
46
+
47
+ if (process.argv.at(-1) === 'down') {
48
+ fs.outputFileSync(basePath + '/maintenance', Date.now().toString())
49
+ console.log(chalk.red('Maintenance mode enabled'))
50
+ process.exit(0)
51
+ }
52
+
53
+ if (process.argv.at(-1) === 'up') {
54
+ fs.removeSync(basePath + '/maintenance')
55
+ console.log(chalk.green('Maintenance mode disabled'))
33
56
  process.exit(0)
34
57
  }
35
58
 
36
- assert(process.env.PRIVATE_KEY, "PRIVATE_KEY is not defined");
37
59
 
60
+ if (process.argv.at(-1) === 'version') {
61
+ console.log(`Interop X Node (v${packageJson.version} - rev.${GIT_SHORT_HASH})`)
62
+ process.exit(0)
63
+ }
64
+
65
+ if (!process.env.PRIVATE_KEY) {
66
+ console.error(chalk.bgRed.white.bold('Please provide a private key\n'))
67
+ printUsage()
68
+ process.exit(1)
69
+ }
38
70
  try {
39
71
  new ethers.Wallet(process.env.PRIVATE_KEY!)
40
72
  } catch (e) {
41
- logger.error('Invalid private key')
73
+ console.error(chalk.bgRed.white('Invalid private key\n'))
74
+ printUsage()
42
75
  process.exit(1)
43
76
  }
44
77
 
45
- logger.debug(`Starting Interop X Node (v${packageJson.version} - rev.@GIT_SHORT_HASH@)`)
78
+ logger.debug(`Starting Interop X Node (v${packageJson.version} - rev.${GIT_SHORT_HASH})`)
46
79
 
47
80
  import { Tasks } from "@/tasks";
48
- import { startPeer } from "@/net";
81
+ import { startPeer, protocol, peerPool } from "@/net";
49
82
  import { startApiServer } from '@/api';
83
+ import { Transaction } from './db';
84
+ import { shortenHash } from './utils';
50
85
 
51
86
  async function main() {
52
87
 
@@ -54,9 +89,44 @@ async function main() {
54
89
 
55
90
  const tasks = new Tasks()
56
91
 
57
- tasks.start();
92
+ setTimeout(() => {
93
+ tasks.start();
94
+ }, 10000)
58
95
 
59
96
  startApiServer()
97
+
98
+ protocol.on('TransactionStatus', async (payload) => {
99
+ if (!peerPool.isLeadNode(payload.peerId)) {
100
+ const peer = peerPool.getPeer(payload.peerId)
101
+
102
+ if (!peer) {
103
+ return;
104
+ }
105
+
106
+ logger.info(`ignored transaction status from ${payload.peerId} ${shortenHash(peer.publicAddress)} `)
107
+ return;
108
+ }
109
+
110
+ const transaction = await Transaction.findOne({ where: { transactionHash: payload.data.transactionHash } })
111
+
112
+ if (!transaction) {
113
+ return;
114
+ }
115
+
116
+ transaction.sourceStatus = payload.data.sourceStatus
117
+ transaction.sourceTransactionHash = payload.data.sourceTransactionHash
118
+ transaction.sourceErrors = payload.data.sourceErrors
119
+ transaction.sourceLogs = payload.data.sourceLogs
120
+
121
+ transaction.targetStatus = payload.data.targetStatus
122
+ transaction.targetTransactionHash = payload.data.targetTransactionHash
123
+ transaction.targetErrors = payload.data.targetErrors
124
+ transaction.targetLogs = payload.data.targetLogs
125
+
126
+ transaction.status = payload.data.status
127
+
128
+ await transaction.save()
129
+ })
60
130
  }
61
131
 
62
132
  main()
@@ -17,6 +17,7 @@ import KadDHT from "libp2p-kad-dht";
17
17
  import PubsubPeerDiscovery from "libp2p-pubsub-peer-discovery";
18
18
  import { protocol } from "@/net";
19
19
  import config from "@/config";
20
+ import chalk from "chalk";
20
21
 
21
22
  const logger = new Logger("Peer");
22
23
 
@@ -80,7 +81,7 @@ export const startPeer = async ({ }: IPeerOptions) => {
80
81
  },
81
82
  });
82
83
 
83
- logger.info("Peer ID:", node.peerId.toB58String());
84
+ logger.info("Peer ID:", chalk.bold(node.peerId.toB58String()));
84
85
 
85
86
  await node.start();
86
87
 
@@ -1,6 +1,9 @@
1
1
  import { Event } from "@/types";
2
2
  import config from "@/config";
3
3
  import Logger from "@/logger";
4
+ import { getAddress } from "ethers/lib/utils";
5
+ import { shortenHash } from "@/utils";
6
+ import chalk from "chalk";
4
7
 
5
8
 
6
9
  const logger = new Logger('PeerPool')
@@ -83,10 +86,10 @@ export class PeerPool {
83
86
  const newPeer = !this.pool.get(peer.id);
84
87
  this.pool.set(peer.id, peer)
85
88
  peer.pooled = true
86
-
87
- if(newPeer) {
89
+
90
+ if (newPeer) {
88
91
  config.events.emit(Event.POOL_PEER_ADDED, peer)
89
- logger.info(`Peer ${peer.id} with address ${peer.publicAddress} added to pool`)
92
+ logger.info(`Peer ${chalk.bold(shortenHash(peer.id, 16))} with address ${chalk.bold(shortenHash(peer.publicAddress))} added to pool`)
90
93
  }
91
94
  }
92
95
  }
@@ -101,7 +104,7 @@ export class PeerPool {
101
104
  if (this.pool.delete(peer.id)) {
102
105
  peer.pooled = false
103
106
  config.events.emit(Event.POOL_PEER_REMOVED, peer)
104
- logger.info(`Peer ${peer.id} with address ${peer.publicAddress} removed from pool`)
107
+ logger.info(`Peer ${chalk.bold(shortenHash(peer.id, 16))} with address ${chalk.bold(shortenHash(peer.publicAddress))} removed from pool`)
105
108
  }
106
109
  }
107
110
  }
@@ -110,7 +113,7 @@ export class PeerPool {
110
113
  this.cleanup()
111
114
 
112
115
  return this.peers.filter((p) => {
113
- if(!p.pooled) return false;
116
+ if (!p.pooled) return false;
114
117
 
115
118
  const now = new Date()
116
119
 
@@ -122,16 +125,33 @@ export class PeerPool {
122
125
  return this.activePeers.map((p) => p.id)
123
126
  }
124
127
 
128
+ getPeer(id: string){
129
+ return this.pool.get(id);
130
+ }
125
131
 
126
- cleanup() {
127
- let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
132
+ isLeadNode(id: string) {
133
+ const peer = this.pool.get(id);
128
134
 
129
- this.peers.forEach((peerInfo) => {
130
- if (peerInfo.updated.getTime() < compDate) {
131
- console.log(`Peer ${peerInfo.id} idle for ${this.PEERS_CLEANUP_TIME_LIMIT} minutes`)
132
- this.remove(peerInfo)
133
- }
134
- })
135
+ if (!peer) {
136
+ return false;
137
+ }
138
+
139
+ return getAddress(peer.publicAddress) === getAddress(config.leadNodeAddress)
140
+ }
141
+
142
+ getLeadPeer() {
143
+ return this.peers.find((p) => this.isLeadNode(p.id))
144
+ }
145
+
146
+ cleanup() {
147
+ // let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
148
+
149
+ // this.peers.forEach((peerInfo) => {
150
+ // if (peerInfo.updated.getTime() < compDate) {
151
+ // console.log(`Peer ${peerInfo.id} idle for ${this.PEERS_CLEANUP_TIME_LIMIT} minutes`)
152
+ // this.remove(peerInfo)
153
+ // }
154
+ // })
135
155
  }
136
156
  }
137
157
 
@@ -2,12 +2,13 @@ import { BaseDialProtocol } from "./BaseDialProtocol";
2
2
  import wait from "waait";
3
3
  import config from "@/config";
4
4
  import { Transaction } from "@/db";
5
- import { buildDataForTransaction, signGnosisSafeTx } from "@/utils";
5
+ import { signGnosisSafeTx } from "@/utils";
6
6
  import { addresses } from "@/constants";
7
7
  import { ChainId } from "@/types";
8
+ import { buildGnosisAction } from "@/gnosis";
8
9
 
9
10
  export interface ISignatureRequest {
10
- type: 'source' | 'target' ,
11
+ type: 'source' | 'target',
11
12
  transactionHash: string
12
13
  safeTxGas: string
13
14
  safeNonce: string
@@ -25,6 +26,10 @@ export class SignatureDialProtocol extends BaseDialProtocol<ISignatureRequest, I
25
26
  }
26
27
 
27
28
  async response(data: ISignatureRequest): Promise<ISignatureResponse> {
29
+ console.log({
30
+ tag: 'SignatureDialProtocol',
31
+ data
32
+ })
28
33
  const signer = config.wallet;
29
34
 
30
35
  let transaction: Transaction | null;
@@ -46,13 +51,14 @@ export class SignatureDialProtocol extends BaseDialProtocol<ISignatureRequest, I
46
51
  error: 'Event not found'
47
52
  };
48
53
  }
54
+ const { data: gnosisData } = await buildGnosisAction(transaction, data.type);
49
55
 
50
56
  const signedData = await signGnosisSafeTx({
51
- //TODO: chain id depends on event type
52
57
  to: addresses[transaction.sourceChainId].multisend,
53
- data: buildDataForTransaction(transaction, data.type),
58
+ data: gnosisData,
54
59
  chainId: transaction.sourceChainId as ChainId,
55
60
  safeTxGas: data.safeTxGas,
61
+ nonce: data.safeNonce,
56
62
  }, { signer });
57
63
 
58
64
  return {