@instadapp/interop-x 0.0.0-dev.c279cb8 → 0.0.0-dev.c696e38

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.
@@ -0,0 +1,274 @@
1
+ import { BaseTask } from "../BaseTask";
2
+ import Logger from "@/logger";
3
+ import { ethers, Wallet } from "ethers";
4
+ import abi from "@/abi";
5
+ import { Transaction } from "@/db";
6
+ import {
7
+ buildSignatureBytes,
8
+ generateGnosisTransaction,
9
+ generateInteropTransactionHash,
10
+ getContract,
11
+ getRpcProviderUrl,
12
+ LiquidityError,
13
+ Signature,
14
+ } from "@/utils";
15
+ import { addresses, blockConfirmations } from "@/constants";
16
+ import { ChainId } from "@/types";
17
+ import config from "@/config";
18
+ import { GnosisSafe, InteropX } from "@/typechain";
19
+ import moment from "moment";
20
+ import { Op } from "sequelize";
21
+ import { buildGnosisAction } from "@/gnosis";
22
+ import { peerPool, protocol } from "@/net";
23
+ import { LogDescription } from "ethers/lib/utils";
24
+ import wait from "waait";
25
+
26
+ class ProcessValidateEvents extends BaseTask {
27
+ sourceProvider: ethers.providers.JsonRpcProvider;
28
+ chainId: ChainId;
29
+ leadNodeOnly: boolean = true;
30
+ blockConfirmationsCount: number = 12;
31
+
32
+ constructor({ chainId }: { chainId: ChainId }) {
33
+ super({
34
+ logger: new Logger("InteropX::ProcessValidateEvents"),
35
+ });
36
+ this.chainId = chainId;
37
+ }
38
+
39
+ async pollHandler() {
40
+ const currentBlockNumber = await this.sourceProvider.getBlockNumber();
41
+
42
+ const transaction = await Transaction.findOne({
43
+ where: {
44
+ status: "pending",
45
+ sourceStatus: "success",
46
+ targetStatus: "pending",
47
+ sourceChainId: this.chainId,
48
+ sourceBlockNumber: {
49
+ [Op.lt]: currentBlockNumber - this.blockConfirmationsCount,
50
+ },
51
+ targetDelayUntil: {
52
+ [Op.or]: {
53
+ [Op.is]: null,
54
+ [Op.lt]: new Date(),
55
+ },
56
+ },
57
+
58
+ submitEvent: { $ne: null },
59
+ validateEvent: { $ne: null },
60
+
61
+ createdAt: {
62
+ [Op.gt]: moment().subtract({ hours: 12 }).toDate(),
63
+ },
64
+ },
65
+ });
66
+
67
+ if (!transaction) {
68
+ return;
69
+ }
70
+
71
+ this.logger.debug(`Processing transaction ${transaction.transactionHash}`);
72
+
73
+ transaction.targetStatus = "proccessing";
74
+ await transaction.save();
75
+
76
+ const { sourceChainId, targetChainId } = transaction.validateEvent
77
+
78
+ const targetProvider = new ethers.providers.JsonRpcProvider(
79
+ getRpcProviderUrl(targetChainId as ChainId)
80
+ );
81
+
82
+ const targetWallet = new ethers.Wallet(
83
+ config.privateKey!,
84
+ targetProvider
85
+ );
86
+
87
+ const targetGnosisContract = getContract<GnosisSafe>(
88
+ addresses[targetChainId].gnosisSafe,
89
+ abi.gnosisSafe,
90
+ targetWallet
91
+ );
92
+
93
+ const ownersThreshold = await targetGnosisContract.getThreshold();
94
+ await wait(10000);
95
+
96
+ this.logger.debug(`Build gnosis action for ${transaction.transactionHash}`);
97
+
98
+ let data,
99
+ logs = [];
100
+
101
+ try {
102
+ ({ data, logs } = await buildGnosisAction(transaction, "target"));
103
+ } catch (error) {
104
+ if (error instanceof LiquidityError) {
105
+ await transaction.save();
106
+ transaction.targetDelayUntil = new Date(Date.now() + 60 * 5 * 1000);
107
+ transaction.targetStatus = "pending";
108
+
109
+ await transaction.save();
110
+
111
+ throw error;
112
+ return;
113
+ }
114
+
115
+ transaction.targetStatus = "failed";
116
+ transaction.targetErrors = [error.message];
117
+ transaction.status = "failed";
118
+ await transaction.save();
119
+ protocol.sendTransaction(transaction);
120
+ return;
121
+ }
122
+
123
+ this.logger.debug(
124
+ `Generating gnosis tx for ${transaction.transactionHash}`
125
+ );
126
+
127
+ let gnosisTx = await generateGnosisTransaction(
128
+ {
129
+ baseGas: "0",
130
+ data,
131
+ gasPrice: "0",
132
+ gasToken: "0x0000000000000000000000000000000000000000",
133
+ nonce: "0",
134
+ operation: "1",
135
+ refundReceiver: "0x0000000000000000000000000000000000000000",
136
+ safeAddress: targetGnosisContract.address,
137
+ safeTxGas: "79668",
138
+ to: addresses[transaction.targetChainId].multisend,
139
+ value: "0",
140
+ },
141
+ targetGnosisContract
142
+ );
143
+
144
+ const owners = await targetGnosisContract
145
+ .getOwners()
146
+ .then((owners) => owners.map((owner) => owner.toLowerCase()));
147
+
148
+ const ownerPeerIds = peerPool.activePeers
149
+ .filter((peer) => owners.includes(peer.publicAddress.toLowerCase()))
150
+ .map((peer) => peer.id);
151
+
152
+ console.log(
153
+ `Collecting signatures for execution ${transaction.transactionHash}`
154
+ );
155
+
156
+ console.log(ownerPeerIds);
157
+
158
+ const signatures = await protocol.requestSignatures(
159
+ {
160
+ type: "target",
161
+ transactionHash: transaction.transactionHash,
162
+ safeTxGas: gnosisTx.safeTxGas,
163
+ safeNonce: gnosisTx.nonce,
164
+ chainId: targetChainId,
165
+ },
166
+ ownerPeerIds
167
+ );
168
+
169
+ const validSignatures = signatures.filter(
170
+ (s) => !!s.data && s.data !== "0x"
171
+ ) as Signature[];
172
+
173
+ console.log({
174
+ signatures,
175
+ validSignatures,
176
+ ownersThreshold: ownersThreshold.toString(),
177
+ });
178
+
179
+ if (
180
+ validSignatures.length === 0 ||
181
+ ownersThreshold.gt(validSignatures.length)
182
+ ) {
183
+ await transaction.save();
184
+ transaction.targetDelayUntil = new Date(Date.now() + 30 * 1000);
185
+ transaction.targetStatus = "pending";
186
+
187
+ await transaction.save();
188
+ const errorMessage = signatures.find((s) => !!s.error)?.error;
189
+ throw new Error(
190
+ `Not enough signatures` + (errorMessage ? `: ${errorMessage}` : "")
191
+ );
192
+ }
193
+
194
+ console.log(
195
+ `Executing transaction for execution ${transaction.transactionHash}`
196
+ );
197
+
198
+ const { data: txData } =
199
+ await targetGnosisContract.populateTransaction.execTransaction(
200
+ gnosisTx.to,
201
+ gnosisTx.value,
202
+ gnosisTx.data,
203
+ gnosisTx.operation,
204
+ gnosisTx.safeTxGas,
205
+ gnosisTx.baseGas,
206
+ gnosisTx.gasPrice,
207
+ gnosisTx.gasToken,
208
+ gnosisTx.refundReceiver,
209
+ buildSignatureBytes(validSignatures)
210
+ );
211
+
212
+ const [gasPrice, gasLimit] = await Promise.all([
213
+ targetProvider.getGasPrice(),
214
+ targetProvider.estimateGas({
215
+ from: targetWallet.address,
216
+ to: targetGnosisContract.address,
217
+ data: txData,
218
+ }),
219
+ ]);
220
+
221
+ const txSent = await targetWallet.sendTransaction({
222
+ from: targetWallet.address,
223
+ to: targetGnosisContract.address,
224
+ gasPrice: gasPrice.mul(120).div(100),
225
+ gasLimit: 5_000_000,//gasLimit.mul(120).div(100),
226
+ data: txData,
227
+ });
228
+
229
+ console.log(txSent);
230
+
231
+ const receipt = await txSent.wait();
232
+
233
+ const parsedLogs: LogDescription[] = [];
234
+
235
+ receipt.logs.forEach((log) => {
236
+ try {
237
+ parsedLogs.push(targetGnosisContract.interface.parseLog(log));
238
+ } catch (e) { }
239
+ });
240
+
241
+ if (parsedLogs.find((e) => e.name === "ExecutionSuccess")) {
242
+ console.log("ExecutionSuccess");
243
+ transaction.targetStatus = "success";
244
+ transaction.status = "success";
245
+ if (txSent.blockNumber)
246
+ transaction.targetBlockNumber = txSent.blockNumber;
247
+ transaction.targetTransactionHash = txSent.hash;
248
+ transaction.targetLogs = logs;
249
+ await transaction.save();
250
+ } else {
251
+ console.log("ExecutionFailure");
252
+ transaction.targetStatus = "failed";
253
+ if (txSent.blockNumber)
254
+ transaction.targetBlockNumber = txSent.blockNumber;
255
+ transaction.targetTransactionHash = txSent.hash;
256
+ transaction.status = "failed";
257
+ await transaction.save();
258
+ }
259
+
260
+ protocol.sendTransaction(transaction);
261
+ }
262
+
263
+ async start(): Promise<void> {
264
+ this.blockConfirmationsCount = blockConfirmations[this.chainId] + 1;
265
+
266
+ this.sourceProvider = new ethers.providers.JsonRpcProvider(
267
+ getRpcProviderUrl(this.chainId)
268
+ );
269
+
270
+ await super.start();
271
+ }
272
+ }
273
+
274
+ export default ProcessValidateEvents;
@@ -86,6 +86,7 @@ class SyncLogSubmitEvents extends BaseTask {
86
86
  submitEvent: {
87
87
  actionId,
88
88
  actionIdHashHash,
89
+ actionIdHash: actionIdHashHash,
89
90
  vnonce: vnonce.toString(),
90
91
  position: {
91
92
  withdraw: position.withdraw.map((v) => ({
@@ -0,0 +1,152 @@
1
+ import { BaseTask } from "../BaseTask";
2
+ import Logger from "@/logger";
3
+ import { ethers } from "ethers";
4
+ import abi from "@/abi";
5
+ import { Transaction } from "@/db";
6
+ import {
7
+ generateInteropTransactionHash,
8
+ getContract,
9
+ getRpcProviderUrl,
10
+ } from "@/utils";
11
+ import { addresses } from "@/constants";
12
+ import { ChainId } from "@/types";
13
+ import config from "@/config";
14
+ import { InteropX } from "@/typechain";
15
+ import { Op } from "sequelize";
16
+
17
+ class SyncLogValidateEvents extends BaseTask {
18
+ contractAddress: string;
19
+ provider: ethers.providers.JsonRpcProvider;
20
+ contract: InteropX;
21
+ chainId: ChainId;
22
+
23
+ constructor({ chainId }: { chainId: ChainId }) {
24
+ super({
25
+ logger: new Logger("InteropX::SyncLogValidateEvents"),
26
+ });
27
+ this.chainId = chainId;
28
+ }
29
+
30
+ async pollHandler() {
31
+ const currentBlock = await this.provider.getBlockNumber();
32
+
33
+ const events = await this.contract.queryFilter(
34
+ this.contract.filters.LogValidate(),
35
+ currentBlock - 2000,
36
+ currentBlock
37
+ );
38
+
39
+ let processedEvents = 0;
40
+
41
+ for (const event of events) {
42
+ try {
43
+ if (!event.args) {
44
+ continue;
45
+ }
46
+
47
+ const {
48
+ sourceSpells,
49
+ position,
50
+ actionId,
51
+ actionIdHash,
52
+ sourceSender,
53
+ sourceDsaId,
54
+ targetDsaId,
55
+ sourceChainId,
56
+ targetChainId,
57
+ vnonce,
58
+ metadata,
59
+ } = event.args;
60
+
61
+ const uniqueIdentifier = {
62
+ actionId,
63
+ vnonce: vnonce.toString(),
64
+ sourceSender: sourceSender.toString(),
65
+ sourceChainId: sourceChainId.toNumber(),
66
+ targetChainId: targetChainId.toNumber(),
67
+ sourceDsaId: sourceDsaId.toString(),
68
+ targetDsaId: targetDsaId.toString(),
69
+ };
70
+
71
+ let transactionHash = generateInteropTransactionHash(uniqueIdentifier);
72
+
73
+ const transaction = await Transaction.findOne({
74
+ where: {
75
+ transactionHash,
76
+ validateEvent: { [Op.eq]: null },
77
+ },
78
+ });
79
+
80
+ if (!transaction) {
81
+ continue;
82
+ }
83
+
84
+ if (transaction.sourceStatus != "success") {
85
+ transaction.sourceStatus = "success";
86
+ }
87
+
88
+ if (!transaction.sourceCreatedAt) {
89
+ transaction.sourceCreatedAt = new Date();
90
+ }
91
+
92
+ transaction.sourceTransactionHash = event.transactionHash;
93
+ transaction.sourceBlockNumber = event.blockNumber;
94
+ transaction.sourceLogs = [];
95
+ (transaction.validateEvent = {
96
+ actionId,
97
+ actionIdHashHash: actionIdHash,
98
+ actionIdHash,
99
+ vnonce: vnonce.toString(),
100
+ sourceSpells: sourceSpells.map(({ connector, data }) => ({
101
+ connector,
102
+ data,
103
+ })),
104
+ position: {
105
+ withdraw: position.withdraw.map((v) => ({
106
+ sourceToken: v.sourceToken,
107
+ targetToken: v.targetToken,
108
+ amount: v.amount.toString(),
109
+ })),
110
+ supply: position.supply.map((v) => ({
111
+ sourceToken: v.sourceToken,
112
+ targetToken: v.targetToken,
113
+ amount: v.amount.toString(),
114
+ })),
115
+ },
116
+ sourceChainId: sourceChainId.toNumber(),
117
+ targetChainId: targetChainId.toNumber(),
118
+ sourceSender,
119
+ sourceDsaId: sourceDsaId.toString(),
120
+ targetDsaId: targetDsaId.toString(),
121
+ metadata,
122
+ }),
123
+ await transaction.save();
124
+
125
+ this.logger.info(`New InteropX tranaction: ${transactionHash} `);
126
+ } catch (error) {
127
+ this.logger.error(error);
128
+ }
129
+ }
130
+
131
+ if (processedEvents > 0)
132
+ this.logger.info(`${processedEvents} events processed`);
133
+ }
134
+
135
+ async start(): Promise<void> {
136
+ this.contractAddress = addresses[this.chainId].interopX;
137
+
138
+ this.provider = new ethers.providers.JsonRpcProvider(
139
+ getRpcProviderUrl(this.chainId)
140
+ );
141
+
142
+ this.contract = getContract<InteropX>(
143
+ this.contractAddress,
144
+ abi.interopX,
145
+ new ethers.Wallet(config.privateKey!, this.provider)
146
+ );
147
+
148
+ await super.start();
149
+ }
150
+ }
151
+
152
+ export default SyncLogValidateEvents;
@@ -7,6 +7,8 @@ import AutoUpdateTask from "./AutoUpdateTask";
7
7
 
8
8
  import SyncLogSubmitEvents from "./InteropX/SyncLogSubmitEvents";
9
9
  import ProcessSubmitSubmitEvents from "./InteropX/ProcessSubmitSubmitEvents";
10
+ import SyncLogValidateEvents from "./InteropX/SyncLogValidateEvents";
11
+ import ProcessValidateEvents from "./InteropX/ProcessValidateEvents";
10
12
 
11
13
  export class Tasks {
12
14
 
@@ -21,6 +23,12 @@ export class Tasks {
21
23
  new ProcessSubmitSubmitEvents({ chainId: 137 }),
22
24
  new ProcessSubmitSubmitEvents({ chainId: 43114 }),
23
25
 
26
+ new SyncLogValidateEvents({ chainId: 137 }),
27
+ new SyncLogValidateEvents({ chainId: 43114 }),
28
+
29
+ new ProcessValidateEvents({ chainId: 137 }),
30
+ new ProcessValidateEvents({ chainId: 43114 }),
31
+
24
32
  new SyncTransactionStatusTask(),
25
33
  ];
26
34