@instadapp/interop-x 0.0.0-dev.b3789e6 → 0.0.0-dev.b8c571d

Sign up to get free protection for your applications and to get access to all the features.
Files changed (33) hide show
  1. package/bin/interop-x +1 -1
  2. package/dist/package.json +6 -3
  3. package/dist/src/constants/addresses.js +0 -8
  4. package/dist/src/constants/index.js +1 -0
  5. package/dist/src/constants/itokens.js +13 -0
  6. package/dist/src/db/models/transaction.js +2 -0
  7. package/dist/src/index.js +1 -1
  8. package/dist/src/net/peer/index.js +6 -2
  9. package/dist/src/net/pool/index.js +16 -9
  10. package/dist/src/net/protocol/dial/SignatureDialProtocol.js +22 -12
  11. package/dist/src/tasks/BaseTask.js +1 -1
  12. package/dist/src/tasks/InteropBridge/ProcessWithdrawEvents.js +145 -0
  13. package/dist/src/tasks/InteropBridge/SyncWithdrawEvents.js +70 -0
  14. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +147 -0
  15. package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +14 -5
  16. package/dist/src/tasks/index.js +13 -0
  17. package/dist/src/utils/index.js +124 -2
  18. package/package.json +6 -3
  19. package/patches/@ethersproject+properties+5.6.0.patch +13 -0
  20. package/src/constants/addresses.ts +0 -8
  21. package/src/constants/index.ts +1 -0
  22. package/src/constants/itokens.ts +10 -0
  23. package/src/db/models/transaction.ts +6 -2
  24. package/src/net/peer/index.ts +7 -6
  25. package/src/net/pool/index.ts +20 -10
  26. package/src/net/protocol/dial/SignatureDialProtocol.ts +25 -13
  27. package/src/tasks/BaseTask.ts +1 -1
  28. package/src/tasks/InteropBridge/ProcessWithdrawEvents.ts +231 -0
  29. package/src/tasks/InteropBridge/SyncWithdrawEvents.ts +121 -0
  30. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +241 -0
  31. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +22 -7
  32. package/src/tasks/index.ts +19 -2
  33. package/src/utils/index.ts +175 -3
@@ -4,12 +4,25 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Tasks = void 0;
7
+ const ProcessDepositEvents_1 = __importDefault(require("./InteropXGateway/ProcessDepositEvents"));
7
8
  const SyncDepositEvents_1 = __importDefault(require("./InteropXGateway/SyncDepositEvents"));
9
+ const SyncWithdrawEvents_1 = __importDefault(require("./InteropBridge/SyncWithdrawEvents"));
10
+ const ProcessWithdrawEvents_1 = __importDefault(require("./InteropBridge/ProcessWithdrawEvents"));
8
11
  class Tasks {
9
12
  constructor() {
10
13
  this.tasks = [
11
14
  new SyncDepositEvents_1.default({
12
15
  chainId: 43114
16
+ }),
17
+ new ProcessDepositEvents_1.default({
18
+ chainId: 43114
19
+ }),
20
+ new SyncWithdrawEvents_1.default({
21
+ chainId: 137,
22
+ itokenAddress: '0xEab02fe1F016eE3e4106c1C6aad35FeEe657268E',
23
+ }),
24
+ new ProcessWithdrawEvents_1.default({
25
+ chainId: 137,
13
26
  })
14
27
  ];
15
28
  }
@@ -3,7 +3,7 @@ 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
- exports.generateInteropTransactionHash = exports.asyncCallWithTimeout = exports.buildSignatureBytes = exports.getRpcProviderUrl = exports.signGnosisSafeTx = exports.short = exports.http = void 0;
6
+ exports.getContract = exports.buildWithdrawDataForTransaction = exports.buildDepositDataForTransaction = exports.buildDataForTransaction = exports.generateInteropTransactionHash = exports.asyncCallWithTimeout = exports.buildSignatureBytes = exports.getRpcProviderUrl = exports.signGnosisSafeTx = exports.short = exports.http = void 0;
7
7
  /**
8
8
  * @module util
9
9
  */
@@ -11,6 +11,9 @@ const axios_1 = __importDefault(require("axios"));
11
11
  const axios_retry_1 = __importDefault(require("axios-retry"));
12
12
  const constants_1 = require("@/constants");
13
13
  const ethers_1 = require("ethers");
14
+ const ethers_multisend_1 = require("ethers-multisend");
15
+ const config_1 = __importDefault(require("@/config"));
16
+ const abi_1 = __importDefault(require("@/abi"));
14
17
  exports.http = axios_1.default.create();
15
18
  (0, axios_retry_1.default)(exports.http, { retries: 3, retryDelay: axios_retry_1.default.exponentialDelay });
16
19
  function short(buffer) {
@@ -93,9 +96,128 @@ exports.asyncCallWithTimeout = asyncCallWithTimeout;
93
96
  const generateInteropTransactionHash = (data) => {
94
97
  return ethers_1.ethers.utils.solidityKeccak256(['string', 'string', 'string', 'string'], [
95
98
  String(data.action),
96
- String(data.sourceTransactionHash),
99
+ String(data.submitTransactionHash),
97
100
  String(data.sourceChainId),
98
101
  String(data.targetChainId),
99
102
  ]);
100
103
  };
101
104
  exports.generateInteropTransactionHash = generateInteropTransactionHash;
105
+ const buildDataForTransaction = async (transaction, type) => {
106
+ type = type || transaction.sourceStatus === 'pending' ? 'source' : 'target';
107
+ switch (transaction.action) {
108
+ case "deposit":
109
+ return await (0, exports.buildDepositDataForTransaction)(transaction, type);
110
+ case "withdraw":
111
+ return await (0, exports.buildWithdrawDataForTransaction)(transaction, type);
112
+ default:
113
+ throw new Error(`Unknown action: ${transaction.action}`);
114
+ }
115
+ };
116
+ exports.buildDataForTransaction = buildDataForTransaction;
117
+ const buildDepositDataForTransaction = async (transaction, type) => {
118
+ const transactions = [];
119
+ if (transaction.action !== 'deposit') {
120
+ throw new Error(`Invalid action: ${transaction.action}`);
121
+ }
122
+ if (transaction.action === 'deposit' && transaction.sourceStatus === 'pending') {
123
+ throw Error('Cannot build data for pending deposit transaction');
124
+ }
125
+ if (!transaction.submitEvent) {
126
+ throw Error('Cannot build data for transaction without submitEvent');
127
+ }
128
+ const token = constants_1.tokens[transaction.sourceChainId].find(token => token.address.toLowerCase() === transaction.submitEvent.token.toLowerCase());
129
+ if (!token) {
130
+ throw Error('Cannot build data for transaction without token');
131
+ }
132
+ const itoken = constants_1.itokens[transaction.targetChainId].find(itoken => itoken.symbol.toLowerCase() === token.symbol.toLowerCase());
133
+ if (!itoken) {
134
+ throw Error('Cannot build data for transaction without itoken');
135
+ }
136
+ const targetChainProvider = new ethers_1.ethers.providers.JsonRpcProvider((0, exports.getRpcProviderUrl)(transaction.targetChainId));
137
+ const targetWallet = new ethers_1.ethers.Wallet(config_1.default.privateKey, targetChainProvider);
138
+ const interopBridgeContract = getContract(itoken.address, abi_1.default.interopBridgeToken, targetWallet);
139
+ const { data } = await interopBridgeContract.populateTransaction.mint(transaction.submitEvent.user, ethers_1.ethers.BigNumber.from(transaction.submitEvent.amount.toString()), ethers_1.ethers.BigNumber.from(transaction.submitEvent.sourceChainId.toString()), transaction.submitTransactionHash);
140
+ transactions.push({
141
+ to: itoken.address,
142
+ data: data,
143
+ value: '0',
144
+ operation: ethers_multisend_1.OperationType.Call,
145
+ });
146
+ return (0, ethers_multisend_1.encodeMulti)(transactions).data;
147
+ };
148
+ exports.buildDepositDataForTransaction = buildDepositDataForTransaction;
149
+ const buildWithdrawDataForTransaction = async (transaction, type) => {
150
+ const transactions = [];
151
+ if (transaction.action !== 'withdraw') {
152
+ throw new Error(`Invalid action: ${transaction.action}`);
153
+ }
154
+ if (transaction.action === 'withdraw' && transaction.sourceStatus === 'pending') {
155
+ throw Error('Cannot build data for pending withdraw transaction');
156
+ }
157
+ if (!transaction.submitEvent) {
158
+ throw Error('Cannot build data for transaction without submitEvent');
159
+ }
160
+ const { to, amount, chainId, itoken: itokenAddress } = transaction.submitEvent;
161
+ const itoken = constants_1.itokens[transaction.sourceChainId].find(token => token.address.toLowerCase() === itokenAddress.toLowerCase());
162
+ if (!itoken) {
163
+ throw Error('Cannot build data for transaction without itoken');
164
+ }
165
+ const token = constants_1.tokens[chainId].find(t => t.symbol.toLowerCase() === itoken.symbol.toLowerCase());
166
+ if (!token) {
167
+ throw Error('Cannot build data for transaction without token');
168
+ }
169
+ const targetChainProvider = new ethers_1.ethers.providers.JsonRpcProvider((0, exports.getRpcProviderUrl)(transaction.targetChainId));
170
+ const targetWallet = new ethers_1.ethers.Wallet(config_1.default.privateKey, targetChainProvider);
171
+ const gatewayAddress = constants_1.addresses[chainId].interopXGateway;
172
+ const interopBridgeContract = getContract(gatewayAddress, abi_1.default.interopXGateway, targetWallet);
173
+ const { data } = await interopBridgeContract.populateTransaction.systemWithdraw(ethers_1.ethers.BigNumber.from(amount.toString()), to, token.address, ethers_1.ethers.BigNumber.from(transaction.submitEvent.sourceChainId.toString()), transaction.submitTransactionHash);
174
+ transactions.push({
175
+ to: gatewayAddress,
176
+ data: data,
177
+ value: '0',
178
+ operation: ethers_multisend_1.OperationType.Call,
179
+ });
180
+ return (0, ethers_multisend_1.encodeMulti)(transactions).data;
181
+ };
182
+ exports.buildWithdrawDataForTransaction = buildWithdrawDataForTransaction;
183
+ function getContract(address, contractInterface, signerOrProvider) {
184
+ if (!ethers_1.ethers.utils.getAddress(address) || address === ethers_1.ethers.constants.AddressZero) {
185
+ throw Error(`Invalid 'address' parameter '${address}'.`);
186
+ }
187
+ const contract = new ethers_1.ethers.Contract(address, contractInterface, signerOrProvider);
188
+ return new Proxy(contract, {
189
+ get(target, prop, receiver) {
190
+ const value = Reflect.get(target, prop, receiver);
191
+ if (typeof value === 'function' && (contract.functions.hasOwnProperty(prop) || ['queryFilter'].includes(String(prop)))) {
192
+ return async (...args) => {
193
+ try {
194
+ return await value.bind(contract)(...args);
195
+ }
196
+ catch (error) {
197
+ throw new Error(`Error calling "${String(prop)}" on "${address}": ${error.reason || error.message}`);
198
+ }
199
+ };
200
+ }
201
+ if (typeof value === 'object' && ['populateTransaction', 'estimateGas', 'functions', 'callStatic'].includes(String(prop))) {
202
+ const parentProp = String(prop);
203
+ return new Proxy(value, {
204
+ get(target, prop, receiver) {
205
+ const value = Reflect.get(target, prop, receiver);
206
+ if (typeof value === 'function') {
207
+ return async (...args) => {
208
+ try {
209
+ return await value.bind(contract)(...args);
210
+ }
211
+ catch (error) {
212
+ throw new Error(`Error calling "${String(prop)}" using "${parentProp}" on "${address}": ${error.reason || error.message}`);
213
+ }
214
+ };
215
+ }
216
+ }
217
+ });
218
+ }
219
+ return value;
220
+ },
221
+ });
222
+ }
223
+ exports.getContract = getContract;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instadapp/interop-x",
3
- "version": "0.0.0-dev.b3789e6",
3
+ "version": "0.0.0-dev.b8c571d",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "engines": {
@@ -12,7 +12,8 @@
12
12
  "build": "yarn generate-abi-types && export GIT_REF=$(git rev-parse --short HEAD) && rimraf ./dist && tsc -p tsconfig.json && replace-in-file '@GIT_SHORT_HASH@' $GIT_REF ./dist/**/*.js",
13
13
  "dev": "yarn generate-abi-types && NODE_ENV=development nodemon",
14
14
  "generate-abi-types": "typechain --target=ethers-v5 'src/abi/*.json' --out-dir 'src/typechain'",
15
- "prepublishOnly": "yarn build"
15
+ "prepublishOnly": "yarn build",
16
+ "postinstall": "patch-package"
16
17
  },
17
18
  "nodemonConfig": {
18
19
  "watch": [
@@ -45,7 +46,7 @@
45
46
  "libp2p-websockets": "^0.16.2",
46
47
  "luxon": "^2.3.2",
47
48
  "module-alias": "^2.2.2",
48
- "sequelize": "^6.19.0",
49
+ "sequelize": "6.18.0",
49
50
  "sqlite3": "^5.0.5",
50
51
  "waait": "^1.0.5"
51
52
  },
@@ -59,6 +60,8 @@
59
60
  "@types/fs-extra": "^9.0.13",
60
61
  "@types/node": "^17.0.17",
61
62
  "nodemon": "^2.0.15",
63
+ "patch-package": "^6.4.7",
64
+ "postinstall-postinstall": "^2.1.0",
62
65
  "replace-in-file": "^6.3.2",
63
66
  "rimraf": "^3.0.2",
64
67
  "ts-node": "^10.5.0",
@@ -0,0 +1,13 @@
1
+ diff --git a/node_modules/@ethersproject/properties/lib/index.js b/node_modules/@ethersproject/properties/lib/index.js
2
+ index 41e0b52..4c7a9e3 100644
3
+ --- a/node_modules/@ethersproject/properties/lib/index.js
4
+ +++ b/node_modules/@ethersproject/properties/lib/index.js
5
+ @@ -44,7 +44,7 @@ function defineReadOnly(object, name, value) {
6
+ Object.defineProperty(object, name, {
7
+ enumerable: true,
8
+ value: value,
9
+ - writable: false,
10
+ + writable: true,
11
+ });
12
+ }
13
+ exports.defineReadOnly = defineReadOnly;
@@ -3,23 +3,15 @@ export const addresses = {
3
3
  gnosisSafe: '0x811Bff6eF88dAAA0aD6438386B534A81cE3F160F',
4
4
  multisend: '0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761',
5
5
  interopXGateway: '',
6
- interopBridgeTokens: [],
7
6
  },
8
7
  137: {
9
8
  gnosisSafe: '0x5635d2910e51da33d9DC0422c893CF4F28B69A25',
10
9
  multisend: '0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761',
11
10
  interopXGateway: '',
12
- interopBridgeTokens: [
13
- {
14
- address: '0x6c20F03598d5ABF729348E2868b0ff5e8A48aB1F',
15
- symbol : 'USDC',
16
- }
17
- ],
18
11
  },
19
12
  43114: {
20
13
  gnosisSafe: '0x31d7a5194Fe60AC209Cf1Ce2d539C9A60662Ed6b',
21
14
  multisend: '0x998739BFdAAdde7C933B942a68053933098f9EDa',
22
15
  interopXGateway: '0x8D27758751BA488690974B6Ccfcda771D462945f',
23
- interopBridgeTokens: [],
24
16
  }
25
17
  }
@@ -1,2 +1,3 @@
1
1
  export * from './addresses';
2
2
  export * from './tokens';
3
+ export * from './itokens';
@@ -0,0 +1,10 @@
1
+ export const itokens = {
2
+ 1: [],
3
+ 137: [
4
+ {
5
+ address: '0xEab02fe1F016eE3e4106c1C6aad35FeEe657268E',
6
+ symbol: 'USDC',
7
+ }
8
+ ],
9
+ 43114: []
10
+ };
@@ -9,10 +9,12 @@ export class Transaction extends Model<InferAttributes<Transaction>, InferCreati
9
9
  declare from: string;
10
10
  declare to: string;
11
11
 
12
+ declare submitTransactionHash: string;
13
+ declare submitBlockNumber: number;
12
14
 
13
15
  declare sourceChainId: number;
14
- declare sourceTransactionHash: string;
15
- declare sourceBlockNumber: number;
16
+ declare sourceTransactionHash: CreationOptional<string>;
17
+ declare sourceBlockNumber: CreationOptional<number>;
16
18
  declare sourceStatus: string;
17
19
  declare sourceErrors: CreationOptional<string[]>;
18
20
  declare sourceCreatedAt: CreationOptional<Date>;
@@ -45,6 +47,8 @@ Transaction.init({
45
47
  primaryKey: true
46
48
  },
47
49
 
50
+ submitTransactionHash: DataTypes.NUMBER,
51
+ submitBlockNumber: DataTypes.NUMBER,
48
52
 
49
53
  transactionHash: DataTypes.STRING,
50
54
  action: DataTypes.STRING,
@@ -88,12 +88,13 @@ export const startPeer = async ({ }: IPeerOptions) => {
88
88
  libp2p: node
89
89
  })
90
90
 
91
- node.on("peer:discovery", (peer) =>
92
- logger.log(`Discovered peer ${peer}`)
93
- ); // peer disc.
94
- node.connectionManager.on("peer:connect", (connection) =>
95
- logger.log(`Connected to ${connection.remotePeer.toB58String()}`)
96
- );
91
+ node.on("peer:discovery", (peer) => {
92
+ // logger.log(`Discovered peer ${peer}`)
93
+ }); // peer disc.
94
+
95
+ node.connectionManager.on("peer:connect", (connection) => {
96
+ // logger.log(`Connected to ${connection.remotePeer.toB58String()}`)
97
+ });
97
98
 
98
99
  logger.log("Peer discovery started");
99
100
 
@@ -1,5 +1,9 @@
1
1
  import { Event } from "@/types";
2
2
  import config from "@/config";
3
+ import Logger from "@/logger";
4
+
5
+
6
+ const logger = new Logger('PeerPool')
3
7
 
4
8
  export interface IPeerInfo {
5
9
  id: string;
@@ -75,10 +79,15 @@ export class PeerPool {
75
79
  * @emits {@link Event.POOL_PEER_ADDED}
76
80
  */
77
81
  add(peer?: IPeerInfo) {
78
- if (peer && peer.id && !this.pool.get(peer.id)) {
82
+ if (peer && peer.id) {
83
+ const newPeer = !this.pool.get(peer.id);
79
84
  this.pool.set(peer.id, peer)
80
85
  peer.pooled = true
81
- config.events.emit(Event.POOL_PEER_ADDED, peer)
86
+
87
+ if(newPeer) {
88
+ config.events.emit(Event.POOL_PEER_ADDED, peer)
89
+ logger.info(`Peer ${peer.id} with address ${peer.publicAddress} added to pool`)
90
+ }
82
91
  }
83
92
  }
84
93
 
@@ -92,6 +101,7 @@ export class PeerPool {
92
101
  if (this.pool.delete(peer.id)) {
93
102
  peer.pooled = false
94
103
  config.events.emit(Event.POOL_PEER_REMOVED, peer)
104
+ logger.info(`Peer ${peer.id} with address ${peer.publicAddress} removed from pool`)
95
105
  }
96
106
  }
97
107
  }
@@ -114,14 +124,14 @@ export class PeerPool {
114
124
 
115
125
 
116
126
  cleanup() {
117
- let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
118
-
119
- this.peers.forEach((peerInfo) => {
120
- if (peerInfo.updated.getTime() < compDate) {
121
- console.log(`Peer ${peerInfo.id} idle for ${this.PEERS_CLEANUP_TIME_LIMIT} minutes`)
122
- this.remove(peerInfo)
123
- }
124
- })
127
+ // let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
128
+
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
+ // })
125
135
  }
126
136
  }
127
137
 
@@ -2,9 +2,12 @@ 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";
6
+ import { addresses } from "@/constants";
7
+ import { ChainId } from "@/types";
5
8
 
6
9
  export interface ISignatureRequest {
7
- type: string,
10
+ type: 'source' | 'target' ,
8
11
  transactionHash: string
9
12
  safeTxGas: string
10
13
  safeNonce: string
@@ -24,19 +27,19 @@ export class SignatureDialProtocol extends BaseDialProtocol<ISignatureRequest, I
24
27
  async response(data: ISignatureRequest): Promise<ISignatureResponse> {
25
28
  const signer = config.wallet;
26
29
 
27
- let event: Transaction | null;
30
+ let transaction: Transaction | null;
28
31
  let maxTimeout = 20000;
29
32
 
30
33
  do {
31
- event = await Transaction.findOne({ where: { transactionHash: data.transactionHash } })
34
+ transaction = await Transaction.findOne({ where: { transactionHash: data.transactionHash } })
32
35
 
33
- if (!event) {
36
+ if (!transaction) {
34
37
  await wait(1000);
35
38
  maxTimeout -= 1000;
36
39
  }
37
- } while (!event && maxTimeout > 0)
40
+ } while (!transaction && maxTimeout > 0)
38
41
 
39
- if (!event) {
42
+ if (!transaction) {
40
43
  return {
41
44
  signer: signer.address,
42
45
  data: null,
@@ -44,16 +47,25 @@ export class SignatureDialProtocol extends BaseDialProtocol<ISignatureRequest, I
44
47
  };
45
48
  }
46
49
 
47
- // const signedData = await signGnosisSafeTx({
48
- // to: addresses[event.chainId as ChainId].multisend,
49
- // data: 'TODO',
50
- // chainId: event.chainId as ChainId,
51
- // safeTxGas: data.safeTxGas,
52
- // }, { signer });
50
+ console.log("signing:", {
51
+ to: addresses[transaction.targetChainId].multisend,
52
+ data: await buildDataForTransaction(transaction, data.type),
53
+ chainId: transaction.targetChainId as ChainId,
54
+ safeTxGas: data.safeTxGas,
55
+ nonce: data.safeNonce,
56
+ });
57
+
58
+ const signedData = await signGnosisSafeTx({
59
+ to: addresses[transaction.targetChainId].multisend,
60
+ data: await buildDataForTransaction(transaction, data.type),
61
+ chainId: transaction.targetChainId as ChainId,
62
+ safeTxGas: data.safeTxGas,
63
+ nonce: data.safeNonce,
64
+ }, { signer });
53
65
 
54
66
  return {
55
67
  signer: signer.address,
56
- data: null, //signedData,
68
+ data: signedData
57
69
  }
58
70
  }
59
71
  }
@@ -37,7 +37,7 @@ export class BaseTask extends EventEmitter implements IBaseTask {
37
37
  await this.pollHandler()
38
38
  }
39
39
  } catch (err) {
40
- this.logger.error(`poll check error: ${err.message}\ntrace: ${err.stack}`)
40
+ this.logger.error(`poll check error:\n${err.message}\ntrace: ${err.stack}`)
41
41
  }
42
42
 
43
43
  await this.postPollHandler()