@instadapp/interop-x 0.0.0-dev.051cd4e
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.
- package/.env.example +2 -0
- package/.github/workflows/publish-dev.yml +30 -0
- package/README.md +21 -0
- package/bin/interop-x +2 -0
- package/dist/package.json +72 -0
- package/dist/src/abi/erc20.json +350 -0
- package/dist/src/abi/gnosisSafe.json +747 -0
- package/dist/src/abi/index.js +15 -0
- package/dist/src/abi/interopBridgeToken.json +286 -0
- package/dist/src/abi/interopXGateway.json +184 -0
- package/dist/src/api/index.js +33 -0
- package/dist/src/config/index.js +22 -0
- package/dist/src/constants/addresses.js +20 -0
- package/dist/src/constants/index.js +19 -0
- package/dist/src/constants/itokens.js +13 -0
- package/dist/src/constants/tokens.js +107 -0
- package/dist/src/db/index.js +17 -0
- package/dist/src/db/models/index.js +17 -0
- package/dist/src/db/models/transaction.js +54 -0
- package/dist/src/db/sequelize.js +23 -0
- package/dist/src/index.js +103 -0
- package/dist/src/logger/index.js +138 -0
- package/dist/src/net/index.js +19 -0
- package/dist/src/net/peer/index.js +108 -0
- package/dist/src/net/pool/index.js +125 -0
- package/dist/src/net/protocol/dial/BaseDialProtocol.js +106 -0
- package/dist/src/net/protocol/dial/SignatureDialProtocol.js +56 -0
- package/dist/src/net/protocol/index.js +121 -0
- package/dist/src/tasks/AutoUpdateTask.js +45 -0
- package/dist/src/tasks/BaseTask.js +61 -0
- package/dist/src/tasks/InteropBridge/ProcessWithdrawEvents.js +147 -0
- package/dist/src/tasks/InteropBridge/SyncWithdrawEvents.js +70 -0
- package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +150 -0
- package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +75 -0
- package/dist/src/tasks/index.js +42 -0
- package/dist/src/typechain/Erc20.js +2 -0
- package/dist/src/typechain/GnosisSafe.js +2 -0
- package/dist/src/typechain/InteropBridgeToken.js +2 -0
- package/dist/src/typechain/InteropXGateway.js +2 -0
- package/dist/src/typechain/common.js +2 -0
- package/dist/src/typechain/factories/Erc20__factory.js +367 -0
- package/dist/src/typechain/factories/GnosisSafe__factory.js +1174 -0
- package/dist/src/typechain/factories/InteropBridgeToken__factory.js +459 -0
- package/dist/src/typechain/factories/InteropXGateway__factory.js +265 -0
- package/dist/src/typechain/factories/index.js +14 -0
- package/dist/src/typechain/index.js +35 -0
- package/dist/src/types.js +21 -0
- package/dist/src/utils/index.js +228 -0
- package/package.json +72 -0
- package/patches/@ethersproject+properties+5.6.0.patch +13 -0
- package/src/abi/erc20.json +350 -0
- package/src/abi/gnosisSafe.json +747 -0
- package/src/abi/index.ts +11 -0
- package/src/abi/interopBridgeToken.json +286 -0
- package/src/abi/interopXGateway.json +184 -0
- package/src/api/index.ts +33 -0
- package/src/config/index.ts +32 -0
- package/src/constants/addresses.ts +17 -0
- package/src/constants/index.ts +3 -0
- package/src/constants/itokens.ts +10 -0
- package/src/constants/tokens.ts +104 -0
- package/src/db/index.ts +1 -0
- package/src/db/models/index.ts +1 -0
- package/src/db/models/transaction.ts +96 -0
- package/src/db/sequelize.ts +22 -0
- package/src/index.ts +123 -0
- package/src/logger/index.ts +157 -0
- package/src/net/index.ts +3 -0
- package/src/net/peer/index.ts +120 -0
- package/src/net/pool/index.ts +154 -0
- package/src/net/protocol/dial/BaseDialProtocol.ts +104 -0
- package/src/net/protocol/dial/SignatureDialProtocol.ts +71 -0
- package/src/net/protocol/index.ts +182 -0
- package/src/tasks/AutoUpdateTask.ts +54 -0
- package/src/tasks/BaseTask.ts +75 -0
- package/src/tasks/InteropBridge/ProcessWithdrawEvents.ts +233 -0
- package/src/tasks/InteropBridge/SyncWithdrawEvents.ts +121 -0
- package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +245 -0
- package/src/tasks/InteropXGateway/SyncDepositEvents.ts +126 -0
- package/src/tasks/index.ts +41 -0
- package/src/typechain/Erc20.ts +491 -0
- package/src/typechain/GnosisSafe.ts +1728 -0
- package/src/typechain/InteropBridgeToken.ts +686 -0
- package/src/typechain/InteropXGateway.ts +407 -0
- package/src/typechain/common.ts +44 -0
- package/src/typechain/factories/Erc20__factory.ts +368 -0
- package/src/typechain/factories/GnosisSafe__factory.ts +1178 -0
- package/src/typechain/factories/InteropBridgeToken__factory.ts +466 -0
- package/src/typechain/factories/InteropXGateway__factory.ts +272 -0
- package/src/typechain/factories/index.ts +7 -0
- package/src/typechain/index.ts +12 -0
- package/src/types.ts +39 -0
- package/src/utils/index.ts +307 -0
- package/tsconfig.json +30 -0
@@ -0,0 +1,125 @@
|
|
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.peerPool = exports.PeerPool = void 0;
|
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 logger = new logger_1.default('PeerPool');
|
12
|
+
class PeerPool {
|
13
|
+
constructor() {
|
14
|
+
this.PEERS_CLEANUP_TIME_LIMIT = 1;
|
15
|
+
this.pool = new Map();
|
16
|
+
config_1.default.events.on(types_1.Event.PEER_CONNECTED, (peer) => {
|
17
|
+
this.connected(peer);
|
18
|
+
});
|
19
|
+
config_1.default.events.on(types_1.Event.PEER_DISCONNECTED, (peer) => {
|
20
|
+
this.disconnected(peer);
|
21
|
+
});
|
22
|
+
}
|
23
|
+
/**
|
24
|
+
* Connected peers
|
25
|
+
*/
|
26
|
+
get peers() {
|
27
|
+
const connectedPeers = Array.from(this.pool.values());
|
28
|
+
return connectedPeers;
|
29
|
+
}
|
30
|
+
/**
|
31
|
+
* Number of peers in pool
|
32
|
+
*/
|
33
|
+
get size() {
|
34
|
+
return this.peers.length;
|
35
|
+
}
|
36
|
+
/**
|
37
|
+
* Return true if pool contains the specified peer
|
38
|
+
* @param peer peer object or id
|
39
|
+
*/
|
40
|
+
contains(peer) {
|
41
|
+
if (typeof peer !== 'string') {
|
42
|
+
peer = peer.id;
|
43
|
+
}
|
44
|
+
return !!this.pool.get(peer);
|
45
|
+
}
|
46
|
+
/**
|
47
|
+
* Handler for peer connections
|
48
|
+
* @param peer peer
|
49
|
+
*/
|
50
|
+
connected(peer) {
|
51
|
+
if (this.size >= config_1.default.maxPeers)
|
52
|
+
return;
|
53
|
+
this.add(peer);
|
54
|
+
}
|
55
|
+
/**
|
56
|
+
* Handler for peer disconnections
|
57
|
+
* @param peer peer
|
58
|
+
*/
|
59
|
+
disconnected(peer) {
|
60
|
+
this.remove(peer);
|
61
|
+
}
|
62
|
+
/**
|
63
|
+
* Add peer to pool
|
64
|
+
* @param peer peer
|
65
|
+
* @emits {@link Event.POOL_PEER_ADDED}
|
66
|
+
*/
|
67
|
+
add(peer) {
|
68
|
+
if (peer && peer.id) {
|
69
|
+
const newPeer = !this.pool.get(peer.id);
|
70
|
+
this.pool.set(peer.id, peer);
|
71
|
+
peer.pooled = true;
|
72
|
+
if (newPeer) {
|
73
|
+
config_1.default.events.emit(types_1.Event.POOL_PEER_ADDED, peer);
|
74
|
+
logger.info(`Peer ${peer.id} with address ${peer.publicAddress} added to pool`);
|
75
|
+
}
|
76
|
+
}
|
77
|
+
}
|
78
|
+
/**
|
79
|
+
* Remove peer from pool
|
80
|
+
* @param peer peer
|
81
|
+
* @emits {@link Event.POOL_PEER_REMOVED}
|
82
|
+
*/
|
83
|
+
remove(peer) {
|
84
|
+
if (peer && peer.id) {
|
85
|
+
if (this.pool.delete(peer.id)) {
|
86
|
+
peer.pooled = false;
|
87
|
+
config_1.default.events.emit(types_1.Event.POOL_PEER_REMOVED, peer);
|
88
|
+
logger.info(`Peer ${peer.id} with address ${peer.publicAddress} removed from pool`);
|
89
|
+
}
|
90
|
+
}
|
91
|
+
}
|
92
|
+
get activePeers() {
|
93
|
+
this.cleanup();
|
94
|
+
return this.peers.filter((p) => {
|
95
|
+
if (!p.pooled)
|
96
|
+
return false;
|
97
|
+
const now = new Date();
|
98
|
+
return (now.getTime() - p.updated.getTime()) < 1000 * 10; // 10 seconds
|
99
|
+
});
|
100
|
+
}
|
101
|
+
get activePeerIds() {
|
102
|
+
return this.activePeers.map((p) => p.id);
|
103
|
+
}
|
104
|
+
getPeer(id) {
|
105
|
+
return this.pool.get(id);
|
106
|
+
}
|
107
|
+
isLeadNode(id) {
|
108
|
+
const peer = this.pool.get(id);
|
109
|
+
if (!peer) {
|
110
|
+
return false;
|
111
|
+
}
|
112
|
+
return (0, utils_1.getAddress)(peer.publicAddress) === (0, utils_1.getAddress)(config_1.default.leadNodeAddress);
|
113
|
+
}
|
114
|
+
cleanup() {
|
115
|
+
// let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
|
116
|
+
// this.peers.forEach((peerInfo) => {
|
117
|
+
// if (peerInfo.updated.getTime() < compDate) {
|
118
|
+
// console.log(`Peer ${peerInfo.id} idle for ${this.PEERS_CLEANUP_TIME_LIMIT} minutes`)
|
119
|
+
// this.remove(peerInfo)
|
120
|
+
// }
|
121
|
+
// })
|
122
|
+
}
|
123
|
+
}
|
124
|
+
exports.PeerPool = PeerPool;
|
125
|
+
exports.peerPool = new PeerPool();
|
@@ -0,0 +1,106 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __asyncValues = (this && this.__asyncValues) || function (o) {
|
3
|
+
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
4
|
+
var m = o[Symbol.asyncIterator], i;
|
5
|
+
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
|
6
|
+
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
|
7
|
+
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
8
|
+
};
|
9
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
10
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
11
|
+
};
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
13
|
+
exports.BaseDialProtocol = void 0;
|
14
|
+
const it_pipe_1 = __importDefault(require("it-pipe"));
|
15
|
+
const peer_id_1 = __importDefault(require("peer-id"));
|
16
|
+
const utils_1 = require("@/utils");
|
17
|
+
const waait_1 = __importDefault(require("waait"));
|
18
|
+
class BaseDialProtocol {
|
19
|
+
constructor(libp2p, protocol) {
|
20
|
+
this.timeout = 20000;
|
21
|
+
this.libp2p = libp2p;
|
22
|
+
this.protocol = protocol;
|
23
|
+
this.libp2p.handle(this.protocol, this.handle.bind(this));
|
24
|
+
}
|
25
|
+
encode(data) {
|
26
|
+
return JSON.stringify(data);
|
27
|
+
}
|
28
|
+
encodeResponse(data) {
|
29
|
+
return JSON.stringify(data);
|
30
|
+
}
|
31
|
+
decode(data) {
|
32
|
+
return JSON.parse(data.toString());
|
33
|
+
}
|
34
|
+
decodeResponse(data) {
|
35
|
+
return JSON.parse(data.toString());
|
36
|
+
}
|
37
|
+
async response(data) {
|
38
|
+
return data;
|
39
|
+
}
|
40
|
+
async handle({ connection, stream }) {
|
41
|
+
const instance = this;
|
42
|
+
try {
|
43
|
+
await (0, it_pipe_1.default)(stream, async function (source) {
|
44
|
+
var e_1, _a;
|
45
|
+
try {
|
46
|
+
for (var source_1 = __asyncValues(source), source_1_1; source_1_1 = await source_1.next(), !source_1_1.done;) {
|
47
|
+
const message = source_1_1.value;
|
48
|
+
const response = instance.encodeResponse(await instance.response(instance.decode(message)));
|
49
|
+
await (0, it_pipe_1.default)([response], stream);
|
50
|
+
}
|
51
|
+
}
|
52
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
53
|
+
finally {
|
54
|
+
try {
|
55
|
+
if (source_1_1 && !source_1_1.done && (_a = source_1.return)) await _a.call(source_1);
|
56
|
+
}
|
57
|
+
finally { if (e_1) throw e_1.error; }
|
58
|
+
}
|
59
|
+
});
|
60
|
+
}
|
61
|
+
catch (err) {
|
62
|
+
console.error(err);
|
63
|
+
}
|
64
|
+
}
|
65
|
+
async send(data, peerId) {
|
66
|
+
return await (0, utils_1.asyncCallWithTimeout)(new Promise(async (resolve, reject) => {
|
67
|
+
try {
|
68
|
+
let connection = this.libp2p.connectionManager.get(peer_id_1.default.createFromB58String(peerId));
|
69
|
+
if (!connection) {
|
70
|
+
await (0, waait_1.default)(5000);
|
71
|
+
connection = this.libp2p.connectionManager.get(peer_id_1.default.createFromB58String(peerId));
|
72
|
+
if (!connection) {
|
73
|
+
await (0, waait_1.default)(3000);
|
74
|
+
connection = this.libp2p.connectionManager.get(peer_id_1.default.createFromB58String(peerId));
|
75
|
+
if (!connection) {
|
76
|
+
throw new Error('No connection available');
|
77
|
+
}
|
78
|
+
}
|
79
|
+
}
|
80
|
+
const { stream } = await connection.newStream([this.protocol]);
|
81
|
+
const instance = this;
|
82
|
+
(0, it_pipe_1.default)([this.encode(data)], stream, async function (source) {
|
83
|
+
var e_2, _a;
|
84
|
+
try {
|
85
|
+
for (var source_2 = __asyncValues(source), source_2_1; source_2_1 = await source_2.next(), !source_2_1.done;) {
|
86
|
+
const message = source_2_1.value;
|
87
|
+
resolve(instance.decodeResponse(message));
|
88
|
+
stream.close();
|
89
|
+
}
|
90
|
+
}
|
91
|
+
catch (e_2_1) { e_2 = { error: e_2_1 }; }
|
92
|
+
finally {
|
93
|
+
try {
|
94
|
+
if (source_2_1 && !source_2_1.done && (_a = source_2.return)) await _a.call(source_2);
|
95
|
+
}
|
96
|
+
finally { if (e_2) throw e_2.error; }
|
97
|
+
}
|
98
|
+
});
|
99
|
+
}
|
100
|
+
catch (error) {
|
101
|
+
reject(error);
|
102
|
+
}
|
103
|
+
}), this.timeout);
|
104
|
+
}
|
105
|
+
}
|
106
|
+
exports.BaseDialProtocol = BaseDialProtocol;
|
@@ -0,0 +1,56 @@
|
|
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.SignatureDialProtocol = void 0;
|
7
|
+
const BaseDialProtocol_1 = require("./BaseDialProtocol");
|
8
|
+
const waait_1 = __importDefault(require("waait"));
|
9
|
+
const config_1 = __importDefault(require("@/config"));
|
10
|
+
const db_1 = require("@/db");
|
11
|
+
const utils_1 = require("@/utils");
|
12
|
+
const constants_1 = require("@/constants");
|
13
|
+
class SignatureDialProtocol extends BaseDialProtocol_1.BaseDialProtocol {
|
14
|
+
constructor(libp2p) {
|
15
|
+
super(libp2p, '/interop-x/signatures');
|
16
|
+
this.timeout = 30000;
|
17
|
+
}
|
18
|
+
async response(data) {
|
19
|
+
const signer = config_1.default.wallet;
|
20
|
+
let transaction;
|
21
|
+
let maxTimeout = 20000;
|
22
|
+
do {
|
23
|
+
transaction = await db_1.Transaction.findOne({ where: { transactionHash: data.transactionHash } });
|
24
|
+
if (!transaction) {
|
25
|
+
await (0, waait_1.default)(1000);
|
26
|
+
maxTimeout -= 1000;
|
27
|
+
}
|
28
|
+
} while (!transaction && maxTimeout > 0);
|
29
|
+
if (!transaction) {
|
30
|
+
return {
|
31
|
+
signer: signer.address,
|
32
|
+
data: null,
|
33
|
+
error: 'Event not found'
|
34
|
+
};
|
35
|
+
}
|
36
|
+
console.log("signing:", {
|
37
|
+
to: constants_1.addresses[transaction.targetChainId].multisend,
|
38
|
+
data: await (0, utils_1.buildDataForTransaction)(transaction, data.type),
|
39
|
+
chainId: transaction.targetChainId,
|
40
|
+
safeTxGas: data.safeTxGas,
|
41
|
+
nonce: data.safeNonce,
|
42
|
+
});
|
43
|
+
const signedData = await (0, utils_1.signGnosisSafeTx)({
|
44
|
+
to: constants_1.addresses[transaction.targetChainId].multisend,
|
45
|
+
data: await (0, utils_1.buildDataForTransaction)(transaction, data.type),
|
46
|
+
chainId: transaction.targetChainId,
|
47
|
+
safeTxGas: data.safeTxGas,
|
48
|
+
nonce: data.safeNonce,
|
49
|
+
}, { signer });
|
50
|
+
return {
|
51
|
+
signer: signer.address,
|
52
|
+
data: signedData
|
53
|
+
};
|
54
|
+
}
|
55
|
+
}
|
56
|
+
exports.SignatureDialProtocol = SignatureDialProtocol;
|
@@ -0,0 +1,121 @@
|
|
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.protocol = void 0;
|
7
|
+
const stream_1 = require("stream");
|
8
|
+
const ethereumjs_util_1 = require("ethereumjs-util");
|
9
|
+
const SignatureDialProtocol_1 = require("./dial/SignatureDialProtocol");
|
10
|
+
const __1 = require("..");
|
11
|
+
const config_1 = __importDefault(require("@/config"));
|
12
|
+
const types_1 = require("@/types");
|
13
|
+
class Protocol extends stream_1.EventEmitter {
|
14
|
+
constructor() {
|
15
|
+
super(...arguments);
|
16
|
+
this.protocolMessages = [
|
17
|
+
{
|
18
|
+
name: 'PeerInfo',
|
19
|
+
code: 0x01,
|
20
|
+
encode: (info) => [
|
21
|
+
Buffer.from(info.publicAddress),
|
22
|
+
],
|
23
|
+
decode: ([publicAddress]) => ({
|
24
|
+
publicAddress: publicAddress.toString(),
|
25
|
+
}),
|
26
|
+
},
|
27
|
+
{
|
28
|
+
name: 'TransactionStatus',
|
29
|
+
code: 0x02,
|
30
|
+
encode: (transaction) => [
|
31
|
+
Buffer.from(transaction.transactionHash),
|
32
|
+
Buffer.from(transaction.sourceStatus),
|
33
|
+
Buffer.from(transaction.sourceTransactionHash),
|
34
|
+
transaction.sourceErrors ? transaction.sourceErrors.map((e) => Buffer.from(e)) : [],
|
35
|
+
Buffer.from(transaction.targetStatus),
|
36
|
+
Buffer.from(transaction.targetTransactionHash),
|
37
|
+
transaction.targetErrors ? transaction.targetErrors.map((e) => Buffer.from(e)) : [],
|
38
|
+
Buffer.from(transaction.status),
|
39
|
+
],
|
40
|
+
decode: ([transactionHash, sourceStatus, sourceTransactionHash, sourceErrors, targetStatus, targetTransactionHash, targetErrors, status]) => ({
|
41
|
+
transactionHash: transactionHash.toString(),
|
42
|
+
sourceStatus: sourceStatus.toString(),
|
43
|
+
sourceTransactionHash: sourceTransactionHash.toString(),
|
44
|
+
sourceErrors: sourceErrors.map((e) => e.toString()),
|
45
|
+
targetStatus: targetStatus.toString(),
|
46
|
+
targetTransactionHash: targetTransactionHash.toString(),
|
47
|
+
targetErrors: targetErrors.map((e) => e.toString()),
|
48
|
+
status: status.toString(),
|
49
|
+
}),
|
50
|
+
},
|
51
|
+
];
|
52
|
+
}
|
53
|
+
start({ libp2p, topic = null, }) {
|
54
|
+
this.libp2p = libp2p;
|
55
|
+
this.topic = topic || 'itnerop-x-protocol';
|
56
|
+
if (this.libp2p.isStarted())
|
57
|
+
this.init();
|
58
|
+
this.on('PeerInfo', (payload) => {
|
59
|
+
config_1.default.events.emit(types_1.Event.PEER_CONNECTED, {
|
60
|
+
id: payload.peerId,
|
61
|
+
publicAddress: payload.data.publicAddress,
|
62
|
+
pooled: false,
|
63
|
+
updated: new Date(),
|
64
|
+
});
|
65
|
+
});
|
66
|
+
this.signature = new SignatureDialProtocol_1.SignatureDialProtocol(this.libp2p);
|
67
|
+
}
|
68
|
+
init() {
|
69
|
+
this.libp2p.pubsub.subscribe(this.topic);
|
70
|
+
this.libp2p.pubsub.on(this.topic, (message) => {
|
71
|
+
try {
|
72
|
+
const [codeBuf, payload] = ethereumjs_util_1.rlp.decode(message.data);
|
73
|
+
const code = (0, ethereumjs_util_1.bufferToInt)(codeBuf);
|
74
|
+
const protocolMessage = this.protocolMessages.find((m) => m.code === code);
|
75
|
+
if (!protocolMessage) {
|
76
|
+
return;
|
77
|
+
}
|
78
|
+
const decoded = protocolMessage.decode(payload);
|
79
|
+
this.emit(protocolMessage.name, {
|
80
|
+
peerId: message.from,
|
81
|
+
name: protocolMessage.name,
|
82
|
+
code: protocolMessage.code,
|
83
|
+
data: decoded
|
84
|
+
});
|
85
|
+
this.emit('all', {
|
86
|
+
peerId: message.from,
|
87
|
+
name: protocolMessage.name,
|
88
|
+
code: protocolMessage.code,
|
89
|
+
data: decoded,
|
90
|
+
});
|
91
|
+
}
|
92
|
+
catch (err) {
|
93
|
+
console.error(err);
|
94
|
+
}
|
95
|
+
});
|
96
|
+
}
|
97
|
+
sendPeerInfo(data) {
|
98
|
+
const message = this.protocolMessages.find((m) => m.name === 'PeerInfo');
|
99
|
+
const encoded = ethereumjs_util_1.rlp.encode([message.code, message.encode(data)]);
|
100
|
+
this.libp2p.pubsub.publish(this.topic, encoded);
|
101
|
+
}
|
102
|
+
sendTransaction(transaction) {
|
103
|
+
const message = this.protocolMessages.find((m) => m.name === 'TransactionStatus');
|
104
|
+
const encoded = ethereumjs_util_1.rlp.encode([message.code, message.encode(transaction)]);
|
105
|
+
this.libp2p.pubsub.publish(this.topic, encoded);
|
106
|
+
}
|
107
|
+
async requestSignatures(data, peerIds) {
|
108
|
+
try {
|
109
|
+
peerIds = peerIds || __1.peerPool.activePeerIds;
|
110
|
+
const promises = peerIds.map((peerId) => this.signature.send(data, peerId));
|
111
|
+
return (await Promise.allSettled(promises))
|
112
|
+
.map((p) => p.status === 'fulfilled' ? p.value : null)
|
113
|
+
.filter(Boolean);
|
114
|
+
}
|
115
|
+
catch (error) {
|
116
|
+
console.log(error);
|
117
|
+
return [];
|
118
|
+
}
|
119
|
+
}
|
120
|
+
}
|
121
|
+
exports.protocol = new Protocol();
|
@@ -0,0 +1,45 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
|
+
};
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
6
|
+
const BaseTask_1 = require("./BaseTask");
|
7
|
+
const logger_1 = __importDefault(require("@/logger"));
|
8
|
+
const package_json_1 = __importDefault(require("../../package.json"));
|
9
|
+
const utils_1 = require("@/utils");
|
10
|
+
const child_process_1 = require("child_process");
|
11
|
+
const config_1 = __importDefault(require("@/config"));
|
12
|
+
const currentVersion = package_json_1.default.version;
|
13
|
+
class AutoUpdateTask extends BaseTask_1.BaseTask {
|
14
|
+
constructor() {
|
15
|
+
super({
|
16
|
+
logger: new logger_1.default("AutoUpdateTask"),
|
17
|
+
});
|
18
|
+
this.pollIntervalMs = 60 * 1000;
|
19
|
+
}
|
20
|
+
prePollHandler() {
|
21
|
+
return config_1.default.autoUpdate && !config_1.default.isLeadNode();
|
22
|
+
}
|
23
|
+
async pollHandler() {
|
24
|
+
const { data } = await utils_1.http.get('https://registry.npmjs.org/@instadapp/interop-x');
|
25
|
+
const version = data['dist-tags'].latest;
|
26
|
+
if (version === currentVersion) {
|
27
|
+
return;
|
28
|
+
}
|
29
|
+
this.logger.warn(`New version ${version} available.`);
|
30
|
+
const update = (0, child_process_1.spawn)('npm', ['-g', 'install', '@instadapp/interop-x']);
|
31
|
+
update.on("close", () => {
|
32
|
+
this.logger.warn(`Installed version ${version}`);
|
33
|
+
this.logger.warn(`Restarting...`);
|
34
|
+
const restart = (0, child_process_1.spawn)(process.argv[0], process.argv.slice(1), {
|
35
|
+
cwd: process.cwd(),
|
36
|
+
detached: true,
|
37
|
+
stdio: "inherit"
|
38
|
+
});
|
39
|
+
restart.on("close", () => {
|
40
|
+
process.exit();
|
41
|
+
});
|
42
|
+
});
|
43
|
+
}
|
44
|
+
}
|
45
|
+
exports.default = AutoUpdateTask;
|
@@ -0,0 +1,61 @@
|
|
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.BaseTask = void 0;
|
7
|
+
const config_1 = __importDefault(require("@/config"));
|
8
|
+
const events_1 = __importDefault(require("events"));
|
9
|
+
const waait_1 = __importDefault(require("waait"));
|
10
|
+
const logger_1 = __importDefault(require("@/logger"));
|
11
|
+
class BaseTask extends events_1.default {
|
12
|
+
constructor({ logger }) {
|
13
|
+
super();
|
14
|
+
this.started = false;
|
15
|
+
this.pollIntervalMs = 10 * 1000;
|
16
|
+
this.leadNodeOnly = false;
|
17
|
+
this.logger = logger !== null && logger !== void 0 ? logger : new logger_1.default('BaseTask');
|
18
|
+
}
|
19
|
+
async pollCheck() {
|
20
|
+
while (true) {
|
21
|
+
if (!this.started) {
|
22
|
+
return;
|
23
|
+
}
|
24
|
+
try {
|
25
|
+
const shouldPoll = this.prePollHandler();
|
26
|
+
if (shouldPoll) {
|
27
|
+
await this.pollHandler();
|
28
|
+
}
|
29
|
+
}
|
30
|
+
catch (err) {
|
31
|
+
this.logger.error(`poll check error:\n${err.message}\ntrace: ${err.stack}`);
|
32
|
+
}
|
33
|
+
await this.postPollHandler();
|
34
|
+
}
|
35
|
+
}
|
36
|
+
prePollHandler() {
|
37
|
+
if (!this.leadNodeOnly) {
|
38
|
+
return true;
|
39
|
+
}
|
40
|
+
return config_1.default.isLeadNode();
|
41
|
+
}
|
42
|
+
async pollHandler() {
|
43
|
+
this.logger.warn('pollHandler not implemented');
|
44
|
+
}
|
45
|
+
async postPollHandler() {
|
46
|
+
await (0, waait_1.default)(this.pollIntervalMs);
|
47
|
+
}
|
48
|
+
async start() {
|
49
|
+
this.started = true;
|
50
|
+
try {
|
51
|
+
await this.pollCheck();
|
52
|
+
}
|
53
|
+
catch (err) {
|
54
|
+
this.logger.error(`base task error: ${err.message}\ntrace: ${err.stack}`);
|
55
|
+
}
|
56
|
+
}
|
57
|
+
async stop() {
|
58
|
+
this.started = false;
|
59
|
+
}
|
60
|
+
}
|
61
|
+
exports.BaseTask = BaseTask;
|
@@ -0,0 +1,147 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
|
+
};
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
6
|
+
const BaseTask_1 = require("../BaseTask");
|
7
|
+
const logger_1 = __importDefault(require("@/logger"));
|
8
|
+
const ethers_1 = require("ethers");
|
9
|
+
const abi_1 = __importDefault(require("@/abi"));
|
10
|
+
const db_1 = require("@/db");
|
11
|
+
const utils_1 = require("@/utils");
|
12
|
+
const constants_1 = require("@/constants");
|
13
|
+
const config_1 = __importDefault(require("@/config"));
|
14
|
+
const sequelize_1 = require("sequelize");
|
15
|
+
const waait_1 = __importDefault(require("waait"));
|
16
|
+
const net_1 = require("@/net");
|
17
|
+
const generateGnosisTransaction = async (transactionData, safeContract) => {
|
18
|
+
console.log(transactionData);
|
19
|
+
let isExecuted = await safeContract.dataHashes(await safeContract.getTransactionHash(transactionData.to, transactionData.value, transactionData.data, transactionData.operation, transactionData.safeTxGas, transactionData.baseGas, transactionData.gasPrice, transactionData.gasToken, transactionData.refundReceiver, transactionData.nonce));
|
20
|
+
while (isExecuted == 1) {
|
21
|
+
transactionData.safeTxGas = ethers_1.BigNumber.from(String(transactionData.safeTxGas)).add(1).toString();
|
22
|
+
isExecuted = await safeContract.dataHashes(await safeContract.getTransactionHash(transactionData.to, transactionData.value, transactionData.data, transactionData.operation, transactionData.safeTxGas, transactionData.baseGas, transactionData.gasPrice, transactionData.gasToken, transactionData.refundReceiver, transactionData.nonce));
|
23
|
+
}
|
24
|
+
return transactionData;
|
25
|
+
};
|
26
|
+
class ProcessWithdrawEvents extends BaseTask_1.BaseTask {
|
27
|
+
constructor({ chainId }) {
|
28
|
+
super({
|
29
|
+
logger: new logger_1.default("InteropXGateway::ProcessWithdrawEvents"),
|
30
|
+
});
|
31
|
+
this.leadNodeOnly = true;
|
32
|
+
this.chainId = chainId;
|
33
|
+
}
|
34
|
+
async pollHandler() {
|
35
|
+
var _a;
|
36
|
+
const blockNumber = await this.provider.getBlockNumber();
|
37
|
+
const transaction = await db_1.Transaction.findOne({
|
38
|
+
where: {
|
39
|
+
status: 'pending',
|
40
|
+
sourceStatus: 'success',
|
41
|
+
targetStatus: 'uninitialised',
|
42
|
+
action: 'withdraw',
|
43
|
+
sourceCreatedAt: {
|
44
|
+
[sequelize_1.Op.gte]: new Date(Date.now() - 12 * 60 * 60 * 1000),
|
45
|
+
},
|
46
|
+
targetDelayUntil: {
|
47
|
+
[sequelize_1.Op.or]: {
|
48
|
+
[sequelize_1.Op.is]: null,
|
49
|
+
[sequelize_1.Op.lt]: new Date(),
|
50
|
+
}
|
51
|
+
},
|
52
|
+
sourceBlockNumber: {
|
53
|
+
[sequelize_1.Op.lt]: blockNumber - 12,
|
54
|
+
},
|
55
|
+
sourceChainId: this.chainId,
|
56
|
+
}
|
57
|
+
});
|
58
|
+
if (!transaction) {
|
59
|
+
return;
|
60
|
+
}
|
61
|
+
console.log(`Processing transaction ${transaction.transactionHash}`);
|
62
|
+
transaction.targetStatus = 'pending';
|
63
|
+
await transaction.save();
|
64
|
+
// refresh event data?
|
65
|
+
const targetChainProvider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(transaction.targetChainId));
|
66
|
+
const targetWallet = new ethers_1.ethers.Wallet(config_1.default.privateKey, targetChainProvider);
|
67
|
+
const safeAddress = constants_1.addresses[transaction.targetChainId].gnosisSafe;
|
68
|
+
const safeContract = (0, utils_1.getContract)(safeAddress, abi_1.default.gnosisSafe, targetWallet);
|
69
|
+
const ownersThreshold = await safeContract.getThreshold();
|
70
|
+
await (0, waait_1.default)(10000);
|
71
|
+
let gnosisTx = await generateGnosisTransaction({
|
72
|
+
baseGas: "0",
|
73
|
+
data: await (0, utils_1.buildDataForTransaction)(transaction),
|
74
|
+
gasPrice: "0",
|
75
|
+
gasToken: "0x0000000000000000000000000000000000000000",
|
76
|
+
nonce: '0',
|
77
|
+
operation: "1",
|
78
|
+
refundReceiver: "0x0000000000000000000000000000000000000000",
|
79
|
+
safeAddress: safeAddress,
|
80
|
+
safeTxGas: "79668",
|
81
|
+
to: constants_1.addresses[transaction.targetChainId].multisend,
|
82
|
+
value: "0",
|
83
|
+
}, safeContract);
|
84
|
+
const owners = await safeContract.getOwners().then(owners => owners.map(owner => owner.toLowerCase()));
|
85
|
+
const ownerPeerIds = net_1.peerPool.activePeers.filter(peer => owners.includes(peer.publicAddress.toLowerCase())).map(peer => peer.id);
|
86
|
+
console.log(`Collecting signatures for execution ${transaction.transactionHash}`);
|
87
|
+
console.log(ownerPeerIds);
|
88
|
+
const signatures = await net_1.protocol.requestSignatures({
|
89
|
+
type: 'source',
|
90
|
+
transactionHash: transaction.transactionHash,
|
91
|
+
safeTxGas: gnosisTx.safeTxGas,
|
92
|
+
safeNonce: gnosisTx.nonce
|
93
|
+
}, ownerPeerIds);
|
94
|
+
const validSignatures = signatures.filter(s => !!s.data && s.data !== '0x');
|
95
|
+
console.log({ signatures, validSignatures, ownersThreshold: ownersThreshold.toString() });
|
96
|
+
if (validSignatures.length === 0 || ownersThreshold.gt(validSignatures.length)) {
|
97
|
+
await transaction.save();
|
98
|
+
transaction.targetDelayUntil = new Date(Date.now() + 30 * 1000);
|
99
|
+
transaction.targetStatus = 'uninitialised';
|
100
|
+
await transaction.save();
|
101
|
+
const errorMessage = (_a = signatures.find(s => !!s.error)) === null || _a === void 0 ? void 0 : _a.error;
|
102
|
+
throw new Error(`Not enough signatures` + (errorMessage ? `: ${errorMessage}` : ''));
|
103
|
+
}
|
104
|
+
console.log(`Executing transaction for execution ${transaction.transactionHash}`);
|
105
|
+
const { data: txData } = await safeContract.populateTransaction.execTransaction(gnosisTx.to, gnosisTx.value, gnosisTx.data, gnosisTx.operation, gnosisTx.safeTxGas, gnosisTx.baseGas, gnosisTx.gasPrice, gnosisTx.gasToken, gnosisTx.refundReceiver, (0, utils_1.buildSignatureBytes)(validSignatures));
|
106
|
+
console.log({
|
107
|
+
from: targetWallet.address,
|
108
|
+
gasPrice: ethers_1.BigNumber.from(120 * 10 ** 9).toString(),
|
109
|
+
to: safeAddress,
|
110
|
+
data: txData,
|
111
|
+
});
|
112
|
+
const txSent = await targetWallet.sendTransaction({
|
113
|
+
from: targetWallet.address,
|
114
|
+
gasPrice: ethers_1.BigNumber.from(120 * 10 ** 9),
|
115
|
+
to: safeAddress,
|
116
|
+
data: txData,
|
117
|
+
});
|
118
|
+
const receipt = await txSent.wait();
|
119
|
+
const parsedLogs = [];
|
120
|
+
receipt.logs.forEach((log) => {
|
121
|
+
try {
|
122
|
+
parsedLogs.push(safeContract.interface.parseLog(log));
|
123
|
+
}
|
124
|
+
catch (e) { }
|
125
|
+
});
|
126
|
+
if (parsedLogs.find(e => e.name === 'ExecutionSuccess')) {
|
127
|
+
console.log('ExecutionSuccess');
|
128
|
+
transaction.targetStatus = 'success';
|
129
|
+
transaction.targetTransactionHash = txSent.hash;
|
130
|
+
transaction.status = 'success';
|
131
|
+
await transaction.save();
|
132
|
+
}
|
133
|
+
else {
|
134
|
+
console.log('ExecutionFailure');
|
135
|
+
transaction.targetStatus = 'failed';
|
136
|
+
transaction.targetTransactionHash = txSent.hash;
|
137
|
+
transaction.status = 'failed';
|
138
|
+
await transaction.save();
|
139
|
+
}
|
140
|
+
}
|
141
|
+
async start() {
|
142
|
+
this.logger.info(`Starting execution watcher on interop chain`);
|
143
|
+
this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
|
144
|
+
await super.start();
|
145
|
+
}
|
146
|
+
}
|
147
|
+
exports.default = ProcessWithdrawEvents;
|