@instadapp/interop-x 0.0.0-dev.9b1fcb8 → 0.0.0-dev.ab1e84b
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/dist/package.json +4 -3
- package/dist/src/config/index.js +1 -0
- package/dist/src/index.js +40 -5
- package/dist/src/net/pool/index.js +11 -0
- package/dist/src/net/protocol/index.js +30 -1
- package/dist/src/tasks/AutoUpdateTask.js +44 -0
- package/dist/src/tasks/InteropBridge/ProcessWithdrawEvents.js +147 -0
- package/dist/src/tasks/InteropBridge/SyncWithdrawEvents.js +2 -0
- package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +3 -0
- package/dist/src/tasks/index.js +6 -0
- package/dist/src/utils/index.js +55 -5
- package/package.json +4 -3
- package/src/config/index.ts +2 -0
- package/src/index.ts +50 -7
- package/src/net/pool/index.ts +19 -3
- package/src/net/protocol/index.ts +45 -1
- package/src/tasks/AutoUpdateTask.ts +56 -0
- package/src/tasks/InteropBridge/ProcessWithdrawEvents.ts +233 -0
- package/src/tasks/InteropBridge/SyncWithdrawEvents.ts +3 -1
- package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +4 -0
- package/src/tasks/index.ts +9 -0
- package/src/utils/index.ts +73 -4
package/dist/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@instadapp/interop-x",
|
3
|
-
"version": "0.0.0-dev.
|
3
|
+
"version": "0.0.0-dev.ab1e84b",
|
4
4
|
"license": "MIT",
|
5
5
|
"main": "dist/index.js",
|
6
6
|
"engines": {
|
@@ -24,6 +24,7 @@
|
|
24
24
|
},
|
25
25
|
"dependencies": {
|
26
26
|
"@achingbrain/libp2p-gossipsub": "^0.12.2",
|
27
|
+
"await-spawn": "^4.0.2",
|
27
28
|
"axios": "^0.27.1",
|
28
29
|
"axios-retry": "^3.2.4",
|
29
30
|
"bignumber.js": "^9.0.2",
|
@@ -46,6 +47,8 @@
|
|
46
47
|
"libp2p-websockets": "^0.16.2",
|
47
48
|
"luxon": "^2.3.2",
|
48
49
|
"module-alias": "^2.2.2",
|
50
|
+
"patch-package": "^6.4.7",
|
51
|
+
"postinstall-postinstall": "^2.1.0",
|
49
52
|
"sequelize": "6.18.0",
|
50
53
|
"sqlite3": "^5.0.5",
|
51
54
|
"waait": "^1.0.5"
|
@@ -60,8 +63,6 @@
|
|
60
63
|
"@types/fs-extra": "^9.0.13",
|
61
64
|
"@types/node": "^17.0.17",
|
62
65
|
"nodemon": "^2.0.15",
|
63
|
-
"patch-package": "^6.4.7",
|
64
|
-
"postinstall-postinstall": "^2.1.0",
|
65
66
|
"replace-in-file": "^6.3.2",
|
66
67
|
"rimraf": "^3.0.2",
|
67
68
|
"ts-node": "^10.5.0",
|
package/dist/src/config/index.js
CHANGED
@@ -8,6 +8,7 @@ class Config {
|
|
8
8
|
this.maxPeers = 10;
|
9
9
|
this.privateKey = process.env.PRIVATE_KEY;
|
10
10
|
this.staging = !!process.env.STAGING && process.env.STAGING === 'true';
|
11
|
+
this.autoUpdate = !!process.env.AUTO_UPDATE && process.env.AUTO_UPDATE === 'true';
|
11
12
|
this.wallet = new ethers_1.Wallet(this.privateKey);
|
12
13
|
this.leadNodeAddress = '0x910E413DBF3F6276Fe8213fF656726bDc142E08E';
|
13
14
|
}
|
package/dist/src/index.js
CHANGED
@@ -19,36 +19,71 @@ module_alias_1.default.addAliases({
|
|
19
19
|
"@/typechain": __dirname + "/typechain"
|
20
20
|
});
|
21
21
|
(0, module_alias_1.default)();
|
22
|
-
const assert_1 = __importDefault(require("assert"));
|
23
22
|
const dotenv_1 = __importDefault(require("dotenv"));
|
23
|
+
const chalk_1 = __importDefault(require("chalk"));
|
24
24
|
const ethers_1 = require("ethers");
|
25
25
|
const package_json_1 = __importDefault(require("../package.json"));
|
26
26
|
dotenv_1.default.config();
|
27
27
|
const logger_1 = __importDefault(require("@/logger"));
|
28
28
|
const logger = new logger_1.default('Process');
|
29
|
-
|
29
|
+
const printUsage = () => {
|
30
30
|
console.log('Usage:');
|
31
31
|
console.log(' PRIVATE_KEY=abcd1234 interop-x');
|
32
32
|
console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x');
|
33
|
+
console.log(' PRIVATE_KEY=abcd1234 AUTO_UPDATE=true interop-x');
|
34
|
+
console.log(' PRIVATE_KEY=abcd1234 API_HOST=0.0.0.0 API_PORT=8080 interop-x');
|
35
|
+
};
|
36
|
+
if (process.argv.at(-1) === 'help') {
|
37
|
+
printUsage();
|
33
38
|
process.exit(0);
|
34
39
|
}
|
35
|
-
|
40
|
+
const GIT_SHORT_HASH = 'ab1e84b';
|
41
|
+
if (process.argv.at(-1) === 'version') {
|
42
|
+
console.log(`Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
|
43
|
+
process.exit(0);
|
44
|
+
}
|
45
|
+
if (!process.env.PRIVATE_KEY) {
|
46
|
+
console.error(chalk_1.default.bgRed.white.bold('Please provide a private key\n'));
|
47
|
+
printUsage();
|
48
|
+
process.exit(1);
|
49
|
+
}
|
36
50
|
try {
|
37
51
|
new ethers_1.ethers.Wallet(process.env.PRIVATE_KEY);
|
38
52
|
}
|
39
53
|
catch (e) {
|
40
|
-
|
54
|
+
console.error(chalk_1.default.bgRed.white('Invalid private key\n'));
|
55
|
+
printUsage();
|
41
56
|
process.exit(1);
|
42
57
|
}
|
43
|
-
logger.debug(`Starting Interop X Node (v${package_json_1.default.version} - rev
|
58
|
+
logger.debug(`Starting Interop X Node (v${package_json_1.default.version} - rev.${GIT_SHORT_HASH})`);
|
44
59
|
const tasks_1 = require("@/tasks");
|
45
60
|
const net_1 = require("@/net");
|
46
61
|
const api_1 = require("@/api");
|
62
|
+
const db_1 = require("./db");
|
47
63
|
async function main() {
|
48
64
|
(0, net_1.startPeer)({});
|
49
65
|
const tasks = new tasks_1.Tasks();
|
50
66
|
tasks.start();
|
51
67
|
(0, api_1.startApiServer)();
|
68
|
+
net_1.protocol.on('TransactionStatus', async (payload) => {
|
69
|
+
if (!net_1.peerPool.isLeadNode(payload.peerId)) {
|
70
|
+
const peer = net_1.peerPool.getPeer(payload.peerId);
|
71
|
+
logger.info(`ignored transaction status from ${payload.peerId} ${peer === null || peer === void 0 ? void 0 : peer.publicAddress} `);
|
72
|
+
return;
|
73
|
+
}
|
74
|
+
const transaction = await db_1.Transaction.findOne({ where: { transactionHash: payload.data.transactionHash } });
|
75
|
+
if (!transaction) {
|
76
|
+
return;
|
77
|
+
}
|
78
|
+
transaction.sourceStatus = payload.data.sourceStatus;
|
79
|
+
transaction.sourceTransactionHash = payload.data.sourceTransactionHash;
|
80
|
+
transaction.sourceErrors = payload.data.sourceErrors;
|
81
|
+
transaction.targetStatus = payload.data.targetStatus;
|
82
|
+
transaction.targetTransactionHash = payload.data.targetTransactionHash;
|
83
|
+
transaction.targetErrors = payload.data.targetErrors;
|
84
|
+
transaction.status = payload.data.status;
|
85
|
+
await transaction.save();
|
86
|
+
});
|
52
87
|
}
|
53
88
|
main()
|
54
89
|
.then(() => {
|
@@ -7,6 +7,7 @@ exports.peerPool = exports.PeerPool = void 0;
|
|
7
7
|
const types_1 = require("@/types");
|
8
8
|
const config_1 = __importDefault(require("@/config"));
|
9
9
|
const logger_1 = __importDefault(require("@/logger"));
|
10
|
+
const utils_1 = require("ethers/lib/utils");
|
10
11
|
const logger = new logger_1.default('PeerPool');
|
11
12
|
class PeerPool {
|
12
13
|
constructor() {
|
@@ -100,6 +101,16 @@ class PeerPool {
|
|
100
101
|
get activePeerIds() {
|
101
102
|
return this.activePeers.map((p) => p.id);
|
102
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
|
+
}
|
103
114
|
cleanup() {
|
104
115
|
// let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
|
105
116
|
// this.peers.forEach((peerInfo) => {
|
@@ -16,7 +16,7 @@ class Protocol extends stream_1.EventEmitter {
|
|
16
16
|
this.protocolMessages = [
|
17
17
|
{
|
18
18
|
name: 'PeerInfo',
|
19
|
-
code:
|
19
|
+
code: 0x01,
|
20
20
|
encode: (info) => [
|
21
21
|
Buffer.from(info.publicAddress),
|
22
22
|
],
|
@@ -24,6 +24,30 @@ class Protocol extends stream_1.EventEmitter {
|
|
24
24
|
publicAddress: publicAddress.toString(),
|
25
25
|
}),
|
26
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
|
+
},
|
27
51
|
];
|
28
52
|
}
|
29
53
|
start({ libp2p, topic = null, }) {
|
@@ -75,6 +99,11 @@ class Protocol extends stream_1.EventEmitter {
|
|
75
99
|
const encoded = ethereumjs_util_1.rlp.encode([message.code, message.encode(data)]);
|
76
100
|
this.libp2p.pubsub.publish(this.topic, encoded);
|
77
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
|
+
}
|
78
107
|
async requestSignatures(data, peerIds) {
|
79
108
|
try {
|
80
109
|
peerIds = peerIds || __1.peerPool.activePeerIds;
|
@@ -0,0 +1,44 @@
|
|
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 await_spawn_1 = __importDefault(require("await-spawn"));
|
11
|
+
const config_1 = __importDefault(require("@/config"));
|
12
|
+
const waait_1 = __importDefault(require("waait"));
|
13
|
+
const currentVersion = package_json_1.default.version;
|
14
|
+
class AutoUpdateTask extends BaseTask_1.BaseTask {
|
15
|
+
constructor() {
|
16
|
+
super({
|
17
|
+
logger: new logger_1.default("AutoUpdateTask"),
|
18
|
+
});
|
19
|
+
this.pollIntervalMs = 60 * 1000;
|
20
|
+
}
|
21
|
+
prePollHandler() {
|
22
|
+
return config_1.default.autoUpdate && !config_1.default.isLeadNode();
|
23
|
+
}
|
24
|
+
async pollHandler() {
|
25
|
+
const { data } = await utils_1.http.get('https://registry.npmjs.org/@instadapp/interop-x');
|
26
|
+
const version = data['dist-tags'].latest;
|
27
|
+
if (version === currentVersion) {
|
28
|
+
return;
|
29
|
+
}
|
30
|
+
this.logger.warn(`New version ${version} available.`);
|
31
|
+
await (0, await_spawn_1.default)('npm', ['-g', 'install', '@instadapp/interop-x']);
|
32
|
+
this.logger.warn(`Installed version ${version}`);
|
33
|
+
this.logger.warn(`Restarting...`);
|
34
|
+
await (0, waait_1.default)(1000);
|
35
|
+
console.log(process.argv[0], process.argv.slice(1));
|
36
|
+
(0, await_spawn_1.default)(process.argv[0], process.argv.slice(1), {
|
37
|
+
cwd: process.cwd(),
|
38
|
+
detached: true,
|
39
|
+
stdio: "inherit"
|
40
|
+
});
|
41
|
+
process.exit();
|
42
|
+
}
|
43
|
+
}
|
44
|
+
exports.default = AutoUpdateTask;
|
@@ -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;
|
@@ -43,10 +43,12 @@ class SyncWithdrawEvents extends BaseTask_1.BaseTask {
|
|
43
43
|
sourceTransactionHash: event.transactionHash, sourceBlockNumber: event.blockNumber, sourceStatus: "success", targetStatus: "uninitialised", submitEvent: {
|
44
44
|
to,
|
45
45
|
amount: amount.toString(),
|
46
|
+
itoken: this.itokenAddress,
|
46
47
|
chainId: chainId.toString()
|
47
48
|
}, sourceEvent: {
|
48
49
|
to,
|
49
50
|
amount: amount.toString(),
|
51
|
+
itoken: this.itokenAddress,
|
50
52
|
chainId: chainId.toString(),
|
51
53
|
}, status: "pending" }));
|
52
54
|
this.logger.info(`Withdraw queued: ${event.transactionHash} ${event.blockNumber}`);
|
@@ -126,15 +126,18 @@ class ProcessDepositEvents extends BaseTask_1.BaseTask {
|
|
126
126
|
if (parsedLogs.find(e => e.name === 'ExecutionSuccess')) {
|
127
127
|
console.log('ExecutionSuccess');
|
128
128
|
transaction.targetStatus = 'success';
|
129
|
+
transaction.targetTransactionHash = txSent.hash;
|
129
130
|
transaction.status = 'success';
|
130
131
|
await transaction.save();
|
131
132
|
}
|
132
133
|
else {
|
133
134
|
console.log('ExecutionFailure');
|
134
135
|
transaction.targetStatus = 'failed';
|
136
|
+
transaction.targetTransactionHash = txSent.hash;
|
135
137
|
transaction.status = 'failed';
|
136
138
|
await transaction.save();
|
137
139
|
}
|
140
|
+
net_1.protocol.sendTransaction(transaction);
|
138
141
|
}
|
139
142
|
async start() {
|
140
143
|
this.logger.info(`Starting execution watcher on interop chain`);
|
package/dist/src/tasks/index.js
CHANGED
@@ -7,9 +7,12 @@ exports.Tasks = void 0;
|
|
7
7
|
const ProcessDepositEvents_1 = __importDefault(require("./InteropXGateway/ProcessDepositEvents"));
|
8
8
|
const SyncDepositEvents_1 = __importDefault(require("./InteropXGateway/SyncDepositEvents"));
|
9
9
|
const SyncWithdrawEvents_1 = __importDefault(require("./InteropBridge/SyncWithdrawEvents"));
|
10
|
+
const ProcessWithdrawEvents_1 = __importDefault(require("./InteropBridge/ProcessWithdrawEvents"));
|
11
|
+
const AutoUpdateTask_1 = __importDefault(require("./AutoUpdateTask"));
|
10
12
|
class Tasks {
|
11
13
|
constructor() {
|
12
14
|
this.tasks = [
|
15
|
+
new AutoUpdateTask_1.default(),
|
13
16
|
new SyncDepositEvents_1.default({
|
14
17
|
chainId: 43114
|
15
18
|
}),
|
@@ -19,6 +22,9 @@ class Tasks {
|
|
19
22
|
new SyncWithdrawEvents_1.default({
|
20
23
|
chainId: 137,
|
21
24
|
itokenAddress: '0xEab02fe1F016eE3e4106c1C6aad35FeEe657268E',
|
25
|
+
}),
|
26
|
+
new ProcessWithdrawEvents_1.default({
|
27
|
+
chainId: 137,
|
22
28
|
})
|
23
29
|
];
|
24
30
|
}
|
package/dist/src/utils/index.js
CHANGED
@@ -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.getContract = exports.buildDataForTransaction = 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
|
*/
|
@@ -104,9 +104,20 @@ const generateInteropTransactionHash = (data) => {
|
|
104
104
|
exports.generateInteropTransactionHash = generateInteropTransactionHash;
|
105
105
|
const buildDataForTransaction = async (transaction, type) => {
|
106
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) => {
|
107
118
|
const transactions = [];
|
108
|
-
if (transaction.action
|
109
|
-
throw new Error(
|
119
|
+
if (transaction.action !== 'deposit') {
|
120
|
+
throw new Error(`Invalid action: ${transaction.action}`);
|
110
121
|
}
|
111
122
|
if (transaction.action === 'deposit' && transaction.sourceStatus === 'pending') {
|
112
123
|
throw Error('Cannot build data for pending deposit transaction');
|
@@ -125,7 +136,7 @@ const buildDataForTransaction = async (transaction, type) => {
|
|
125
136
|
const targetChainProvider = new ethers_1.ethers.providers.JsonRpcProvider((0, exports.getRpcProviderUrl)(transaction.targetChainId));
|
126
137
|
const targetWallet = new ethers_1.ethers.Wallet(config_1.default.privateKey, targetChainProvider);
|
127
138
|
const interopBridgeContract = getContract(itoken.address, abi_1.default.interopBridgeToken, targetWallet);
|
128
|
-
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.
|
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);
|
129
140
|
transactions.push({
|
130
141
|
to: itoken.address,
|
131
142
|
data: data,
|
@@ -134,12 +145,51 @@ const buildDataForTransaction = async (transaction, type) => {
|
|
134
145
|
});
|
135
146
|
return (0, ethers_multisend_1.encodeMulti)(transactions).data;
|
136
147
|
};
|
137
|
-
exports.
|
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.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;
|
138
183
|
function getContract(address, contractInterface, signerOrProvider) {
|
139
184
|
if (!ethers_1.ethers.utils.getAddress(address) || address === ethers_1.ethers.constants.AddressZero) {
|
140
185
|
throw Error(`Invalid 'address' parameter '${address}'.`);
|
141
186
|
}
|
142
187
|
const contract = new ethers_1.ethers.Contract(address, contractInterface, signerOrProvider);
|
188
|
+
// Make sure the contract properties is writable
|
189
|
+
const desc = Object.getOwnPropertyDescriptor(contract, 'functions');
|
190
|
+
if (!desc || desc.writable !== true) {
|
191
|
+
return contract;
|
192
|
+
}
|
143
193
|
return new Proxy(contract, {
|
144
194
|
get(target, prop, receiver) {
|
145
195
|
const value = Reflect.get(target, prop, receiver);
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@instadapp/interop-x",
|
3
|
-
"version": "0.0.0-dev.
|
3
|
+
"version": "0.0.0-dev.ab1e84b",
|
4
4
|
"license": "MIT",
|
5
5
|
"main": "dist/index.js",
|
6
6
|
"engines": {
|
@@ -24,6 +24,7 @@
|
|
24
24
|
},
|
25
25
|
"dependencies": {
|
26
26
|
"@achingbrain/libp2p-gossipsub": "^0.12.2",
|
27
|
+
"await-spawn": "^4.0.2",
|
27
28
|
"axios": "^0.27.1",
|
28
29
|
"axios-retry": "^3.2.4",
|
29
30
|
"bignumber.js": "^9.0.2",
|
@@ -46,6 +47,8 @@
|
|
46
47
|
"libp2p-websockets": "^0.16.2",
|
47
48
|
"luxon": "^2.3.2",
|
48
49
|
"module-alias": "^2.2.2",
|
50
|
+
"patch-package": "^6.4.7",
|
51
|
+
"postinstall-postinstall": "^2.1.0",
|
49
52
|
"sequelize": "6.18.0",
|
50
53
|
"sqlite3": "^5.0.5",
|
51
54
|
"waait": "^1.0.5"
|
@@ -60,8 +63,6 @@
|
|
60
63
|
"@types/fs-extra": "^9.0.13",
|
61
64
|
"@types/node": "^17.0.17",
|
62
65
|
"nodemon": "^2.0.15",
|
63
|
-
"patch-package": "^6.4.7",
|
64
|
-
"postinstall-postinstall": "^2.1.0",
|
65
66
|
"replace-in-file": "^6.3.2",
|
66
67
|
"rimraf": "^3.0.2",
|
67
68
|
"ts-node": "^10.5.0",
|
package/src/config/index.ts
CHANGED
@@ -8,12 +8,14 @@ class Config {
|
|
8
8
|
public readonly privateKey: string
|
9
9
|
public readonly wallet: Wallet
|
10
10
|
public readonly staging: boolean
|
11
|
+
public readonly autoUpdate: boolean
|
11
12
|
|
12
13
|
constructor() {
|
13
14
|
this.events = new EventBus() as EventBusType
|
14
15
|
this.maxPeers = 10
|
15
16
|
this.privateKey = process.env.PRIVATE_KEY as string;
|
16
17
|
this.staging = !! process.env.STAGING && process.env.STAGING === 'true';
|
18
|
+
this.autoUpdate = !! process.env.AUTO_UPDATE && process.env.AUTO_UPDATE === 'true';
|
17
19
|
this.wallet = new Wallet(this.privateKey);
|
18
20
|
this.leadNodeAddress = '0x910E413DBF3F6276Fe8213fF656726bDc142E08E'
|
19
21
|
}
|
package/src/index.ts
CHANGED
@@ -16,8 +16,8 @@ moduleAlias.addAliases({
|
|
16
16
|
})
|
17
17
|
|
18
18
|
moduleAlias();
|
19
|
-
import assert from "assert";
|
20
19
|
import dotenv from "dotenv";
|
20
|
+
import chalk from 'chalk';
|
21
21
|
import { ethers } from "ethers";
|
22
22
|
import packageJson from '../package.json'
|
23
23
|
dotenv.config();
|
@@ -25,28 +25,45 @@ dotenv.config();
|
|
25
25
|
import Logger from "@/logger";
|
26
26
|
const logger = new Logger('Process')
|
27
27
|
|
28
|
-
|
29
|
-
if (process.argv.at(-1) === 'help') {
|
28
|
+
const printUsage = () => {
|
30
29
|
console.log('Usage:')
|
31
30
|
console.log(' PRIVATE_KEY=abcd1234 interop-x')
|
32
31
|
console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x')
|
32
|
+
console.log(' PRIVATE_KEY=abcd1234 AUTO_UPDATE=true interop-x')
|
33
|
+
console.log(' PRIVATE_KEY=abcd1234 API_HOST=0.0.0.0 API_PORT=8080 interop-x')
|
34
|
+
}
|
35
|
+
|
36
|
+
if (process.argv.at(-1) === 'help') {
|
37
|
+
printUsage()
|
33
38
|
process.exit(0)
|
34
39
|
}
|
35
40
|
|
36
|
-
|
41
|
+
const GIT_SHORT_HASH = '@GIT_SHORT_HASH@';
|
37
42
|
|
43
|
+
if (process.argv.at(-1) === 'version') {
|
44
|
+
console.log(`Interop X Node (v${packageJson.version} - rev.${GIT_SHORT_HASH})`)
|
45
|
+
process.exit(0)
|
46
|
+
}
|
47
|
+
|
48
|
+
if(! process.env.PRIVATE_KEY) {
|
49
|
+
console.error(chalk.bgRed.white.bold('Please provide a private key\n'))
|
50
|
+
printUsage()
|
51
|
+
process.exit(1)
|
52
|
+
}
|
38
53
|
try {
|
39
54
|
new ethers.Wallet(process.env.PRIVATE_KEY!)
|
40
55
|
} catch (e) {
|
41
|
-
|
56
|
+
console.error(chalk.bgRed.white('Invalid private key\n'))
|
57
|
+
printUsage()
|
42
58
|
process.exit(1)
|
43
59
|
}
|
44
60
|
|
45
|
-
logger.debug(`Starting Interop X Node (v${packageJson.version} - rev
|
61
|
+
logger.debug(`Starting Interop X Node (v${packageJson.version} - rev.${GIT_SHORT_HASH})`)
|
46
62
|
|
47
63
|
import { Tasks } from "@/tasks";
|
48
|
-
import { startPeer } from "@/net";
|
64
|
+
import { startPeer, protocol, peerPool } from "@/net";
|
49
65
|
import { startApiServer } from '@/api';
|
66
|
+
import { Transaction } from './db';
|
50
67
|
|
51
68
|
async function main() {
|
52
69
|
|
@@ -57,6 +74,32 @@ async function main() {
|
|
57
74
|
tasks.start();
|
58
75
|
|
59
76
|
startApiServer()
|
77
|
+
|
78
|
+
protocol.on('TransactionStatus', async (payload) => {
|
79
|
+
if (!peerPool.isLeadNode(payload.peerId)) {
|
80
|
+
const peer = peerPool.getPeer(payload.peerId)
|
81
|
+
logger.info(`ignored transaction status from ${payload.peerId} ${peer?.publicAddress} `)
|
82
|
+
return;
|
83
|
+
}
|
84
|
+
|
85
|
+
const transaction = await Transaction.findOne({ where: { transactionHash: payload.data.transactionHash } })
|
86
|
+
|
87
|
+
if (!transaction) {
|
88
|
+
return;
|
89
|
+
}
|
90
|
+
|
91
|
+
transaction.sourceStatus = payload.data.sourceStatus
|
92
|
+
transaction.sourceTransactionHash = payload.data.sourceTransactionHash
|
93
|
+
transaction.sourceErrors = payload.data.sourceErrors
|
94
|
+
|
95
|
+
transaction.targetStatus = payload.data.targetStatus
|
96
|
+
transaction.targetTransactionHash = payload.data.targetTransactionHash
|
97
|
+
transaction.targetErrors = payload.data.targetErrors
|
98
|
+
|
99
|
+
transaction.status = payload.data.status
|
100
|
+
|
101
|
+
await transaction.save()
|
102
|
+
})
|
60
103
|
}
|
61
104
|
|
62
105
|
main()
|
package/src/net/pool/index.ts
CHANGED
@@ -1,6 +1,7 @@
|
|
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";
|
4
5
|
|
5
6
|
|
6
7
|
const logger = new Logger('PeerPool')
|
@@ -83,8 +84,8 @@ export class PeerPool {
|
|
83
84
|
const newPeer = !this.pool.get(peer.id);
|
84
85
|
this.pool.set(peer.id, peer)
|
85
86
|
peer.pooled = true
|
86
|
-
|
87
|
-
if(newPeer) {
|
87
|
+
|
88
|
+
if (newPeer) {
|
88
89
|
config.events.emit(Event.POOL_PEER_ADDED, peer)
|
89
90
|
logger.info(`Peer ${peer.id} with address ${peer.publicAddress} added to pool`)
|
90
91
|
}
|
@@ -110,7 +111,7 @@ export class PeerPool {
|
|
110
111
|
this.cleanup()
|
111
112
|
|
112
113
|
return this.peers.filter((p) => {
|
113
|
-
if(!p.pooled) return false;
|
114
|
+
if (!p.pooled) return false;
|
114
115
|
|
115
116
|
const now = new Date()
|
116
117
|
|
@@ -123,6 +124,21 @@ export class PeerPool {
|
|
123
124
|
}
|
124
125
|
|
125
126
|
|
127
|
+
getPeer(id: string){
|
128
|
+
return this.pool.get(id);
|
129
|
+
}
|
130
|
+
|
131
|
+
isLeadNode(id: string) {
|
132
|
+
const peer = this.pool.get(id);
|
133
|
+
|
134
|
+
if (!peer) {
|
135
|
+
return false;
|
136
|
+
}
|
137
|
+
|
138
|
+
return getAddress(peer.publicAddress) === getAddress(config.leadNodeAddress)
|
139
|
+
}
|
140
|
+
|
141
|
+
|
126
142
|
cleanup() {
|
127
143
|
// let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
|
128
144
|
|
@@ -5,6 +5,7 @@ import { SignatureDialProtocol, ISignatureRequest, ISignatureResponse } from "./
|
|
5
5
|
import { IPeerInfo, peerPool } from "..";
|
6
6
|
import config from "@/config";
|
7
7
|
import { Event } from "@/types";
|
8
|
+
import { Transaction } from "@/db";
|
8
9
|
|
9
10
|
export interface ProtocolOptions {
|
10
11
|
/* Handshake timeout in ms (default: 8000) */
|
@@ -33,7 +34,12 @@ interface PeerInfoEvent extends BaseMessageEvent {
|
|
33
34
|
data: Omit<IPeerInfo, 'id' | 'updated' | 'idle' | 'pooled'>
|
34
35
|
}
|
35
36
|
|
37
|
+
interface TransactionStatusEvent extends BaseMessageEvent {
|
38
|
+
data: Pick<Transaction, 'transactionHash' | 'sourceStatus' | 'sourceTransactionHash' | 'sourceErrors' | 'targetStatus' | 'targetTransactionHash' | 'targetErrors' | 'status'>
|
39
|
+
}
|
40
|
+
|
36
41
|
declare interface Protocol {
|
42
|
+
on(event: 'TransactionStatus', listener: (payload: TransactionStatusEvent) => void): this;
|
37
43
|
on(event: 'PeerInfo', listener: (payload: PeerInfoEvent) => void): this;
|
38
44
|
on(event: string, listener: (payload: BaseMessageEvent) => void): this;
|
39
45
|
}
|
@@ -44,7 +50,7 @@ class Protocol extends EventEmitter {
|
|
44
50
|
private protocolMessages: Message[] = [
|
45
51
|
{
|
46
52
|
name: 'PeerInfo',
|
47
|
-
code:
|
53
|
+
code: 0x01,
|
48
54
|
encode: (info: Pick<IPeerInfo, 'publicAddress'>) => [
|
49
55
|
Buffer.from(info.publicAddress),
|
50
56
|
],
|
@@ -52,6 +58,36 @@ class Protocol extends EventEmitter {
|
|
52
58
|
publicAddress: publicAddress.toString(),
|
53
59
|
}),
|
54
60
|
},
|
61
|
+
{
|
62
|
+
name: 'TransactionStatus',
|
63
|
+
code: 0x02,
|
64
|
+
encode: (transaction: Transaction) => [
|
65
|
+
Buffer.from(transaction.transactionHash),
|
66
|
+
|
67
|
+
Buffer.from(transaction.sourceStatus),
|
68
|
+
Buffer.from(transaction.sourceTransactionHash),
|
69
|
+
transaction.sourceErrors ? transaction.sourceErrors.map((e) => Buffer.from(e)) : [],
|
70
|
+
|
71
|
+
Buffer.from(transaction.targetStatus),
|
72
|
+
Buffer.from(transaction.targetTransactionHash),
|
73
|
+
transaction.targetErrors ? transaction.targetErrors.map((e) => Buffer.from(e)) : [],
|
74
|
+
|
75
|
+
Buffer.from(transaction.status),
|
76
|
+
],
|
77
|
+
decode: ([transactionHash, sourceStatus, sourceTransactionHash, sourceErrors, targetStatus, targetTransactionHash, targetErrors, status]: [Buffer, Buffer, Buffer, Buffer[], Buffer, Buffer, Buffer[], Buffer]) => ({
|
78
|
+
transactionHash: transactionHash.toString(),
|
79
|
+
|
80
|
+
sourceStatus: sourceStatus.toString(),
|
81
|
+
sourceTransactionHash: sourceTransactionHash.toString(),
|
82
|
+
sourceErrors: sourceErrors.map((e) => e.toString()),
|
83
|
+
|
84
|
+
targetStatus: targetStatus.toString(),
|
85
|
+
targetTransactionHash: targetTransactionHash.toString(),
|
86
|
+
targetErrors: targetErrors.map((e) => e.toString()),
|
87
|
+
|
88
|
+
status: status.toString(),
|
89
|
+
}),
|
90
|
+
},
|
55
91
|
];
|
56
92
|
private signature: SignatureDialProtocol;
|
57
93
|
|
@@ -121,6 +157,14 @@ class Protocol extends EventEmitter {
|
|
121
157
|
this.libp2p.pubsub.publish(this.topic, encoded)
|
122
158
|
}
|
123
159
|
|
160
|
+
public sendTransaction(transaction: Transaction) {
|
161
|
+
const message = this.protocolMessages.find((m) => m.name === 'TransactionStatus')!
|
162
|
+
|
163
|
+
const encoded = rlp.encode([message.code, message.encode(transaction)]);
|
164
|
+
|
165
|
+
this.libp2p.pubsub.publish(this.topic, encoded)
|
166
|
+
}
|
167
|
+
|
124
168
|
async requestSignatures(data: ISignatureRequest, peerIds?: string[]) {
|
125
169
|
try {
|
126
170
|
peerIds = peerIds || peerPool.activePeerIds;
|
@@ -0,0 +1,56 @@
|
|
1
|
+
import { BaseTask } from "./BaseTask";
|
2
|
+
import Logger from '@/logger';
|
3
|
+
import packageJson from '../../package.json'
|
4
|
+
import { http } from "@/utils";
|
5
|
+
import spawn from 'await-spawn';
|
6
|
+
import config from "@/config";
|
7
|
+
import wait from "waait";
|
8
|
+
const currentVersion = packageJson.version;
|
9
|
+
|
10
|
+
class AutoUpdateTask extends BaseTask {
|
11
|
+
pollIntervalMs: number = 60 * 1000
|
12
|
+
|
13
|
+
constructor() {
|
14
|
+
super({
|
15
|
+
logger: new Logger("AutoUpdateTask"),
|
16
|
+
})
|
17
|
+
}
|
18
|
+
|
19
|
+
prePollHandler(): boolean {
|
20
|
+
return config.autoUpdate && !config.isLeadNode();
|
21
|
+
}
|
22
|
+
|
23
|
+
async pollHandler() {
|
24
|
+
|
25
|
+
const { data } = await http.get('https://registry.npmjs.org/@instadapp/interop-x')
|
26
|
+
|
27
|
+
const version = data['dist-tags'].latest
|
28
|
+
|
29
|
+
if (version === currentVersion) {
|
30
|
+
return;
|
31
|
+
}
|
32
|
+
|
33
|
+
this.logger.warn(`New version ${version} available.`)
|
34
|
+
|
35
|
+
|
36
|
+
await spawn('npm', ['-g', 'install', '@instadapp/interop-x']);
|
37
|
+
|
38
|
+
this.logger.warn(`Installed version ${version}`)
|
39
|
+
this.logger.warn(`Restarting...`)
|
40
|
+
|
41
|
+
await wait(1000)
|
42
|
+
|
43
|
+
console.log(process.argv[0], process.argv.slice(1));
|
44
|
+
|
45
|
+
|
46
|
+
spawn(process.argv[0], process.argv.slice(1), {
|
47
|
+
cwd: process.cwd(),
|
48
|
+
detached: true,
|
49
|
+
stdio: "inherit"
|
50
|
+
});
|
51
|
+
|
52
|
+
process.exit()
|
53
|
+
}
|
54
|
+
}
|
55
|
+
|
56
|
+
export default AutoUpdateTask;
|
@@ -0,0 +1,233 @@
|
|
1
|
+
import { BaseTask } from "../BaseTask";
|
2
|
+
import Logger from '@/logger';
|
3
|
+
import { BigNumber, ethers } from "ethers";
|
4
|
+
import abi from "@/abi";
|
5
|
+
import { Transaction } from "@/db";
|
6
|
+
import { buildDataForTransaction, buildSignatureBytes, getContract, getRpcProviderUrl, Signature } from "@/utils";
|
7
|
+
import { addresses } from "@/constants";
|
8
|
+
import { ChainId } from "@/types";
|
9
|
+
import config from "@/config";
|
10
|
+
import { GnosisSafe, InteropXGateway } from "@/typechain";
|
11
|
+
import { Op } from "sequelize";
|
12
|
+
import wait from "waait";
|
13
|
+
import { peerPool, protocol } from "@/net";
|
14
|
+
import { LogDescription } from "ethers/lib/utils";
|
15
|
+
|
16
|
+
const generateGnosisTransaction = async (transactionData: any, safeContract: GnosisSafe) => {
|
17
|
+
console.log(transactionData);
|
18
|
+
|
19
|
+
let isExecuted = await safeContract.dataHashes(
|
20
|
+
await safeContract.getTransactionHash(
|
21
|
+
transactionData.to,
|
22
|
+
transactionData.value,
|
23
|
+
transactionData.data,
|
24
|
+
transactionData.operation,
|
25
|
+
transactionData.safeTxGas,
|
26
|
+
transactionData.baseGas,
|
27
|
+
transactionData.gasPrice,
|
28
|
+
transactionData.gasToken,
|
29
|
+
transactionData.refundReceiver,
|
30
|
+
transactionData.nonce
|
31
|
+
)
|
32
|
+
)
|
33
|
+
|
34
|
+
while (isExecuted == 1) {
|
35
|
+
transactionData.safeTxGas = BigNumber.from(String(transactionData.safeTxGas)).add(1).toString()
|
36
|
+
|
37
|
+
isExecuted = await safeContract.dataHashes(
|
38
|
+
await safeContract.getTransactionHash(
|
39
|
+
transactionData.to,
|
40
|
+
transactionData.value,
|
41
|
+
transactionData.data,
|
42
|
+
transactionData.operation,
|
43
|
+
transactionData.safeTxGas,
|
44
|
+
transactionData.baseGas,
|
45
|
+
transactionData.gasPrice,
|
46
|
+
transactionData.gasToken,
|
47
|
+
transactionData.refundReceiver,
|
48
|
+
transactionData.nonce
|
49
|
+
)
|
50
|
+
)
|
51
|
+
}
|
52
|
+
|
53
|
+
return transactionData
|
54
|
+
}
|
55
|
+
|
56
|
+
class ProcessWithdrawEvents extends BaseTask {
|
57
|
+
provider: ethers.providers.JsonRpcProvider;
|
58
|
+
chainId: ChainId;
|
59
|
+
leadNodeOnly = true
|
60
|
+
|
61
|
+
constructor({ chainId }: { chainId: ChainId }) {
|
62
|
+
super({
|
63
|
+
logger: new Logger("InteropXGateway::ProcessWithdrawEvents"),
|
64
|
+
})
|
65
|
+
this.chainId = chainId;
|
66
|
+
}
|
67
|
+
|
68
|
+
async pollHandler() {
|
69
|
+
const blockNumber = await this.provider.getBlockNumber()
|
70
|
+
|
71
|
+
const transaction = await Transaction.findOne({
|
72
|
+
where: {
|
73
|
+
status: 'pending',
|
74
|
+
sourceStatus: 'success',
|
75
|
+
targetStatus: 'uninitialised',
|
76
|
+
action: 'withdraw',
|
77
|
+
sourceCreatedAt: {
|
78
|
+
[Op.gte]: new Date(Date.now() - 12 * 60 * 60 * 1000),
|
79
|
+
},
|
80
|
+
targetDelayUntil: {
|
81
|
+
[Op.or]: {
|
82
|
+
[Op.is]: null,
|
83
|
+
[Op.lt]: new Date(),
|
84
|
+
}
|
85
|
+
},
|
86
|
+
sourceBlockNumber: {
|
87
|
+
[Op.lt]: blockNumber - 12,
|
88
|
+
},
|
89
|
+
sourceChainId: this.chainId,
|
90
|
+
}
|
91
|
+
})
|
92
|
+
|
93
|
+
if (!transaction) {
|
94
|
+
return;
|
95
|
+
}
|
96
|
+
|
97
|
+
console.log(`Processing transaction ${transaction.transactionHash}`);
|
98
|
+
|
99
|
+
transaction.targetStatus = 'pending';
|
100
|
+
await transaction.save();
|
101
|
+
|
102
|
+
// refresh event data?
|
103
|
+
|
104
|
+
const targetChainProvider = new ethers.providers.JsonRpcProvider(
|
105
|
+
getRpcProviderUrl(transaction.targetChainId as ChainId)
|
106
|
+
);
|
107
|
+
|
108
|
+
const targetWallet = new ethers.Wallet(config.privateKey!, targetChainProvider);
|
109
|
+
|
110
|
+
const safeAddress = addresses[transaction.targetChainId].gnosisSafe;
|
111
|
+
|
112
|
+
|
113
|
+
const safeContract = getContract<GnosisSafe>(
|
114
|
+
safeAddress,
|
115
|
+
abi.gnosisSafe,
|
116
|
+
targetWallet
|
117
|
+
)
|
118
|
+
|
119
|
+
const ownersThreshold = await safeContract.getThreshold();
|
120
|
+
await wait(10000);
|
121
|
+
|
122
|
+
let gnosisTx = await generateGnosisTransaction({
|
123
|
+
baseGas: "0",
|
124
|
+
data: await buildDataForTransaction(transaction),
|
125
|
+
gasPrice: "0",
|
126
|
+
gasToken: "0x0000000000000000000000000000000000000000",
|
127
|
+
nonce: '0',
|
128
|
+
operation: "1",
|
129
|
+
refundReceiver: "0x0000000000000000000000000000000000000000",
|
130
|
+
safeAddress: safeAddress,
|
131
|
+
safeTxGas: "79668",
|
132
|
+
to: addresses[transaction.targetChainId].multisend,
|
133
|
+
value: "0",
|
134
|
+
}, safeContract);
|
135
|
+
|
136
|
+
const owners = await safeContract.getOwners().then(owners => owners.map(owner => owner.toLowerCase()));
|
137
|
+
|
138
|
+
const ownerPeerIds = peerPool.activePeers.filter(peer => owners.includes(peer.publicAddress.toLowerCase())).map(peer => peer.id)
|
139
|
+
|
140
|
+
console.log(`Collecting signatures for execution ${transaction.transactionHash}`)
|
141
|
+
|
142
|
+
console.log(ownerPeerIds);
|
143
|
+
|
144
|
+
const signatures = await protocol.requestSignatures({
|
145
|
+
type: 'source',
|
146
|
+
transactionHash: transaction.transactionHash,
|
147
|
+
safeTxGas: gnosisTx.safeTxGas,
|
148
|
+
safeNonce: gnosisTx.nonce
|
149
|
+
}, ownerPeerIds)
|
150
|
+
|
151
|
+
|
152
|
+
const validSignatures = signatures.filter(s => !!s.data && s.data !== '0x') as Signature[];
|
153
|
+
|
154
|
+
console.log({ signatures, validSignatures, ownersThreshold: ownersThreshold.toString() });
|
155
|
+
|
156
|
+
if (validSignatures.length === 0 || ownersThreshold.gt(validSignatures.length)) {
|
157
|
+
await transaction.save();
|
158
|
+
transaction.targetDelayUntil = new Date(Date.now() + 30 * 1000);
|
159
|
+
transaction.targetStatus = 'uninitialised'
|
160
|
+
|
161
|
+
await transaction.save();
|
162
|
+
const errorMessage = signatures.find(s => !!s.error)?.error;
|
163
|
+
throw new Error(`Not enough signatures` + (errorMessage ? `: ${errorMessage}` : ''));
|
164
|
+
}
|
165
|
+
|
166
|
+
|
167
|
+
console.log(`Executing transaction for execution ${transaction.transactionHash}`)
|
168
|
+
|
169
|
+
const { data: txData } = await safeContract.populateTransaction.execTransaction(
|
170
|
+
gnosisTx.to,
|
171
|
+
gnosisTx.value,
|
172
|
+
gnosisTx.data,
|
173
|
+
gnosisTx.operation,
|
174
|
+
gnosisTx.safeTxGas,
|
175
|
+
gnosisTx.baseGas,
|
176
|
+
gnosisTx.gasPrice,
|
177
|
+
gnosisTx.gasToken,
|
178
|
+
gnosisTx.refundReceiver,
|
179
|
+
buildSignatureBytes(validSignatures)
|
180
|
+
);
|
181
|
+
|
182
|
+
console.log({
|
183
|
+
from: targetWallet.address,
|
184
|
+
gasPrice: BigNumber.from(120 * 10 ** 9).toString(),
|
185
|
+
to: safeAddress,
|
186
|
+
data: txData,
|
187
|
+
})
|
188
|
+
|
189
|
+
|
190
|
+
const txSent = await targetWallet.sendTransaction({
|
191
|
+
from: targetWallet.address,
|
192
|
+
gasPrice: BigNumber.from(120 * 10 ** 9),
|
193
|
+
to: safeAddress,
|
194
|
+
data: txData,
|
195
|
+
})
|
196
|
+
|
197
|
+
const receipt = await txSent.wait();
|
198
|
+
|
199
|
+
const parsedLogs: LogDescription[] = [];
|
200
|
+
|
201
|
+
receipt.logs.forEach((log) => {
|
202
|
+
try {
|
203
|
+
parsedLogs.push(safeContract.interface.parseLog(log));
|
204
|
+
} catch (e) { }
|
205
|
+
});
|
206
|
+
|
207
|
+
if (parsedLogs.find(e => e.name === 'ExecutionSuccess')) {
|
208
|
+
console.log('ExecutionSuccess')
|
209
|
+
transaction.targetStatus = 'success'
|
210
|
+
transaction.targetTransactionHash = txSent.hash
|
211
|
+
transaction.status = 'success'
|
212
|
+
await transaction.save();
|
213
|
+
} else {
|
214
|
+
console.log('ExecutionFailure')
|
215
|
+
transaction.targetStatus = 'failed'
|
216
|
+
transaction.targetTransactionHash = txSent.hash
|
217
|
+
transaction.status = 'failed'
|
218
|
+
await transaction.save();
|
219
|
+
}
|
220
|
+
}
|
221
|
+
|
222
|
+
async start(): Promise<void> {
|
223
|
+
this.logger.info(`Starting execution watcher on interop chain`);
|
224
|
+
|
225
|
+
this.provider = new ethers.providers.JsonRpcProvider(
|
226
|
+
getRpcProviderUrl(this.chainId)
|
227
|
+
);
|
228
|
+
|
229
|
+
await super.start()
|
230
|
+
}
|
231
|
+
}
|
232
|
+
|
233
|
+
export default ProcessWithdrawEvents;
|
@@ -75,13 +75,15 @@ class SyncWithdrawEvents extends BaseTask {
|
|
75
75
|
|
76
76
|
submitEvent: {
|
77
77
|
to,
|
78
|
-
amount: amount.toString(),
|
78
|
+
amount: amount.toString(),
|
79
|
+
itoken: this.itokenAddress,
|
79
80
|
chainId: chainId.toString()
|
80
81
|
},
|
81
82
|
|
82
83
|
sourceEvent: {
|
83
84
|
to,
|
84
85
|
amount: amount.toString(),
|
86
|
+
itoken: this.itokenAddress,
|
85
87
|
chainId: chainId.toString(),
|
86
88
|
},
|
87
89
|
status: "pending",
|
@@ -209,14 +209,18 @@ class ProcessDepositEvents extends BaseTask {
|
|
209
209
|
if (parsedLogs.find(e => e.name === 'ExecutionSuccess')) {
|
210
210
|
console.log('ExecutionSuccess')
|
211
211
|
transaction.targetStatus = 'success'
|
212
|
+
transaction.targetTransactionHash = txSent.hash
|
212
213
|
transaction.status = 'success'
|
213
214
|
await transaction.save();
|
214
215
|
} else {
|
215
216
|
console.log('ExecutionFailure')
|
216
217
|
transaction.targetStatus = 'failed'
|
218
|
+
transaction.targetTransactionHash = txSent.hash
|
217
219
|
transaction.status = 'failed'
|
218
220
|
await transaction.save();
|
219
221
|
}
|
222
|
+
|
223
|
+
protocol.sendTransaction(transaction)
|
220
224
|
}
|
221
225
|
|
222
226
|
async start(): Promise<void> {
|
package/src/tasks/index.ts
CHANGED
@@ -1,11 +1,16 @@
|
|
1
1
|
import { BaseTask } from "./BaseTask";
|
2
2
|
import InteropXGatewayProcessDepositEvents from "./InteropXGateway/ProcessDepositEvents";
|
3
3
|
import InteropXGatewaySyncDepositEvents from "./InteropXGateway/SyncDepositEvents";
|
4
|
+
|
4
5
|
import InteropBridgeSyncWithdrawEvents from "./InteropBridge/SyncWithdrawEvents";
|
6
|
+
import InteropBridgeProcessWithdrawEvents from "./InteropBridge/ProcessWithdrawEvents";
|
7
|
+
import AutoUpdateTask from "./AutoUpdateTask";
|
5
8
|
|
6
9
|
export class Tasks {
|
7
10
|
|
8
11
|
tasks: BaseTask[] = [
|
12
|
+
new AutoUpdateTask(),
|
13
|
+
|
9
14
|
new InteropXGatewaySyncDepositEvents({
|
10
15
|
chainId: 43114
|
11
16
|
}),
|
@@ -17,6 +22,10 @@ export class Tasks {
|
|
17
22
|
new InteropBridgeSyncWithdrawEvents({
|
18
23
|
chainId: 137,
|
19
24
|
itokenAddress: '0xEab02fe1F016eE3e4106c1C6aad35FeEe657268E',
|
25
|
+
}),
|
26
|
+
|
27
|
+
new InteropBridgeProcessWithdrawEvents({
|
28
|
+
chainId: 137,
|
20
29
|
})
|
21
30
|
];
|
22
31
|
|
package/src/utils/index.ts
CHANGED
@@ -10,7 +10,7 @@ import { encodeMulti, MetaTransaction, OperationType } from 'ethers-multisend';
|
|
10
10
|
import { Transaction } from '@/db';
|
11
11
|
import config from '@/config';
|
12
12
|
import abi from '@/abi';
|
13
|
-
import { InteropBridgeToken } from '@/typechain';
|
13
|
+
import { InteropBridgeToken, InteropXGateway } from '@/typechain';
|
14
14
|
|
15
15
|
export const http = axios.create();
|
16
16
|
|
@@ -136,10 +136,21 @@ export const generateInteropTransactionHash = (data: { action: string, submitTra
|
|
136
136
|
export const buildDataForTransaction = async (transaction: Transaction, type?: 'source' | 'target') => {
|
137
137
|
type = type || transaction.sourceStatus === 'pending' ? 'source' : 'target';
|
138
138
|
|
139
|
+
switch (transaction.action) {
|
140
|
+
case "deposit":
|
141
|
+
return await buildDepositDataForTransaction(transaction, type);
|
142
|
+
case "withdraw":
|
143
|
+
return await buildWithdrawDataForTransaction(transaction, type);
|
144
|
+
default:
|
145
|
+
throw new Error(`Unknown action: ${transaction.action}`);
|
146
|
+
}
|
147
|
+
}
|
148
|
+
|
149
|
+
export const buildDepositDataForTransaction = async (transaction: Transaction, type: 'source' | 'target') => {
|
139
150
|
const transactions: MetaTransaction[] = [];
|
140
151
|
|
141
|
-
if (transaction.action
|
142
|
-
throw new Error(
|
152
|
+
if (transaction.action !== 'deposit') {
|
153
|
+
throw new Error(`Invalid action: ${transaction.action}`)
|
143
154
|
}
|
144
155
|
|
145
156
|
if (transaction.action === 'deposit' && transaction.sourceStatus === 'pending') {
|
@@ -171,7 +182,7 @@ export const buildDataForTransaction = async (transaction: Transaction, type?: '
|
|
171
182
|
transaction.submitEvent.user,
|
172
183
|
ethers.BigNumber.from(transaction.submitEvent.amount.toString()),
|
173
184
|
ethers.BigNumber.from(transaction.submitEvent.sourceChainId.toString()),
|
174
|
-
transaction.
|
185
|
+
transaction.submitTransactionHash,
|
175
186
|
);
|
176
187
|
|
177
188
|
transactions.push({
|
@@ -184,6 +195,58 @@ export const buildDataForTransaction = async (transaction: Transaction, type?: '
|
|
184
195
|
return encodeMulti(transactions).data
|
185
196
|
}
|
186
197
|
|
198
|
+
export const buildWithdrawDataForTransaction = async (transaction: Transaction, type: 'source' | 'target') => {
|
199
|
+
const transactions: MetaTransaction[] = [];
|
200
|
+
|
201
|
+
if (transaction.action !== 'withdraw') {
|
202
|
+
throw new Error(`Invalid action: ${transaction.action}`)
|
203
|
+
}
|
204
|
+
|
205
|
+
if (transaction.action === 'withdraw' && transaction.sourceStatus === 'pending') {
|
206
|
+
throw Error('Cannot build data for pending withdraw transaction');
|
207
|
+
}
|
208
|
+
|
209
|
+
if (!transaction.submitEvent) {
|
210
|
+
throw Error('Cannot build data for transaction without submitEvent');
|
211
|
+
}
|
212
|
+
|
213
|
+
const { to, amount, chainId, itoken: itokenAddress } = transaction.submitEvent;
|
214
|
+
|
215
|
+
const itoken = itokens[transaction.sourceChainId].find(token => token.address.toLowerCase() === itokenAddress.toLowerCase());
|
216
|
+
|
217
|
+
if (!itoken) {
|
218
|
+
throw Error('Cannot build data for transaction without itoken');
|
219
|
+
}
|
220
|
+
|
221
|
+
const token = tokens[chainId].find(t => t.symbol.toLowerCase() === itoken.symbol.toLowerCase());
|
222
|
+
|
223
|
+
if (!token) {
|
224
|
+
throw Error('Cannot build data for transaction without token');
|
225
|
+
}
|
226
|
+
|
227
|
+
const targetChainProvider = new ethers.providers.JsonRpcProvider(getRpcProviderUrl(transaction.targetChainId as ChainId));
|
228
|
+
const targetWallet = new ethers.Wallet(config.privateKey, targetChainProvider);
|
229
|
+
const gatewayAddress = addresses[chainId].interopXGateway;
|
230
|
+
const interopBridgeContract = getContract<InteropXGateway>(gatewayAddress, abi.interopXGateway, targetWallet);
|
231
|
+
|
232
|
+
const { data } = await interopBridgeContract.populateTransaction.systemWithdraw(
|
233
|
+
ethers.BigNumber.from(amount.toString()),
|
234
|
+
to,
|
235
|
+
token.address,
|
236
|
+
ethers.BigNumber.from(transaction.sourceChainId.toString()),
|
237
|
+
transaction.submitTransactionHash,
|
238
|
+
);
|
239
|
+
|
240
|
+
transactions.push({
|
241
|
+
to: gatewayAddress,
|
242
|
+
data: data!,
|
243
|
+
value: '0',
|
244
|
+
operation: OperationType.Call,
|
245
|
+
});
|
246
|
+
|
247
|
+
return encodeMulti(transactions).data
|
248
|
+
}
|
249
|
+
|
187
250
|
|
188
251
|
export function getContract<TContract extends ethers.Contract>(address: string, contractInterface: ethers.ContractInterface | any, signerOrProvider?: ethers.Signer | ethers.providers.Provider) {
|
189
252
|
if (!ethers.utils.getAddress(address) || address === ethers.constants.AddressZero) {
|
@@ -196,6 +259,12 @@ export function getContract<TContract extends ethers.Contract>(address: string,
|
|
196
259
|
signerOrProvider
|
197
260
|
) as TContract
|
198
261
|
|
262
|
+
// Make sure the contract properties is writable
|
263
|
+
const desc = Object.getOwnPropertyDescriptor(contract, 'functions');
|
264
|
+
|
265
|
+
if (!desc || desc.writable !== true) {
|
266
|
+
return contract
|
267
|
+
}
|
199
268
|
|
200
269
|
return new Proxy(contract, {
|
201
270
|
get(target, prop, receiver) {
|