@instadapp/interop-x 0.0.0-dev.9b1fcb8 → 0.0.0-dev.a846f65

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 (34) hide show
  1. package/dist/package.json +5 -5
  2. package/dist/src/api/index.js +3 -3
  3. package/dist/src/config/index.js +1 -0
  4. package/dist/src/index.js +44 -5
  5. package/dist/src/net/peer/index.js +2 -1
  6. package/dist/src/net/pool/index.js +18 -2
  7. package/dist/src/net/protocol/dial/SignatureDialProtocol.1.js +28 -0
  8. package/dist/src/net/protocol/index.js +41 -1
  9. package/dist/src/tasks/AutoUpdateTask.js +67 -0
  10. package/dist/src/tasks/BaseTask.js +7 -3
  11. package/dist/src/tasks/InteropBridge/ProcessWithdrawEvents.js +146 -0
  12. package/dist/src/tasks/InteropBridge/SyncWithdrawEvents.js +2 -1
  13. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +3 -1
  14. package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +0 -1
  15. package/dist/src/tasks/Transactions/SyncTransactionStatusTask.js +53 -0
  16. package/dist/src/tasks/index.js +8 -0
  17. package/dist/src/utils/index.js +68 -8
  18. package/package.json +5 -5
  19. package/src/api/index.ts +2 -2
  20. package/src/config/index.ts +2 -0
  21. package/src/index.ts +56 -7
  22. package/src/net/peer/index.ts +2 -1
  23. package/src/net/pool/index.ts +25 -5
  24. package/src/net/protocol/dial/SignatureDialProtocol.1.ts +31 -0
  25. package/src/net/protocol/index.ts +57 -1
  26. package/src/tasks/AutoUpdateTask.ts +81 -0
  27. package/src/tasks/BaseTask.ts +8 -3
  28. package/src/tasks/InteropBridge/ProcessWithdrawEvents.ts +231 -0
  29. package/src/tasks/InteropBridge/SyncWithdrawEvents.ts +3 -3
  30. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +4 -2
  31. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +0 -2
  32. package/src/tasks/Transactions/SyncTransactionStatusTask.ts +65 -0
  33. package/src/tasks/index.ts +11 -0
  34. package/src/utils/index.ts +88 -7
@@ -0,0 +1,81 @@
1
+ import { BaseTask } from "./BaseTask";
2
+ import Logger from '@/logger';
3
+ import { http } from "@/utils";
4
+ import spawn from 'await-spawn';
5
+ import config from "@/config";
6
+ import wait from "waait";
7
+ import packageJson from "../../package.json";
8
+
9
+ const currentVersion = packageJson.version;
10
+
11
+ class AutoUpdateTask extends BaseTask {
12
+ pollIntervalMs: number = 60 * 5 * 1000
13
+
14
+ constructor() {
15
+ super({
16
+ logger: new Logger("AutoUpdateTask"),
17
+ })
18
+ }
19
+
20
+ prePollHandler(): boolean {
21
+ return config.autoUpdate && !config.isLeadNode();
22
+ }
23
+
24
+ async getInstalledVersion() {
25
+ try {
26
+ const stdout = await spawn('npm', ['-g', 'ls', '--depth=0', '--json'])
27
+ return JSON.parse(stdout.toString()).dependencies[packageJson.name].version
28
+ } catch (error) {
29
+ this.logger.error(error)
30
+
31
+ return currentVersion
32
+ }
33
+ }
34
+
35
+ async getLatestVersion() {
36
+ try {
37
+ const stdout = await spawn('npm', ['view', packageJson.name, 'version'])
38
+ return stdout.toString()
39
+ } catch (error) {
40
+ this.logger.error(error)
41
+
42
+ return currentVersion
43
+ }
44
+ }
45
+
46
+ async pollHandler() {
47
+ const version = await this.getLatestVersion()
48
+
49
+ if (version === currentVersion) {
50
+ return;
51
+ }
52
+
53
+ this.logger.warn(`New version ${version} available.`)
54
+
55
+
56
+ this.logger.info('Updating...')
57
+
58
+ const spawner = spawn('npm', ['-g', 'install', '@instadapp/interop-x@latest']);
59
+ spawner.child.on('data', console.log)
60
+ await spawner
61
+
62
+ await wait(5000)
63
+
64
+ if (version !== await this.getInstalledVersion()) {
65
+ this.logger.warn(`failed to install ${version}, retrying in 5 minutes`)
66
+ return;
67
+ }
68
+
69
+ this.logger.warn(`Installed version ${version}`)
70
+ this.logger.warn(`Restarting...`)
71
+
72
+ spawn(process.argv[0], process.argv.slice(1), {
73
+ cwd: process.cwd(),
74
+ stdio: "inherit"
75
+ });
76
+
77
+ process.exit()
78
+ }
79
+ }
80
+
81
+ 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,15 @@ export class BaseTask extends EventEmitter implements IBaseTask {
45
46
  }
46
47
 
47
48
  prePollHandler(): boolean {
48
- if (!this.leadNodeOnly) {
49
- return true
49
+ if (this.exceptLeadNode) {
50
+ return !config.isLeadNode();
50
51
  }
51
52
 
52
- return config.isLeadNode()
53
+ if (this.leadNodeOnly) {
54
+ return config.isLeadNode()
55
+ }
56
+
57
+ return true
53
58
  }
54
59
 
55
60
  async pollHandler() {
@@ -0,0 +1,231 @@
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.provider = new ethers.providers.JsonRpcProvider(
224
+ getRpcProviderUrl(this.chainId)
225
+ );
226
+
227
+ await super.start()
228
+ }
229
+ }
230
+
231
+ 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",
@@ -100,8 +102,6 @@ class SyncWithdrawEvents extends BaseTask {
100
102
  }
101
103
 
102
104
  async start(): Promise<void> {
103
- this.logger.info(`Starting execution watcher on interop chain`);
104
-
105
105
  this.provider = new ethers.providers.JsonRpcProvider(
106
106
  getRpcProviderUrl(this.chainId)
107
107
  );
@@ -209,19 +209,21 @@ 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> {
223
- this.logger.info(`Starting execution watcher on interop chain`);
224
-
225
227
  this.contractAddress = addresses[this.chainId].interopXGateway;
226
228
 
227
229
  this.provider = new ethers.providers.JsonRpcProvider(
@@ -105,8 +105,6 @@ class SyncDepositEvents extends BaseTask {
105
105
  }
106
106
 
107
107
  async start(): Promise<void> {
108
- this.logger.info(`Starting execution watcher on interop chain`);
109
-
110
108
  this.contractAddress = addresses[this.chainId].interopXGateway;
111
109
 
112
110
  this.provider = new ethers.providers.JsonRpcProvider(
@@ -0,0 +1,65 @@
1
+ import { BaseTask } from "../BaseTask";
2
+ import Logger from '@/logger';
3
+ import config from "@/config";
4
+ import { peerPool, protocol } from "@/net";
5
+ import { Transaction } from "@/db";
6
+ import { Op } from "sequelize";
7
+
8
+ class SyncTransactionStatusTask extends BaseTask {
9
+ pollIntervalMs: number = 60 * 1000
10
+ exceptLeadNode: boolean = true;
11
+
12
+ constructor() {
13
+ super({
14
+ logger: new Logger("SyncTransactionStatusTask"),
15
+ })
16
+ }
17
+
18
+ async pollHandler() {
19
+ // if transaction is pending for more than 1 hour, check lead node for status
20
+ const leadNode = peerPool.getLeadPeer();
21
+
22
+ if (!leadNode) {
23
+ return;
24
+ }
25
+
26
+ const transaction = await Transaction.findOne({
27
+ where: {
28
+ status: 'pending',
29
+ sourceCreatedAt: {
30
+ [Op.gte]: new Date(Date.now() - 60 * 60 * 1000),
31
+ },
32
+ }
33
+ })
34
+
35
+ if (!transaction) {
36
+ return;
37
+ }
38
+
39
+ this.logger.info(`Requesting transaction status for ${transaction.transactionHash}`)
40
+
41
+ const transactionStatus = await protocol.requestTransactionStatus(transaction.transactionHash, leadNode.id);
42
+
43
+ if (!transactionStatus) {
44
+ return;
45
+ }
46
+
47
+ this.logger.info(`Received transaction status for ${transaction.transactionHash}`)
48
+
49
+ transaction.sourceStatus = transactionStatus.sourceStatus
50
+ transaction.sourceTransactionHash = transactionStatus.sourceTransactionHash
51
+ transaction.sourceErrors = transactionStatus.sourceErrors
52
+
53
+ transaction.targetStatus = transactionStatus.targetStatus
54
+ transaction.targetTransactionHash = transactionStatus.targetTransactionHash
55
+ transaction.targetErrors = transactionStatus.targetErrors
56
+
57
+ transaction.status = transactionStatus.status
58
+
59
+ await transaction.save()
60
+
61
+ this.logger.info(`Updated transaction status for ${transaction.transactionHash}`)
62
+ }
63
+ }
64
+
65
+ export default SyncTransactionStatusTask;
@@ -1,11 +1,18 @@
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";
8
+ import SyncTransactionStatusTask from "./Transactions/SyncTransactionStatusTask";
5
9
 
6
10
  export class Tasks {
7
11
 
8
12
  tasks: BaseTask[] = [
13
+ new SyncTransactionStatusTask(),
14
+ new AutoUpdateTask(),
15
+
9
16
  new InteropXGatewaySyncDepositEvents({
10
17
  chainId: 43114
11
18
  }),
@@ -17,6 +24,10 @@ export class Tasks {
17
24
  new InteropBridgeSyncWithdrawEvents({
18
25
  chainId: 137,
19
26
  itokenAddress: '0xEab02fe1F016eE3e4106c1C6aad35FeEe657268E',
27
+ }),
28
+
29
+ new InteropBridgeProcessWithdrawEvents({
30
+ chainId: 137,
20
31
  })
21
32
  ];
22
33
 
@@ -10,13 +10,25 @@ 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
 
17
17
  axiosRetry(http, { retries: 3, retryDelay: axiosRetry.exponentialDelay });
18
18
 
19
19
 
20
+ export function shortenHash(hash: string, length: number = 4) {
21
+ if (!hash) return;
22
+
23
+ if (hash.length < 12) return hash;
24
+
25
+ const beginningChars = hash.startsWith("0x") ? length + 2 : length;
26
+
27
+ const shortened = hash.substr(0, beginningChars) + "…" + hash.substr(-length);
28
+
29
+ return shortened;
30
+ }
31
+
20
32
  export function short(buffer: Buffer): string {
21
33
  return buffer.toString('hex').slice(0, 8) + '...'
22
34
  }
@@ -76,11 +88,11 @@ export const signGnosisSafeTx = async ({
76
88
  export const getRpcProviderUrl = (chainId: ChainId) => {
77
89
  switch (chainId) {
78
90
  case 1:
79
- return 'https://rpc.instadapp.io/mainnet';
91
+ return 'https://rpc.ankr.com/eth';
80
92
  case 137:
81
- return 'https://rpc.instadapp.io/polygon';
93
+ return 'https://rpc.ankr.com/polygon';
82
94
  case 43114:
83
- return 'https://rpc.instadapp.io/avalanche';
95
+ return 'https://rpc.ankr.com/avalanche';
84
96
  default:
85
97
  throw new Error(`Unknown chainId: ${chainId}`);
86
98
  }
@@ -136,10 +148,21 @@ export const generateInteropTransactionHash = (data: { action: string, submitTra
136
148
  export const buildDataForTransaction = async (transaction: Transaction, type?: 'source' | 'target') => {
137
149
  type = type || transaction.sourceStatus === 'pending' ? 'source' : 'target';
138
150
 
151
+ switch (transaction.action) {
152
+ case "deposit":
153
+ return await buildDepositDataForTransaction(transaction, type);
154
+ case "withdraw":
155
+ return await buildWithdrawDataForTransaction(transaction, type);
156
+ default:
157
+ throw new Error(`Unknown action: ${transaction.action}`);
158
+ }
159
+ }
160
+
161
+ export const buildDepositDataForTransaction = async (transaction: Transaction, type: 'source' | 'target') => {
139
162
  const transactions: MetaTransaction[] = [];
140
163
 
141
- if (transaction.action != 'deposit') {
142
- throw new Error('Invalid action');
164
+ if (transaction.action !== 'deposit') {
165
+ throw new Error(`Invalid action: ${transaction.action}`)
143
166
  }
144
167
 
145
168
  if (transaction.action === 'deposit' && transaction.sourceStatus === 'pending') {
@@ -171,7 +194,7 @@ export const buildDataForTransaction = async (transaction: Transaction, type?: '
171
194
  transaction.submitEvent.user,
172
195
  ethers.BigNumber.from(transaction.submitEvent.amount.toString()),
173
196
  ethers.BigNumber.from(transaction.submitEvent.sourceChainId.toString()),
174
- transaction.sourceTransactionHash,
197
+ transaction.submitTransactionHash,
175
198
  );
176
199
 
177
200
  transactions.push({
@@ -184,6 +207,58 @@ export const buildDataForTransaction = async (transaction: Transaction, type?: '
184
207
  return encodeMulti(transactions).data
185
208
  }
186
209
 
210
+ export const buildWithdrawDataForTransaction = async (transaction: Transaction, type: 'source' | 'target') => {
211
+ const transactions: MetaTransaction[] = [];
212
+
213
+ if (transaction.action !== 'withdraw') {
214
+ throw new Error(`Invalid action: ${transaction.action}`)
215
+ }
216
+
217
+ if (transaction.action === 'withdraw' && transaction.sourceStatus === 'pending') {
218
+ throw Error('Cannot build data for pending withdraw transaction');
219
+ }
220
+
221
+ if (!transaction.submitEvent) {
222
+ throw Error('Cannot build data for transaction without submitEvent');
223
+ }
224
+
225
+ const { to, amount, chainId, itoken: itokenAddress } = transaction.submitEvent;
226
+
227
+ const itoken = itokens[transaction.sourceChainId].find(token => token.address.toLowerCase() === itokenAddress.toLowerCase());
228
+
229
+ if (!itoken) {
230
+ throw Error('Cannot build data for transaction without itoken');
231
+ }
232
+
233
+ const token = tokens[chainId].find(t => t.symbol.toLowerCase() === itoken.symbol.toLowerCase());
234
+
235
+ if (!token) {
236
+ throw Error('Cannot build data for transaction without token');
237
+ }
238
+
239
+ const targetChainProvider = new ethers.providers.JsonRpcProvider(getRpcProviderUrl(transaction.targetChainId as ChainId));
240
+ const targetWallet = new ethers.Wallet(config.privateKey, targetChainProvider);
241
+ const gatewayAddress = addresses[chainId].interopXGateway;
242
+ const interopBridgeContract = getContract<InteropXGateway>(gatewayAddress, abi.interopXGateway, targetWallet);
243
+
244
+ const { data } = await interopBridgeContract.populateTransaction.systemWithdraw(
245
+ ethers.BigNumber.from(amount.toString()),
246
+ to,
247
+ token.address,
248
+ ethers.BigNumber.from(transaction.sourceChainId.toString()),
249
+ transaction.submitTransactionHash,
250
+ );
251
+
252
+ transactions.push({
253
+ to: gatewayAddress,
254
+ data: data!,
255
+ value: '0',
256
+ operation: OperationType.Call,
257
+ });
258
+
259
+ return encodeMulti(transactions).data
260
+ }
261
+
187
262
 
188
263
  export function getContract<TContract extends ethers.Contract>(address: string, contractInterface: ethers.ContractInterface | any, signerOrProvider?: ethers.Signer | ethers.providers.Provider) {
189
264
  if (!ethers.utils.getAddress(address) || address === ethers.constants.AddressZero) {
@@ -196,6 +271,12 @@ export function getContract<TContract extends ethers.Contract>(address: string,
196
271
  signerOrProvider
197
272
  ) as TContract
198
273
 
274
+ // Make sure the contract properties is writable
275
+ const desc = Object.getOwnPropertyDescriptor(contract, 'functions');
276
+
277
+ if (!desc || desc.writable !== true) {
278
+ return contract
279
+ }
199
280
 
200
281
  return new Proxy(contract, {
201
282
  get(target, prop, receiver) {