@instadapp/interop-x 0.0.0-dev.80722d6 → 0.0.0-dev.80dece2
Sign up to get free protection for your applications and to get access to all the features.
- package/bin/interop-x +1 -1
- package/dist/package.json +72 -0
- package/dist/{abi → src/abi}/erc20.json +0 -0
- package/dist/{abi → src/abi}/gnosisSafe.json +0 -0
- package/dist/{abi → src/abi}/index.js +0 -0
- package/dist/{abi → src/abi}/interopBridgeToken.json +0 -0
- package/dist/{abi → src/abi}/interopXGateway.json +0 -0
- package/dist/src/api/index.js +33 -0
- package/dist/{config → src/config}/index.js +0 -0
- package/dist/{constants → src/constants}/addresses.js +0 -8
- package/dist/{constants → src/constants}/index.js +1 -0
- package/dist/src/constants/itokens.js +13 -0
- package/dist/{constants → src/constants}/tokens.js +0 -0
- package/dist/{db → src/db}/index.js +0 -0
- package/dist/{db → src/db}/models/index.js +0 -0
- package/dist/{db → src/db}/models/transaction.js +3 -1
- package/dist/{db → src/db}/sequelize.js +0 -0
- package/dist/{index.js → src/index.js} +35 -3
- package/dist/{logger → src/logger}/index.js +0 -0
- package/dist/{net → src/net}/index.js +0 -0
- package/dist/{net → src/net}/peer/index.js +6 -2
- package/dist/{net → src/net}/pool/index.js +27 -9
- package/dist/{net → src/net}/protocol/dial/BaseDialProtocol.js +0 -0
- package/dist/{net → src/net}/protocol/dial/SignatureDialProtocol.js +22 -12
- package/dist/{net → src/net}/protocol/index.js +30 -1
- package/dist/{tasks → src/tasks}/BaseTask.js +1 -1
- 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/{tasks → src/tasks}/InteropXGateway/SyncDepositEvents.js +16 -20
- package/dist/{tasks → src/tasks}/index.js +13 -0
- package/dist/{typechain → src/typechain}/Erc20.js +0 -0
- package/dist/{typechain → src/typechain}/GnosisSafe.js +0 -0
- package/dist/{typechain → src/typechain}/InteropBridgeToken.js +0 -0
- package/dist/{typechain → src/typechain}/InteropXGateway.js +0 -0
- package/dist/{typechain → src/typechain}/common.js +0 -0
- package/dist/{typechain → src/typechain}/factories/Erc20__factory.js +0 -0
- package/dist/{typechain → src/typechain}/factories/GnosisSafe__factory.js +0 -0
- package/dist/{typechain → src/typechain}/factories/InteropBridgeToken__factory.js +0 -0
- package/dist/{typechain → src/typechain}/factories/InteropXGateway__factory.js +0 -0
- package/dist/{typechain → src/typechain}/factories/index.js +0 -0
- package/dist/{typechain → src/typechain}/index.js +0 -0
- package/dist/{types.js → src/types.js} +0 -0
- package/dist/src/utils/index.js +228 -0
- package/package.json +10 -4
- package/patches/@ethersproject+properties+5.6.0.patch +13 -0
- package/src/api/index.ts +33 -0
- package/src/constants/addresses.ts +0 -8
- package/src/constants/index.ts +1 -0
- package/src/constants/itokens.ts +10 -0
- package/src/db/models/transaction.ts +8 -4
- package/src/index.ts +46 -5
- package/src/net/peer/index.ts +7 -6
- package/src/net/pool/index.ts +37 -11
- package/src/net/protocol/dial/SignatureDialProtocol.ts +25 -13
- package/src/net/protocol/index.ts +45 -1
- package/src/tasks/BaseTask.ts +1 -1
- 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 +23 -11
- package/src/tasks/index.ts +19 -2
- package/src/utils/index.ts +182 -4
- package/dist/utils/index.js +0 -101
@@ -0,0 +1,70 @@
|
|
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 config_1 = __importDefault(require("@/config"));
|
13
|
+
class SyncWithdrawEvents extends BaseTask_1.BaseTask {
|
14
|
+
constructor({ chainId, itokenAddress }) {
|
15
|
+
super({
|
16
|
+
logger: new logger_1.default("InteropBridgeToken::SyncWithdrawEvents"),
|
17
|
+
});
|
18
|
+
this.chainId = chainId;
|
19
|
+
this.itokenAddress = itokenAddress;
|
20
|
+
}
|
21
|
+
async pollHandler() {
|
22
|
+
const currentBlock = await this.provider.getBlockNumber();
|
23
|
+
const events = await this.contract.queryFilter(this.contract.filters.Burn(), currentBlock - 2000, currentBlock);
|
24
|
+
let processedEvents = 0;
|
25
|
+
for (const event of events) {
|
26
|
+
try {
|
27
|
+
if (!event.args) {
|
28
|
+
continue;
|
29
|
+
}
|
30
|
+
const { to, amount, chainId } = event.args;
|
31
|
+
const uniqueIdentifier = {
|
32
|
+
action: 'withdraw',
|
33
|
+
submitTransactionHash: event.transactionHash,
|
34
|
+
sourceChainId: this.chainId,
|
35
|
+
targetChainId: chainId.toNumber(),
|
36
|
+
};
|
37
|
+
if (await db_1.Transaction.findOne({ where: uniqueIdentifier })) {
|
38
|
+
continue;
|
39
|
+
}
|
40
|
+
const tx = await event.getTransaction();
|
41
|
+
await db_1.Transaction.create(Object.assign(Object.assign({}, uniqueIdentifier), { transactionHash: (0, utils_1.generateInteropTransactionHash)(uniqueIdentifier), from: tx.from, to, submitTransactionHash: event.transactionHash, submitBlockNumber: event.blockNumber,
|
42
|
+
// submit & source are the same
|
43
|
+
sourceTransactionHash: event.transactionHash, sourceBlockNumber: event.blockNumber, sourceStatus: "success", targetStatus: "uninitialised", submitEvent: {
|
44
|
+
to,
|
45
|
+
amount: amount.toString(),
|
46
|
+
itoken: this.itokenAddress,
|
47
|
+
chainId: chainId.toString()
|
48
|
+
}, sourceEvent: {
|
49
|
+
to,
|
50
|
+
amount: amount.toString(),
|
51
|
+
itoken: this.itokenAddress,
|
52
|
+
chainId: chainId.toString(),
|
53
|
+
}, status: "pending" }));
|
54
|
+
this.logger.info(`Withdraw queued: ${event.transactionHash} ${event.blockNumber}`);
|
55
|
+
}
|
56
|
+
catch (error) {
|
57
|
+
this.logger.error(error);
|
58
|
+
}
|
59
|
+
}
|
60
|
+
if (processedEvents > 0)
|
61
|
+
this.logger.info(`${processedEvents} events processed`);
|
62
|
+
}
|
63
|
+
async start() {
|
64
|
+
this.logger.info(`Starting execution watcher on interop chain`);
|
65
|
+
this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
|
66
|
+
this.contract = (0, utils_1.getContract)(this.itokenAddress, abi_1.default.interopBridgeToken, new ethers_1.ethers.Wallet(config_1.default.privateKey, this.provider));
|
67
|
+
await super.start();
|
68
|
+
}
|
69
|
+
}
|
70
|
+
exports.default = SyncWithdrawEvents;
|
@@ -0,0 +1,150 @@
|
|
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 ProcessDepositEvents extends BaseTask_1.BaseTask {
|
27
|
+
constructor({ chainId }) {
|
28
|
+
super({
|
29
|
+
logger: new logger_1.default("InteropXGateway::ProcessDepositEvents"),
|
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: 'deposit',
|
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
|
+
net_1.protocol.sendTransaction(transaction);
|
141
|
+
}
|
142
|
+
async start() {
|
143
|
+
this.logger.info(`Starting execution watcher on interop chain`);
|
144
|
+
this.contractAddress = constants_1.addresses[this.chainId].interopXGateway;
|
145
|
+
this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
|
146
|
+
this.contract = (0, utils_1.getContract)(this.contractAddress, abi_1.default.interopXGateway, new ethers_1.ethers.Wallet(config_1.default.privateKey, this.provider));
|
147
|
+
await super.start();
|
148
|
+
}
|
149
|
+
}
|
150
|
+
exports.default = ProcessDepositEvents;
|
@@ -29,8 +29,8 @@ class SyncDepositEvents extends BaseTask_1.BaseTask {
|
|
29
29
|
}
|
30
30
|
const { sourceChainId, targetChainId, user, vnonce, amount, token } = event.args;
|
31
31
|
const uniqueIdentifier = {
|
32
|
-
|
33
|
-
|
32
|
+
action: 'deposit',
|
33
|
+
submitTransactionHash: event.transactionHash,
|
34
34
|
sourceChainId: sourceChainId.toNumber(),
|
35
35
|
targetChainId: targetChainId.toNumber(),
|
36
36
|
};
|
@@ -38,28 +38,24 @@ class SyncDepositEvents extends BaseTask_1.BaseTask {
|
|
38
38
|
continue;
|
39
39
|
}
|
40
40
|
const tx = await event.getTransaction();
|
41
|
-
await db_1.Transaction.create({
|
42
|
-
|
43
|
-
|
44
|
-
|
45
|
-
|
46
|
-
|
47
|
-
|
48
|
-
|
49
|
-
|
50
|
-
|
51
|
-
targetStatus: "uninitialised",
|
52
|
-
submitEvent: {
|
41
|
+
await db_1.Transaction.create(Object.assign(Object.assign({}, uniqueIdentifier), { transactionHash: (0, utils_1.generateInteropTransactionHash)(uniqueIdentifier), from: tx.from, to: user, submitTransactionHash: event.transactionHash, submitBlockNumber: event.blockNumber,
|
42
|
+
// submit & source are the same
|
43
|
+
sourceTransactionHash: event.transactionHash, sourceBlockNumber: event.blockNumber, sourceStatus: "success", targetStatus: "uninitialised", submitEvent: {
|
44
|
+
user,
|
45
|
+
sourceChainId: sourceChainId.toString(),
|
46
|
+
targetChainId: targetChainId.toString(),
|
47
|
+
token: token,
|
48
|
+
amount: amount.toString(),
|
49
|
+
vnonce: vnonce.toString(),
|
50
|
+
}, sourceEvent: {
|
53
51
|
user,
|
54
52
|
sourceChainId: sourceChainId.toString(),
|
55
53
|
targetChainId: targetChainId.toString(),
|
56
54
|
token: token,
|
57
|
-
|
55
|
+
amount: amount.toString(),
|
58
56
|
vnonce: vnonce.toString(),
|
59
|
-
},
|
60
|
-
|
61
|
-
});
|
62
|
-
this.logger.info(`Execution queued: ${event.transactionHash} ${event.blockNumber}`);
|
57
|
+
}, status: "pending" }));
|
58
|
+
this.logger.info(`Deposit queued: ${event.transactionHash} ${event.blockNumber}`);
|
63
59
|
}
|
64
60
|
catch (error) {
|
65
61
|
this.logger.error(error);
|
@@ -72,7 +68,7 @@ class SyncDepositEvents extends BaseTask_1.BaseTask {
|
|
72
68
|
this.logger.info(`Starting execution watcher on interop chain`);
|
73
69
|
this.contractAddress = constants_1.addresses[this.chainId].interopXGateway;
|
74
70
|
this.provider = new ethers_1.ethers.providers.JsonRpcProvider((0, utils_1.getRpcProviderUrl)(this.chainId));
|
75
|
-
this.contract =
|
71
|
+
this.contract = (0, utils_1.getContract)(this.contractAddress, abi_1.default.interopXGateway, new ethers_1.ethers.Wallet(config_1.default.privateKey, this.provider));
|
76
72
|
await super.start();
|
77
73
|
}
|
78
74
|
}
|
@@ -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
|
}
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
@@ -0,0 +1,228 @@
|
|
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.getContract = exports.buildWithdrawDataForTransaction = exports.buildDepositDataForTransaction = exports.buildDataForTransaction = exports.generateInteropTransactionHash = exports.asyncCallWithTimeout = exports.buildSignatureBytes = exports.getRpcProviderUrl = exports.signGnosisSafeTx = exports.short = exports.http = void 0;
|
7
|
+
/**
|
8
|
+
* @module util
|
9
|
+
*/
|
10
|
+
const axios_1 = __importDefault(require("axios"));
|
11
|
+
const axios_retry_1 = __importDefault(require("axios-retry"));
|
12
|
+
const constants_1 = require("@/constants");
|
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"));
|
17
|
+
exports.http = axios_1.default.create();
|
18
|
+
(0, axios_retry_1.default)(exports.http, { retries: 3, retryDelay: axios_retry_1.default.exponentialDelay });
|
19
|
+
function short(buffer) {
|
20
|
+
return buffer.toString('hex').slice(0, 8) + '...';
|
21
|
+
}
|
22
|
+
exports.short = short;
|
23
|
+
const signGnosisSafeTx = async ({ to, data = null, value = '0', operation = '1', baseGas = '0', gasPrice = "0", gasToken = "0x0000000000000000000000000000000000000000", refundReceiver = "0x0000000000000000000000000000000000000000", safeTxGas = "79668", nonce = "0", chainId = 137, }, { signer }) => {
|
24
|
+
const gnosisSafe = constants_1.addresses[chainId].gnosisSafe;
|
25
|
+
const domain = {
|
26
|
+
verifyingContract: gnosisSafe,
|
27
|
+
chainId,
|
28
|
+
};
|
29
|
+
const types = {
|
30
|
+
SafeTx: [
|
31
|
+
{ type: 'address', name: 'to' },
|
32
|
+
{ type: 'uint256', name: 'value' },
|
33
|
+
{ type: 'bytes', name: 'data' },
|
34
|
+
{ type: 'uint8', name: 'operation' },
|
35
|
+
{ type: 'uint256', name: 'safeTxGas' },
|
36
|
+
{ type: 'uint256', name: 'baseGas' },
|
37
|
+
{ type: 'uint256', name: 'gasPrice' },
|
38
|
+
{ type: 'address', name: 'gasToken' },
|
39
|
+
{ type: 'address', name: 'refundReceiver' },
|
40
|
+
{ type: 'uint256', name: 'nonce' },
|
41
|
+
],
|
42
|
+
};
|
43
|
+
const message = {
|
44
|
+
baseGas,
|
45
|
+
data,
|
46
|
+
gasPrice,
|
47
|
+
gasToken,
|
48
|
+
nonce: Number(nonce),
|
49
|
+
operation,
|
50
|
+
refundReceiver,
|
51
|
+
safeAddress: gnosisSafe,
|
52
|
+
safeTxGas: String(safeTxGas),
|
53
|
+
to,
|
54
|
+
value,
|
55
|
+
};
|
56
|
+
return await signer._signTypedData(domain, types, message);
|
57
|
+
};
|
58
|
+
exports.signGnosisSafeTx = signGnosisSafeTx;
|
59
|
+
const getRpcProviderUrl = (chainId) => {
|
60
|
+
switch (chainId) {
|
61
|
+
case 1:
|
62
|
+
return 'https://rpc.instadapp.io/mainnet';
|
63
|
+
case 137:
|
64
|
+
return 'https://rpc.instadapp.io/polygon';
|
65
|
+
case 43114:
|
66
|
+
return 'https://rpc.instadapp.io/avalanche';
|
67
|
+
default:
|
68
|
+
throw new Error(`Unknown chainId: ${chainId}`);
|
69
|
+
}
|
70
|
+
};
|
71
|
+
exports.getRpcProviderUrl = getRpcProviderUrl;
|
72
|
+
const buildSignatureBytes = (signatures) => {
|
73
|
+
signatures.sort((left, right) => left.signer.toLowerCase().localeCompare(right.signer.toLowerCase()));
|
74
|
+
let signatureBytes = "0x";
|
75
|
+
for (const sig of signatures) {
|
76
|
+
signatureBytes += sig.data.slice(2);
|
77
|
+
}
|
78
|
+
return signatureBytes;
|
79
|
+
};
|
80
|
+
exports.buildSignatureBytes = buildSignatureBytes;
|
81
|
+
/**
|
82
|
+
* Call an async function with a maximum time limit (in milliseconds) for the timeout
|
83
|
+
* Resolved promise for async function call, or an error if time limit reached
|
84
|
+
*/
|
85
|
+
const asyncCallWithTimeout = async (asyncPromise, timeout) => {
|
86
|
+
let timeoutHandle;
|
87
|
+
const timeoutPromise = new Promise((_resolve, reject) => {
|
88
|
+
timeoutHandle = setTimeout(() => reject(new Error('Async call timeout limit reached')), timeout);
|
89
|
+
});
|
90
|
+
return Promise.race([asyncPromise, timeoutPromise]).then(result => {
|
91
|
+
clearTimeout(timeoutHandle);
|
92
|
+
return result;
|
93
|
+
});
|
94
|
+
};
|
95
|
+
exports.asyncCallWithTimeout = asyncCallWithTimeout;
|
96
|
+
const generateInteropTransactionHash = (data) => {
|
97
|
+
return ethers_1.ethers.utils.solidityKeccak256(['string', 'string', 'string', 'string'], [
|
98
|
+
String(data.action),
|
99
|
+
String(data.submitTransactionHash),
|
100
|
+
String(data.sourceChainId),
|
101
|
+
String(data.targetChainId),
|
102
|
+
]);
|
103
|
+
};
|
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.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
|
+
// Make sure the contract properties is writable
|
189
|
+
const desc = Object.getOwnPropertyDescriptor(contract, 'functions');
|
190
|
+
if (!desc || desc.writable !== true) {
|
191
|
+
return contract;
|
192
|
+
}
|
193
|
+
return new Proxy(contract, {
|
194
|
+
get(target, prop, receiver) {
|
195
|
+
const value = Reflect.get(target, prop, receiver);
|
196
|
+
if (typeof value === 'function' && (contract.functions.hasOwnProperty(prop) || ['queryFilter'].includes(String(prop)))) {
|
197
|
+
return async (...args) => {
|
198
|
+
try {
|
199
|
+
return await value.bind(contract)(...args);
|
200
|
+
}
|
201
|
+
catch (error) {
|
202
|
+
throw new Error(`Error calling "${String(prop)}" on "${address}": ${error.reason || error.message}`);
|
203
|
+
}
|
204
|
+
};
|
205
|
+
}
|
206
|
+
if (typeof value === 'object' && ['populateTransaction', 'estimateGas', 'functions', 'callStatic'].includes(String(prop))) {
|
207
|
+
const parentProp = String(prop);
|
208
|
+
return new Proxy(value, {
|
209
|
+
get(target, prop, receiver) {
|
210
|
+
const value = Reflect.get(target, prop, receiver);
|
211
|
+
if (typeof value === 'function') {
|
212
|
+
return async (...args) => {
|
213
|
+
try {
|
214
|
+
return await value.bind(contract)(...args);
|
215
|
+
}
|
216
|
+
catch (error) {
|
217
|
+
throw new Error(`Error calling "${String(prop)}" using "${parentProp}" on "${address}": ${error.reason || error.message}`);
|
218
|
+
}
|
219
|
+
};
|
220
|
+
}
|
221
|
+
}
|
222
|
+
});
|
223
|
+
}
|
224
|
+
return value;
|
225
|
+
},
|
226
|
+
});
|
227
|
+
}
|
228
|
+
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.
|
3
|
+
"version": "0.0.0-dev.80dece2",
|
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": [
|
@@ -32,6 +33,8 @@
|
|
32
33
|
"ethers": "^5.6.4",
|
33
34
|
"ethers-multisend": "^2.1.1",
|
34
35
|
"expand-home-dir": "^0.0.3",
|
36
|
+
"fastify": "^3.28.0",
|
37
|
+
"fastify-cors": "^6.0.3",
|
35
38
|
"libp2p": "^0.36.2",
|
36
39
|
"libp2p-bootstrap": "^0.14.0",
|
37
40
|
"libp2p-kad-dht": "^0.28.6",
|
@@ -43,12 +46,15 @@
|
|
43
46
|
"libp2p-websockets": "^0.16.2",
|
44
47
|
"luxon": "^2.3.2",
|
45
48
|
"module-alias": "^2.2.2",
|
46
|
-
"
|
49
|
+
"patch-package": "^6.4.7",
|
50
|
+
"postinstall-postinstall": "^2.1.0",
|
51
|
+
"sequelize": "6.18.0",
|
47
52
|
"sqlite3": "^5.0.5",
|
48
53
|
"waait": "^1.0.5"
|
49
54
|
},
|
50
55
|
"bin": {
|
51
|
-
"interop-x": "bin/interop-x"
|
56
|
+
"interop-x": "bin/interop-x",
|
57
|
+
"interopx": "bin/interop-x"
|
52
58
|
},
|
53
59
|
"devDependencies": {
|
54
60
|
"@typechain/ethers-v5": "^10.0.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;
|
package/src/api/index.ts
ADDED
@@ -0,0 +1,33 @@
|
|
1
|
+
import fastify from "fastify"
|
2
|
+
import cors from 'fastify-cors'
|
3
|
+
import Logger from "@/logger"
|
4
|
+
import { Transaction } from "@/db";
|
5
|
+
|
6
|
+
const logger = new Logger("RPC");
|
7
|
+
|
8
|
+
|
9
|
+
const server = fastify({ logger: false })
|
10
|
+
|
11
|
+
server.register(cors, {})
|
12
|
+
|
13
|
+
server.get('/', async () => 'Interop X API')
|
14
|
+
|
15
|
+
export const startApiServer = async () => {
|
16
|
+
const HOST = process.env.API_HOST || '0.0.0.0';
|
17
|
+
const PORT = process.env.API_PORT || '8080';
|
18
|
+
try {
|
19
|
+
server.get('/transactions', async (req) => {
|
20
|
+
return await Transaction.findAndCountAll({
|
21
|
+
limit: 20,
|
22
|
+
offset: 0,
|
23
|
+
})
|
24
|
+
})
|
25
|
+
|
26
|
+
await server.listen(PORT, HOST)
|
27
|
+
|
28
|
+
logger.log(`RPC Server listening at http://${HOST}:${PORT}`)
|
29
|
+
} catch (err) {
|
30
|
+
logger.error(err)
|
31
|
+
process.exit(1)
|
32
|
+
}
|
33
|
+
}
|