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

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.
Files changed (84) hide show
  1. package/dist/package.json +18 -16
  2. package/dist/src/abi/index.js +2 -4
  3. package/dist/src/abi/interopXContract.json +454 -0
  4. package/dist/src/alias.js +10 -0
  5. package/dist/src/api/index.js +6 -3
  6. package/dist/src/config/index.js +11 -1
  7. package/dist/src/constants/addresses.js +3 -3
  8. package/dist/src/constants/index.js +0 -1
  9. package/dist/src/constants/tokens.js +31 -1
  10. package/dist/src/db/models/transaction.js +27 -11
  11. package/dist/src/gnosis/actions/index.js +9 -0
  12. package/dist/src/gnosis/actions/withdraw/index.js +55 -0
  13. package/dist/src/gnosis/index.js +20 -0
  14. package/dist/src/index.js +75 -24
  15. package/dist/src/net/peer/index.js +2 -1
  16. package/dist/src/net/pool/index.js +18 -2
  17. package/dist/src/net/protocol/dial/SignatureDialProtocol.js +9 -10
  18. package/dist/src/net/protocol/dial/TransactionStatusDialProtocol.js +30 -0
  19. package/dist/src/net/protocol/index.js +51 -1
  20. package/dist/src/tasks/AutoUpdateTask.js +70 -0
  21. package/dist/src/tasks/BaseTask.js +11 -3
  22. package/dist/src/tasks/{InteropBridge/ProcessWithdrawEvents.js → InteropXContract/ProcessBridgeRequestEvents.js} +55 -48
  23. package/dist/src/tasks/InteropXContract/SyncBridgeCommittedEvents.js +92 -0
  24. package/dist/src/tasks/InteropXContract/SyncBridgeRequestEvents.js +78 -0
  25. package/dist/src/tasks/InteropXContract/SyncBridgeRequestSentEvents.js +90 -0
  26. package/dist/src/tasks/Transactions/SyncTransactionStatusTask.js +55 -0
  27. package/dist/src/tasks/index.js +18 -17
  28. package/dist/src/typechain/{InteropBridgeToken.js → InteropXContract.js} +0 -0
  29. package/dist/src/typechain/factories/InteropXContract__factory.js +635 -0
  30. package/dist/src/typechain/factories/index.js +3 -5
  31. package/dist/src/typechain/index.js +3 -5
  32. package/dist/src/utils/index.js +55 -92
  33. package/package.json +18 -16
  34. package/src/abi/index.ts +2 -4
  35. package/src/abi/interopXContract.json +454 -0
  36. package/src/alias.ts +6 -0
  37. package/src/api/index.ts +5 -2
  38. package/src/config/index.ts +11 -1
  39. package/src/constants/addresses.ts +3 -3
  40. package/src/constants/index.ts +0 -1
  41. package/src/constants/tokens.ts +32 -2
  42. package/src/db/models/transaction.ts +76 -27
  43. package/src/gnosis/actions/index.ts +5 -0
  44. package/src/gnosis/actions/withdraw/index.ts +77 -0
  45. package/src/gnosis/index.ts +19 -0
  46. package/src/index.ts +96 -26
  47. package/src/net/peer/index.ts +2 -1
  48. package/src/net/pool/index.ts +25 -5
  49. package/src/net/protocol/dial/SignatureDialProtocol.ts +11 -13
  50. package/src/net/protocol/dial/TransactionStatusDialProtocol.ts +33 -0
  51. package/src/net/protocol/index.ts +67 -1
  52. package/src/tasks/AutoUpdateTask.ts +82 -0
  53. package/src/tasks/BaseTask.ts +13 -3
  54. package/src/tasks/{InteropBridge/ProcessWithdrawEvents.ts → InteropXContract/ProcessBridgeRequestEvents.ts} +78 -93
  55. package/src/tasks/InteropXContract/SyncBridgeCommittedEvents.ts +124 -0
  56. package/src/tasks/InteropXContract/SyncBridgeRequestEvents.ts +115 -0
  57. package/src/tasks/InteropXContract/SyncBridgeRequestSentEvents.ts +121 -0
  58. package/src/tasks/Transactions/SyncTransactionStatusTask.ts +67 -0
  59. package/src/tasks/index.ts +27 -21
  60. package/src/typechain/InteropXContract.ts +680 -0
  61. package/src/typechain/factories/InteropXContract__factory.ts +642 -0
  62. package/src/typechain/factories/index.ts +1 -2
  63. package/src/typechain/index.ts +2 -4
  64. package/src/utils/index.ts +96 -129
  65. package/tsconfig.json +7 -2
  66. package/dist/src/abi/interopBridgeToken.json +0 -286
  67. package/dist/src/abi/interopXGateway.json +0 -184
  68. package/dist/src/constants/itokens.js +0 -13
  69. package/dist/src/tasks/InteropBridge/SyncWithdrawEvents.js +0 -70
  70. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +0 -147
  71. package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +0 -75
  72. package/dist/src/typechain/InteropXGateway.js +0 -2
  73. package/dist/src/typechain/factories/InteropBridgeToken__factory.js +0 -459
  74. package/dist/src/typechain/factories/InteropXGateway__factory.js +0 -265
  75. package/src/abi/interopBridgeToken.json +0 -286
  76. package/src/abi/interopXGateway.json +0 -184
  77. package/src/constants/itokens.ts +0 -10
  78. package/src/tasks/InteropBridge/SyncWithdrawEvents.ts +0 -121
  79. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +0 -241
  80. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +0 -126
  81. package/src/typechain/InteropBridgeToken.ts +0 -686
  82. package/src/typechain/InteropXGateway.ts +0 -407
  83. package/src/typechain/factories/InteropBridgeToken__factory.ts +0 -466
  84. package/src/typechain/factories/InteropXGateway__factory.ts +0 -272
@@ -5,6 +5,8 @@ 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";
9
+ import { TransactionStatusDialProtocol } from "./dial/TransactionStatusDialProtocol";
8
10
 
9
11
  export interface ProtocolOptions {
10
12
  /* Handshake timeout in ms (default: 8000) */
@@ -33,7 +35,12 @@ interface PeerInfoEvent extends BaseMessageEvent {
33
35
  data: Omit<IPeerInfo, 'id' | 'updated' | 'idle' | 'pooled'>
34
36
  }
35
37
 
38
+ interface TransactionStatusEvent extends BaseMessageEvent {
39
+ data: Pick<Transaction, 'transactionHash' | 'sourceStatus' | 'sourceTransactionHash' | 'sourceErrors' | 'sourceLogs' | 'targetStatus' | 'targetTransactionHash' | 'targetErrors' | 'targetLogs' | 'status'>
40
+ }
41
+
36
42
  declare interface Protocol {
43
+ on(event: 'TransactionStatus', listener: (payload: TransactionStatusEvent) => void): this;
37
44
  on(event: 'PeerInfo', listener: (payload: PeerInfoEvent) => void): this;
38
45
  on(event: string, listener: (payload: BaseMessageEvent) => void): this;
39
46
  }
@@ -44,7 +51,7 @@ class Protocol extends EventEmitter {
44
51
  private protocolMessages: Message[] = [
45
52
  {
46
53
  name: 'PeerInfo',
47
- code: 0x09,
54
+ code: 0x01,
48
55
  encode: (info: Pick<IPeerInfo, 'publicAddress'>) => [
49
56
  Buffer.from(info.publicAddress),
50
57
  ],
@@ -52,8 +59,49 @@ class Protocol extends EventEmitter {
52
59
  publicAddress: publicAddress.toString(),
53
60
  }),
54
61
  },
62
+ {
63
+ name: 'TransactionStatus',
64
+ code: 0x02,
65
+ encode: (transaction: Transaction) => [
66
+ Buffer.from(transaction.transactionHash),
67
+
68
+ Buffer.from(transaction.sourceStatus),
69
+ Buffer.from(transaction.sourceTransactionHash || ''),
70
+ transaction.sourceErrors ? transaction.sourceErrors.map((e) => Buffer.from(e)) : [],
71
+ transaction.sourceLogs ? transaction.sourceLogs.map((e) => [Buffer.from(e.type), Buffer.from(e.message)]) : [],
72
+
73
+ Buffer.from(transaction.targetStatus),
74
+ Buffer.from(transaction.targetTransactionHash || ''),
75
+ transaction.targetErrors ? transaction.targetErrors.map((e) => Buffer.from(e)) : [],
76
+ transaction.targetLogs ? transaction.targetLogs.map((e) => [Buffer.from(e.type), Buffer.from(e.message)]) : [],
77
+
78
+ Buffer.from(transaction.status),
79
+ ],
80
+ decode: ([transactionHash, sourceStatus, sourceTransactionHash, sourceErrors, sourceLogs, targetStatus, targetTransactionHash, targetErrors, targetLogs, status]: [Buffer, Buffer, Buffer, Buffer[],[Buffer,Buffer][], Buffer, Buffer, Buffer[],[Buffer,Buffer][], Buffer]) => ({
81
+ transactionHash: transactionHash.toString(),
82
+
83
+ sourceStatus: sourceStatus.toString(),
84
+ sourceTransactionHash: sourceTransactionHash.toString() || null,
85
+ sourceErrors: sourceErrors.map((e) => e.toString()),
86
+ sourceLogs: sourceLogs.map(e => ({
87
+ type: e[0].toString(),
88
+ message: e[1].toString(),
89
+ })),
90
+
91
+ targetStatus: targetStatus.toString(),
92
+ targetTransactionHash: targetTransactionHash.toString() || null,
93
+ targetErrors: targetErrors.map((e) => e.toString()),
94
+ targetLogs: targetLogs.map(e => ({
95
+ type: e[0].toString(),
96
+ message: e[1].toString(),
97
+ })),
98
+
99
+ status: status.toString(),
100
+ }),
101
+ },
55
102
  ];
56
103
  private signature: SignatureDialProtocol;
104
+ private transactionStatus: TransactionStatusDialProtocol;
57
105
 
58
106
 
59
107
  start({ libp2p, topic = null, }) {
@@ -73,6 +121,7 @@ class Protocol extends EventEmitter {
73
121
  })
74
122
 
75
123
  this.signature = new SignatureDialProtocol(this.libp2p);
124
+ this.transactionStatus = new TransactionStatusDialProtocol(this.libp2p);
76
125
  }
77
126
 
78
127
 
@@ -121,6 +170,14 @@ class Protocol extends EventEmitter {
121
170
  this.libp2p.pubsub.publish(this.topic, encoded)
122
171
  }
123
172
 
173
+ public sendTransaction(transaction: Transaction) {
174
+ const message = this.protocolMessages.find((m) => m.name === 'TransactionStatus')!
175
+
176
+ const encoded = rlp.encode([message.code, message.encode(transaction)]);
177
+
178
+ this.libp2p.pubsub.publish(this.topic, encoded)
179
+ }
180
+
124
181
  async requestSignatures(data: ISignatureRequest, peerIds?: string[]) {
125
182
  try {
126
183
  peerIds = peerIds || peerPool.activePeerIds;
@@ -133,6 +190,15 @@ class Protocol extends EventEmitter {
133
190
  return []
134
191
  }
135
192
  }
193
+
194
+ async requestTransactionStatus(transactionHash: string, peerId: string) {
195
+ try {
196
+ return await this.transactionStatus.send(transactionHash, peerId);
197
+ } catch (error) {
198
+ console.log(error);
199
+ return null
200
+ }
201
+ }
136
202
  }
137
203
 
138
204
  export const protocol = new Protocol();
@@ -0,0 +1,82 @@
1
+ import { BaseTask } from "./BaseTask";
2
+ import Logger from '@/logger';
3
+ import spawnAsync from 'await-spawn';
4
+ import { spawn } from 'child_process'
5
+ import config from "@/config";
6
+ import wait from "waait";
7
+ import packageJson from "../../package.json";
8
+
9
+ const currentVersion = packageJson.version;
10
+ const tag = config.staging ? 'dev' : 'latest';
11
+
12
+ class AutoUpdateTask extends BaseTask {
13
+ pollIntervalMs: number = 60 * 10 * 1000
14
+
15
+ constructor() {
16
+ super({
17
+ logger: new Logger("AutoUpdateTask"),
18
+ })
19
+ }
20
+
21
+ prePollHandler(): boolean {
22
+ return config.autoUpdate && !config.isLeadNode();
23
+ }
24
+
25
+ async getInstalledVersion() {
26
+ try {
27
+ const stdout = await spawnAsync('npm', ['-g', 'ls', '--depth=0', '--json'])
28
+ return JSON.parse(stdout.toString()).dependencies[packageJson.name].version
29
+ } catch (error) {
30
+ this.logger.error(error)
31
+ return currentVersion
32
+ }
33
+ }
34
+
35
+ async getLatestVersion() {
36
+ try {
37
+ const stdout = await spawnAsync('npm', ['view', `${packageJson.name}@${tag}`, 'version'])
38
+ return stdout.toString().trim()
39
+ } catch (error) {
40
+ this.logger.error(error)
41
+ return currentVersion
42
+ }
43
+ }
44
+
45
+ async pollHandler() {
46
+ const version = await this.getLatestVersion()
47
+
48
+ if (version === currentVersion) {
49
+ return;
50
+ }
51
+
52
+ this.logger.warn(`New version ${version} available.`)
53
+
54
+ this.logger.info('Updating...')
55
+
56
+ await spawnAsync('npm', ['-g', 'install', `@instadapp/interop-x@${tag}`, '-f']);
57
+
58
+ await wait(5000)
59
+
60
+ if (version !== await this.getInstalledVersion()) {
61
+ this.logger.warn(`failed to install ${version}, retrying in 5 minutes`)
62
+ return;
63
+ }
64
+
65
+ this.logger.warn(`Installed version ${version}`)
66
+ this.logger.warn(`Restarting...`)
67
+
68
+
69
+ // TODO: its restarting in the bg, but it should be in the fg
70
+ const subprocess = spawn(process.argv[0], process.argv.slice(1), {
71
+ cwd: process.cwd(),
72
+ stdio: "inherit",
73
+ // shell: process.env.SHELL,
74
+ });
75
+
76
+ subprocess.unref();
77
+
78
+ process.exit()
79
+ }
80
+ }
81
+
82
+ export default AutoUpdateTask;
@@ -19,6 +19,7 @@ export class BaseTask extends EventEmitter implements IBaseTask {
19
19
  started: boolean = false
20
20
  pollIntervalMs: number = 10 * 1000
21
21
  leadNodeOnly: boolean = false
22
+ exceptLeadNode: boolean = false
22
23
 
23
24
  public constructor({ logger }: { logger?: Logger }) {
24
25
  super()
@@ -45,11 +46,20 @@ export class BaseTask extends EventEmitter implements IBaseTask {
45
46
  }
46
47
 
47
48
  prePollHandler(): boolean {
48
- if (!this.leadNodeOnly) {
49
- return true
49
+ if(config.isMaintenanceMode()){
50
+ this.logger.warn('Maintenance mode is enabled. Skipping task.')
51
+ return false
50
52
  }
51
53
 
52
- return config.isLeadNode()
54
+ if (this.exceptLeadNode) {
55
+ return !config.isLeadNode();
56
+ }
57
+
58
+ if (this.leadNodeOnly) {
59
+ return config.isLeadNode()
60
+ }
61
+
62
+ return true
53
63
  }
54
64
 
55
65
  async pollHandler() {
@@ -1,66 +1,33 @@
1
1
  import { BaseTask } from "../BaseTask";
2
2
  import Logger from '@/logger';
3
- import { BigNumber, ethers } from "ethers";
3
+ import { ethers, Wallet } from "ethers";
4
4
  import abi from "@/abi";
5
5
  import { Transaction } from "@/db";
6
- import { buildDataForTransaction, buildSignatureBytes, getContract, getRpcProviderUrl, Signature } from "@/utils";
6
+ import { buildSignatureBytes, generateGnosisTransaction, generateInteropTransactionHash, getContract, getRpcProviderUrl, Signature } from "@/utils";
7
7
  import { addresses } from "@/constants";
8
+ import { Op } from "sequelize";
8
9
  import { ChainId } from "@/types";
9
10
  import config from "@/config";
10
- import { GnosisSafe, InteropXGateway } from "@/typechain";
11
- import { Op } from "sequelize";
11
+ import { GnosisSafe, InteropXContract } from "@/typechain";
12
12
  import wait from "waait";
13
+ import { buildGnosisAction } from "@/gnosis";
13
14
  import { peerPool, protocol } from "@/net";
14
15
  import { LogDescription } from "ethers/lib/utils";
15
16
 
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 {
17
+ class ProccessBridgeRequestEvents extends BaseTask {
18
+ contractAddress: string;
19
+ safeContractAddress: string;
57
20
  provider: ethers.providers.JsonRpcProvider;
21
+ contract: InteropXContract;
22
+ safeContract: GnosisSafe;
58
23
  chainId: ChainId;
59
- leadNodeOnly = true
24
+ sourceWallet: Wallet;
25
+
26
+ leadNodeOnly: boolean = true;
60
27
 
61
28
  constructor({ chainId }: { chainId: ChainId }) {
62
29
  super({
63
- logger: new Logger("InteropXGateway::ProcessWithdrawEvents"),
30
+ logger: new Logger("InteropXContract::ProccessBridgeRequestEvents"),
64
31
  })
65
32
  this.chainId = chainId;
66
33
  }
@@ -71,19 +38,17 @@ class ProcessWithdrawEvents extends BaseTask {
71
38
  const transaction = await Transaction.findOne({
72
39
  where: {
73
40
  status: 'pending',
74
- sourceStatus: 'success',
75
- targetStatus: 'uninitialised',
76
- action: 'withdraw',
77
- sourceCreatedAt: {
41
+ sourceStatus: 'uninitialised',
42
+ createdAt: {
78
43
  [Op.gte]: new Date(Date.now() - 12 * 60 * 60 * 1000),
79
44
  },
80
- targetDelayUntil: {
45
+ sourceDelayUntil: {
81
46
  [Op.or]: {
82
47
  [Op.is]: null,
83
48
  [Op.lt]: new Date(),
84
49
  }
85
50
  },
86
- sourceBlockNumber: {
51
+ requestBlockNumber: {
87
52
  [Op.lt]: blockNumber - 12,
88
53
  },
89
54
  sourceChainId: this.chainId,
@@ -95,52 +60,53 @@ class ProcessWithdrawEvents extends BaseTask {
95
60
  }
96
61
 
97
62
  console.log(`Processing transaction ${transaction.transactionHash}`);
98
-
63
+
99
64
  transaction.targetStatus = 'pending';
100
65
  await transaction.save();
101
66
 
102
- // refresh event data?
67
+ const ownersThreshold = await this.safeContract.getThreshold();
68
+ await wait(10000);
103
69
 
104
- const targetChainProvider = new ethers.providers.JsonRpcProvider(
105
- getRpcProviderUrl(transaction.targetChainId as ChainId)
106
- );
107
70
 
108
- const targetWallet = new ethers.Wallet(config.privateKey!, targetChainProvider);
71
+ let data, logs = [];
109
72
 
110
- const safeAddress = addresses[transaction.targetChainId].gnosisSafe;
73
+ try {
74
+ ({ data, logs } = await buildGnosisAction(transaction, 'source'));
111
75
 
76
+ } catch (error) {
77
+ console.log(error);
78
+ transaction.sourceStatus = 'failed';
79
+ transaction.sourceErrors = [error.message];
80
+ transaction.targetStatus = 'failed';
112
81
 
113
- const safeContract = getContract<GnosisSafe>(
114
- safeAddress,
115
- abi.gnosisSafe,
116
- targetWallet
117
- )
118
-
119
- const ownersThreshold = await safeContract.getThreshold();
120
- await wait(10000);
82
+ transaction.status = 'failed'
83
+ await transaction.save();
84
+ protocol.sendTransaction(transaction)
85
+ return;
86
+ }
121
87
 
122
88
  let gnosisTx = await generateGnosisTransaction({
123
89
  baseGas: "0",
124
- data: await buildDataForTransaction(transaction),
90
+ data,
125
91
  gasPrice: "0",
126
92
  gasToken: "0x0000000000000000000000000000000000000000",
127
93
  nonce: '0',
128
94
  operation: "1",
129
95
  refundReceiver: "0x0000000000000000000000000000000000000000",
130
- safeAddress: safeAddress,
96
+ safeAddress: this.safeContractAddress,
131
97
  safeTxGas: "79668",
132
- to: addresses[transaction.targetChainId].multisend,
98
+ to: addresses[transaction.sourceChainId].multisend,
133
99
  value: "0",
134
- }, safeContract);
100
+ }, this.safeContract);
135
101
 
136
- const owners = await safeContract.getOwners().then(owners => owners.map(owner => owner.toLowerCase()));
102
+ const owners = await this.safeContract.getOwners().then(owners => owners.map(owner => owner.toLowerCase()));
137
103
 
138
104
  const ownerPeerIds = peerPool.activePeers.filter(peer => owners.includes(peer.publicAddress.toLowerCase())).map(peer => peer.id)
139
105
 
140
106
  console.log(`Collecting signatures for execution ${transaction.transactionHash}`)
141
107
 
142
108
  console.log(ownerPeerIds);
143
-
109
+
144
110
  const signatures = await protocol.requestSignatures({
145
111
  type: 'source',
146
112
  transactionHash: transaction.transactionHash,
@@ -155,18 +121,17 @@ class ProcessWithdrawEvents extends BaseTask {
155
121
 
156
122
  if (validSignatures.length === 0 || ownersThreshold.gt(validSignatures.length)) {
157
123
  await transaction.save();
158
- transaction.targetDelayUntil = new Date(Date.now() + 30 * 1000);
159
- transaction.targetStatus = 'uninitialised'
124
+ transaction.sourceDelayUntil = new Date(Date.now() + 30 * 1000);
125
+ transaction.sourceStatus = 'uninitialised'
160
126
 
161
127
  await transaction.save();
162
128
  const errorMessage = signatures.find(s => !!s.error)?.error;
163
129
  throw new Error(`Not enough signatures` + (errorMessage ? `: ${errorMessage}` : ''));
164
130
  }
165
131
 
166
-
167
132
  console.log(`Executing transaction for execution ${transaction.transactionHash}`)
168
133
 
169
- const { data: txData } = await safeContract.populateTransaction.execTransaction(
134
+ const { data: txData } = await this.safeContract.populateTransaction.execTransaction(
170
135
  gnosisTx.to,
171
136
  gnosisTx.value,
172
137
  gnosisTx.data,
@@ -179,20 +144,15 @@ class ProcessWithdrawEvents extends BaseTask {
179
144
  buildSignatureBytes(validSignatures)
180
145
  );
181
146
 
182
- console.log({
183
- from: targetWallet.address,
184
- gasPrice: BigNumber.from(120 * 10 ** 9).toString(),
185
- to: safeAddress,
147
+ const txSent = await this.sourceWallet.sendTransaction({
148
+ from: this.sourceWallet.address,
149
+ gasPrice: ethers.BigNumber.from(120 * 10 ** 9),
150
+ to: this.safeContractAddress,
186
151
  data: txData,
187
152
  })
188
153
 
154
+ console.log(txSent);
189
155
 
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
156
 
197
157
  const receipt = await txSent.wait();
198
158
 
@@ -200,32 +160,57 @@ class ProcessWithdrawEvents extends BaseTask {
200
160
 
201
161
  receipt.logs.forEach((log) => {
202
162
  try {
203
- parsedLogs.push(safeContract.interface.parseLog(log));
163
+ parsedLogs.push(this.safeContract.interface.parseLog(log));
204
164
  } catch (e) { }
205
165
  });
206
166
 
207
167
  if (parsedLogs.find(e => e.name === 'ExecutionSuccess')) {
208
168
  console.log('ExecutionSuccess')
209
- transaction.targetStatus = 'success'
169
+ transaction.sourceStatus = 'success'
170
+ if (txSent.blockNumber)
171
+ transaction.sourceBlockNumber = txSent.blockNumber;
172
+ transaction.sourceTransactionHash = txSent.hash
173
+ transaction.sourceLogs = logs;
210
174
  transaction.status = 'success'
211
175
  await transaction.save();
212
176
  } else {
213
177
  console.log('ExecutionFailure')
214
- transaction.targetStatus = 'failed'
178
+ transaction.sourceStatus = 'failed'
179
+ if (txSent.blockNumber)
180
+ transaction.sourceBlockNumber = txSent.blockNumber;
181
+ transaction.sourceTransactionHash = txSent.hash
182
+ transaction.sourceTransactionHash = txSent.hash
215
183
  transaction.status = 'failed'
216
184
  await transaction.save();
217
185
  }
186
+
187
+ protocol.sendTransaction(transaction)
218
188
  }
219
189
 
220
190
  async start(): Promise<void> {
221
- this.logger.info(`Starting execution watcher on interop chain`);
191
+ this.contractAddress = addresses[this.chainId].interopXContract;
222
192
 
223
193
  this.provider = new ethers.providers.JsonRpcProvider(
224
194
  getRpcProviderUrl(this.chainId)
225
195
  );
226
196
 
197
+ this.sourceWallet = new ethers.Wallet(config.privateKey!, this.provider);
198
+
199
+ this.contract = getContract<InteropXContract>(
200
+ this.contractAddress,
201
+ abi.interopXContract,
202
+ this.sourceWallet
203
+ );
204
+
205
+ this.safeContractAddress = addresses[this.chainId].gnosisSafe;
206
+ this.safeContract = getContract<GnosisSafe>(
207
+ this.safeContractAddress,
208
+ abi.gnosisSafe,
209
+ this.sourceWallet
210
+ );
211
+
227
212
  await super.start()
228
213
  }
229
214
  }
230
215
 
231
- export default ProcessWithdrawEvents;
216
+ export default ProccessBridgeRequestEvents;
@@ -0,0 +1,124 @@
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 { generateInteropTransactionHash, getContract, getRpcProviderUrl } from "@/utils";
7
+ import { addresses } from "@/constants";
8
+ import { ChainId } from "@/types";
9
+ import config from "@/config";
10
+ import { InteropXContract } from "@/typechain";
11
+ import { Op } from "sequelize";
12
+
13
+ class SyncBridgeCommittedEvents extends BaseTask {
14
+ contractAddress: string;
15
+ provider: ethers.providers.JsonRpcProvider;
16
+ contract: InteropXContract;
17
+ chainId: ChainId;
18
+
19
+ constructor({ chainId }: { chainId: ChainId }) {
20
+ super({
21
+ logger: new Logger("InteropXContract::SyncBridgeCommittedEvents"),
22
+ })
23
+ this.chainId = chainId;
24
+ }
25
+
26
+ async pollHandler() {
27
+ const currentBlock = await this.provider.getBlockNumber();
28
+
29
+ const events = await this.contract.queryFilter(
30
+ this.contract.filters.LogBridgeCommitted(),
31
+ currentBlock - 2000,
32
+ currentBlock,
33
+ );
34
+
35
+ let processedEvents = 0;
36
+
37
+ for (const event of events) {
38
+
39
+ try {
40
+ if (!event.args) {
41
+ continue;
42
+ }
43
+
44
+ const { actionId, bridger, position, sourceChainId, targetChainId, requestTransactionHash, metadata } = event.args;
45
+
46
+ const uniqueIdentifier = {
47
+ actionId,
48
+ bridger,
49
+ requestTransactionHash,
50
+ sourceChainId: sourceChainId,
51
+ targetChainId: targetChainId,
52
+ }
53
+
54
+ let transactionHash = generateInteropTransactionHash(uniqueIdentifier);
55
+
56
+ const transaction = await Transaction.findOne({
57
+ where: {
58
+ transactionHash,
59
+ committedEvent: {
60
+ [Op.eq]: null,
61
+ }
62
+ }
63
+ });
64
+
65
+ if (!transaction) {
66
+ continue;
67
+ }
68
+ transaction.targetStatus = 'success'
69
+ transaction.targetBlockNumber = event.blockNumber;
70
+ transaction.targetTransactionHash = event.transactionHash
71
+ transaction.committedEvent = {
72
+ actionId,
73
+ bridger,
74
+ position: {
75
+ withdraw: position.withdraw.map((v) => ({
76
+ sourceToken: v.sourceToken,
77
+ targetToken: v.targetToken,
78
+ amount: v.amount.toString()
79
+ })),
80
+ supply: position.supply.map((v) => ({
81
+ sourceToken: v.sourceToken,
82
+ targetToken: v.targetToken,
83
+ amount: v.amount.toString()
84
+ })),
85
+ },
86
+ sourceChainId: sourceChainId,
87
+ targetChainId: targetChainId,
88
+ metadata,
89
+ requestTransactionHash,
90
+ }
91
+
92
+ transaction.status = 'success';
93
+ await transaction.save()
94
+
95
+ this.logger.info(
96
+ `New bridge committed received: ${transactionHash} `
97
+ );
98
+ } catch (error) {
99
+ this.logger.error(error);
100
+ }
101
+ }
102
+
103
+ if (processedEvents > 0)
104
+ this.logger.info(`${processedEvents} events processed`);
105
+ }
106
+
107
+ async start(): Promise<void> {
108
+ this.contractAddress = addresses[this.chainId].interopXContract;
109
+
110
+ this.provider = new ethers.providers.JsonRpcProvider(
111
+ getRpcProviderUrl(this.chainId)
112
+ );
113
+
114
+ this.contract = getContract<InteropXContract>(
115
+ this.contractAddress,
116
+ abi.interopXContract,
117
+ new ethers.Wallet(config.privateKey!, this.provider)
118
+ );
119
+
120
+ await super.start()
121
+ }
122
+ }
123
+
124
+ export default SyncBridgeCommittedEvents;