@instadapp/interop-x 0.0.0-dev.3e0fb42 → 0.0.0-dev.6d71015

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 (89) hide show
  1. package/.env.example +2 -1
  2. package/dist/package.json +72 -0
  3. package/dist/src/abi/erc20.json +350 -0
  4. package/dist/src/abi/gnosisSafe.json +747 -0
  5. package/dist/src/abi/index.js +15 -0
  6. package/dist/src/abi/interopBridgeToken.json +286 -0
  7. package/dist/src/abi/interopXGateway.json +184 -0
  8. package/dist/src/api/index.js +33 -0
  9. package/dist/{config → src/config}/index.js +5 -1
  10. package/dist/src/constants/addresses.js +20 -0
  11. package/dist/{constants → src/constants}/index.js +2 -0
  12. package/dist/src/constants/itokens.js +13 -0
  13. package/dist/src/constants/tokens.js +107 -0
  14. package/dist/{db → src/db}/index.js +0 -0
  15. package/dist/{db → src/db}/models/index.js +1 -1
  16. package/dist/src/db/models/transaction.js +54 -0
  17. package/dist/{db → src/db}/sequelize.js +2 -1
  18. package/dist/src/index.js +68 -0
  19. package/dist/{logger → src/logger}/index.js +0 -0
  20. package/dist/{net → src/net}/index.js +0 -0
  21. package/dist/{net → src/net}/peer/index.js +13 -5
  22. package/dist/{net → src/net}/pool/index.js +18 -11
  23. package/dist/{net → src/net}/protocol/dial/BaseDialProtocol.js +1 -1
  24. package/dist/{net → src/net}/protocol/dial/SignatureDialProtocol.js +22 -14
  25. package/dist/{net → src/net}/protocol/index.js +3 -3
  26. package/dist/{tasks → src/tasks}/BaseTask.js +3 -3
  27. package/dist/src/tasks/InteropXGateway/ProcessDepositEvents.js +147 -0
  28. package/dist/src/tasks/InteropXGateway/SyncDepositEvents.js +75 -0
  29. package/dist/src/tasks/index.js +31 -0
  30. package/dist/src/typechain/Erc20.js +2 -0
  31. package/dist/src/typechain/GnosisSafe.js +2 -0
  32. package/dist/src/typechain/InteropBridgeToken.js +2 -0
  33. package/dist/src/typechain/InteropXGateway.js +2 -0
  34. package/dist/src/typechain/common.js +2 -0
  35. package/dist/src/typechain/factories/Erc20__factory.js +367 -0
  36. package/dist/src/typechain/factories/GnosisSafe__factory.js +1174 -0
  37. package/dist/src/typechain/factories/InteropBridgeToken__factory.js +459 -0
  38. package/dist/src/typechain/factories/InteropXGateway__factory.js +265 -0
  39. package/dist/src/typechain/factories/index.js +14 -0
  40. package/dist/src/typechain/index.js +35 -0
  41. package/dist/{types.js → src/types.js} +0 -0
  42. package/dist/src/utils/index.js +178 -0
  43. package/package.json +19 -6
  44. package/patches/@ethersproject+properties+5.6.0.patch +13 -0
  45. package/src/abi/erc20.json +350 -0
  46. package/src/abi/gnosisSafe.json +747 -0
  47. package/src/abi/index.ts +11 -0
  48. package/src/abi/interopBridgeToken.json +286 -0
  49. package/src/abi/interopXGateway.json +184 -0
  50. package/src/api/index.ts +33 -0
  51. package/src/config/index.ts +7 -1
  52. package/src/constants/addresses.ts +10 -3
  53. package/src/constants/index.ts +2 -0
  54. package/src/constants/itokens.ts +10 -0
  55. package/src/constants/tokens.ts +104 -0
  56. package/src/db/index.ts +1 -1
  57. package/src/db/models/index.ts +1 -1
  58. package/src/db/models/transaction.ts +96 -0
  59. package/src/db/sequelize.ts +2 -1
  60. package/src/index.ts +46 -5
  61. package/src/net/peer/index.ts +15 -8
  62. package/src/net/pool/index.ts +22 -12
  63. package/src/net/protocol/dial/BaseDialProtocol.ts +1 -1
  64. package/src/net/protocol/dial/SignatureDialProtocol.ts +26 -17
  65. package/src/net/protocol/index.ts +4 -4
  66. package/src/tasks/BaseTask.ts +3 -4
  67. package/src/tasks/InteropXGateway/ProcessDepositEvents.ts +241 -0
  68. package/src/tasks/InteropXGateway/SyncDepositEvents.ts +126 -0
  69. package/src/tasks/index.ts +9 -1
  70. package/src/typechain/Erc20.ts +491 -0
  71. package/src/typechain/GnosisSafe.ts +1728 -0
  72. package/src/typechain/InteropBridgeToken.ts +686 -0
  73. package/src/typechain/InteropXGateway.ts +407 -0
  74. package/src/typechain/common.ts +44 -0
  75. package/src/typechain/factories/Erc20__factory.ts +368 -0
  76. package/src/typechain/factories/GnosisSafe__factory.ts +1178 -0
  77. package/src/typechain/factories/InteropBridgeToken__factory.ts +466 -0
  78. package/src/typechain/factories/InteropXGateway__factory.ts +272 -0
  79. package/src/typechain/factories/index.ts +7 -0
  80. package/src/typechain/index.ts +12 -0
  81. package/src/types.ts +2 -2
  82. package/src/utils/index.ts +124 -2
  83. package/tsconfig.json +3 -0
  84. package/dist/constants/addresses.js +0 -13
  85. package/dist/db/models/execution.js +0 -38
  86. package/dist/index.js +0 -34
  87. package/dist/tasks/index.js +0 -19
  88. package/dist/utils/index.js +0 -89
  89. package/src/db/models/execution.ts +0 -57
@@ -0,0 +1,96 @@
1
+ import { sequelize } from '@/db/sequelize'
2
+ import { CreationOptional, InferAttributes, InferCreationAttributes, Model, DataTypes } from 'sequelize';
3
+
4
+ export class Transaction extends Model<InferAttributes<Transaction>, InferCreationAttributes<Transaction>> {
5
+ declare id: CreationOptional<number>;
6
+
7
+ declare transactionHash: string;
8
+ declare action: string;
9
+ declare from: string;
10
+ declare to: string;
11
+
12
+ declare submitTransactionHash: string;
13
+ declare submitBlockNumber: number;
14
+
15
+ declare sourceChainId: number;
16
+ declare sourceTransactionHash: CreationOptional<string>;
17
+ declare sourceBlockNumber: CreationOptional<number>;
18
+ declare sourceStatus: string;
19
+ declare sourceErrors: CreationOptional<string[]>;
20
+ declare sourceCreatedAt: CreationOptional<Date>;
21
+ declare sourceDelayUntil: CreationOptional<Date>;
22
+
23
+ declare targetChainId: number;
24
+ declare targetTransactionHash: CreationOptional<string>;
25
+ declare targetBlockNumber: CreationOptional<number>;
26
+ declare targetStatus: string;
27
+ declare targetErrors: CreationOptional<string[]>;
28
+ declare targetCreatedAt: CreationOptional<Date>;
29
+ declare targetDelayUntil: CreationOptional<Date>;
30
+
31
+ declare submitEvent: any;
32
+ declare sourceEvent: CreationOptional<any>;
33
+ declare targetEvent: CreationOptional<any>;
34
+
35
+ declare metadata: CreationOptional<any>;
36
+
37
+ declare status: string;
38
+
39
+ declare createdAt: CreationOptional<Date>;
40
+ declare updatedAt: CreationOptional<Date>;
41
+ }
42
+
43
+ Transaction.init({
44
+ id: {
45
+ type: DataTypes.INTEGER,
46
+ autoIncrement: true,
47
+ primaryKey: true
48
+ },
49
+
50
+ submitTransactionHash: DataTypes.NUMBER,
51
+ submitBlockNumber: DataTypes.NUMBER,
52
+
53
+ transactionHash: DataTypes.STRING,
54
+ action: DataTypes.STRING,
55
+
56
+ from: DataTypes.STRING,
57
+ to: DataTypes.STRING,
58
+
59
+ sourceChainId: DataTypes.NUMBER,
60
+ sourceTransactionHash: DataTypes.STRING,
61
+ sourceBlockNumber: DataTypes.NUMBER,
62
+ sourceStatus: DataTypes.STRING,
63
+ sourceErrors: {
64
+ type: DataTypes.JSON,
65
+ // defaultValue: [],
66
+ },
67
+ sourceCreatedAt: {
68
+ type: DataTypes.DATE,
69
+ defaultValue: Date.now()
70
+ },
71
+ sourceDelayUntil: DataTypes.STRING,
72
+
73
+ targetChainId: DataTypes.NUMBER,
74
+ targetTransactionHash: DataTypes.STRING,
75
+ targetBlockNumber: DataTypes.NUMBER,
76
+ targetStatus: DataTypes.STRING,
77
+ targetErrors: {
78
+ type: DataTypes.JSON,
79
+ // defaultValue: [],
80
+ },
81
+ targetCreatedAt: DataTypes.DATE,
82
+ targetDelayUntil: DataTypes.DATE,
83
+
84
+ submitEvent: DataTypes.JSON,
85
+ sourceEvent: DataTypes.JSON,
86
+ targetEvent: DataTypes.JSON,
87
+
88
+ metadata: DataTypes.JSON,
89
+
90
+ status: {
91
+ type: DataTypes.STRING,
92
+ defaultValue: 'pending'
93
+ },
94
+ createdAt: DataTypes.DATE,
95
+ updatedAt: DataTypes.DATE,
96
+ }, { sequelize, tableName: 'transactions' });
@@ -1,9 +1,10 @@
1
1
  //@ts-ignore
2
+ import config from "@/config";
2
3
  import expandHomeDir from "expand-home-dir";
3
4
 
4
5
  import { Sequelize } from 'sequelize';
5
6
 
6
- const basePath = expandHomeDir('~/.interop-x/data');
7
+ const basePath = expandHomeDir(`~/.interop-x/data/${config.publicAddress}/${config.staging ? 'staging' : ''}`);
7
8
 
8
9
  export const sequelize = new Sequelize({
9
10
  dialect: 'sqlite',
package/src/index.ts CHANGED
@@ -1,13 +1,52 @@
1
- import { assert } from "console";
1
+ import moduleAlias from 'module-alias';
2
+
3
+ moduleAlias.addAliases({
4
+ "@/": __dirname + "/",
5
+ "@/logger": __dirname + "/logger",
6
+ "@/tasks": __dirname + "/tasks",
7
+ "@/utils": __dirname + "/utils",
8
+ "@/api": __dirname + "/api",
9
+ "@/net": __dirname + "/net",
10
+ "@/db": __dirname + "/db",
11
+ "@/config": __dirname + "/config",
12
+ "@/types": __dirname + "/types",
13
+ "@/abi": __dirname + "/abi",
14
+ "@/constants": __dirname + "/constants",
15
+ "@/typechain": __dirname + "/typechain"
16
+ })
17
+
18
+ moduleAlias();
19
+ import assert from "assert";
2
20
  import dotenv from "dotenv";
3
- import { Tasks } from "tasks";
4
- import Logger from "./logger";
5
- import { startPeer } from "./net";
21
+ import { ethers } from "ethers";
22
+ import packageJson from '../package.json'
6
23
  dotenv.config();
7
24
 
25
+ import Logger from "@/logger";
26
+ const logger = new Logger('Process')
27
+
28
+
29
+ if (process.argv.at(-1) === 'help') {
30
+ console.log('Usage:')
31
+ console.log(' PRIVATE_KEY=abcd1234 interop-x')
32
+ console.log(' PRIVATE_KEY=abcd1234 STAGING=true interop-x')
33
+ process.exit(0)
34
+ }
35
+
8
36
  assert(process.env.PRIVATE_KEY, "PRIVATE_KEY is not defined");
9
37
 
10
- const logger = new Logger('Process')
38
+ try {
39
+ new ethers.Wallet(process.env.PRIVATE_KEY!)
40
+ } catch (e) {
41
+ logger.error('Invalid private key')
42
+ process.exit(1)
43
+ }
44
+
45
+ logger.debug(`Starting Interop X Node (v${packageJson.version} - rev.@GIT_SHORT_HASH@)`)
46
+
47
+ import { Tasks } from "@/tasks";
48
+ import { startPeer } from "@/net";
49
+ import { startApiServer } from '@/api';
11
50
 
12
51
  async function main() {
13
52
 
@@ -16,6 +55,8 @@ async function main() {
16
55
  const tasks = new Tasks()
17
56
 
18
57
  tasks.start();
58
+
59
+ startApiServer()
19
60
  }
20
61
 
21
62
  main()
@@ -5,7 +5,7 @@ import WS from "libp2p-websockets";
5
5
  //@ts-ignore
6
6
  import Mplex from "libp2p-mplex";
7
7
  import { NOISE } from "libp2p-noise";
8
- import Logger from "../../logger";
8
+ import Logger from "@/logger";
9
9
  import Bootstrap from "libp2p-bootstrap";
10
10
  import wait from "waait";
11
11
  import Gossipsub from "@achingbrain/libp2p-gossipsub";
@@ -15,7 +15,8 @@ import MulticastDNS from "libp2p-mdns";
15
15
  import KadDHT from "libp2p-kad-dht";
16
16
  //@ts-ignore
17
17
  import PubsubPeerDiscovery from "libp2p-pubsub-peer-discovery";
18
- import { protocol } from "../protocol";
18
+ import { protocol } from "@/net";
19
+ import config from "@/config";
19
20
 
20
21
  const logger = new Logger("Peer");
21
22
 
@@ -87,16 +88,22 @@ export const startPeer = async ({ }: IPeerOptions) => {
87
88
  libp2p: node
88
89
  })
89
90
 
90
- node.on("peer:discovery", (peer) =>
91
- logger.log(`Discovered peer ${peer}`)
92
- ); // peer disc.
93
- node.connectionManager.on("peer:connect", (connection) =>
94
- logger.log(`Connected to ${connection.remotePeer.toB58String()}`)
95
- );
91
+ node.on("peer:discovery", (peer) => {
92
+ // logger.log(`Discovered peer ${peer}`)
93
+ }); // peer disc.
94
+
95
+ node.connectionManager.on("peer:connect", (connection) => {
96
+ // logger.log(`Connected to ${connection.remotePeer.toB58String()}`)
97
+ });
96
98
 
97
99
  logger.log("Peer discovery started");
98
100
 
99
101
  await wait(1000);
102
+
103
+
104
+ setInterval(() => protocol.sendPeerInfo({
105
+ publicAddress: config.wallet.address,
106
+ }), 5000)
100
107
  };
101
108
 
102
109
  export const stopPeer = async () => {
@@ -1,5 +1,9 @@
1
- import { Event } from "../../types";
2
- import config from "../../config";
1
+ import { Event } from "@/types";
2
+ import config from "@/config";
3
+ import Logger from "@/logger";
4
+
5
+
6
+ const logger = new Logger('PeerPool')
3
7
 
4
8
  export interface IPeerInfo {
5
9
  id: string;
@@ -75,10 +79,15 @@ export class PeerPool {
75
79
  * @emits {@link Event.POOL_PEER_ADDED}
76
80
  */
77
81
  add(peer?: IPeerInfo) {
78
- if (peer && peer.id && !this.pool.get(peer.id)) {
82
+ if (peer && peer.id) {
83
+ const newPeer = !this.pool.get(peer.id);
79
84
  this.pool.set(peer.id, peer)
80
85
  peer.pooled = true
81
- config.events.emit(Event.POOL_PEER_ADDED, peer)
86
+
87
+ if(newPeer) {
88
+ config.events.emit(Event.POOL_PEER_ADDED, peer)
89
+ logger.info(`Peer ${peer.id} with address ${peer.publicAddress} added to pool`)
90
+ }
82
91
  }
83
92
  }
84
93
 
@@ -92,6 +101,7 @@ export class PeerPool {
92
101
  if (this.pool.delete(peer.id)) {
93
102
  peer.pooled = false
94
103
  config.events.emit(Event.POOL_PEER_REMOVED, peer)
104
+ logger.info(`Peer ${peer.id} with address ${peer.publicAddress} removed from pool`)
95
105
  }
96
106
  }
97
107
  }
@@ -114,14 +124,14 @@ export class PeerPool {
114
124
 
115
125
 
116
126
  cleanup() {
117
- let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
118
-
119
- this.peers.forEach((peerInfo) => {
120
- if (peerInfo.updated.getTime() < compDate) {
121
- console.log(`Peer ${peerInfo.id} idle for ${this.PEERS_CLEANUP_TIME_LIMIT} minutes`)
122
- this.remove(peerInfo)
123
- }
124
- })
127
+ // let compDate = Date.now() - this.PEERS_CLEANUP_TIME_LIMIT * 60
128
+
129
+ // this.peers.forEach((peerInfo) => {
130
+ // if (peerInfo.updated.getTime() < compDate) {
131
+ // console.log(`Peer ${peerInfo.id} idle for ${this.PEERS_CLEANUP_TIME_LIMIT} minutes`)
132
+ // this.remove(peerInfo)
133
+ // }
134
+ // })
125
135
  }
126
136
  }
127
137
 
@@ -1,7 +1,7 @@
1
1
  import pipe from 'it-pipe';
2
2
  import Libp2p from 'libp2p';
3
3
  import PeerId from 'peer-id';
4
- import { asyncCallWithTimeout } from '../../../utils';
4
+ import { asyncCallWithTimeout } from '@/utils';
5
5
  import wait from 'waait';
6
6
 
7
7
  export class BaseDialProtocol<TRequest extends any, TResponse extends any> {
@@ -1,14 +1,14 @@
1
- import { signGnosisSafeTx } from "../../../utils";
2
1
  import { BaseDialProtocol } from "./BaseDialProtocol";
3
2
  import wait from "waait";
4
- import { ChainId } from "../../../types";
5
- import config from "config";
6
- import { addresses } from "../../../constants";
7
- import { Execution } from "db";
3
+ import config from "@/config";
4
+ import { Transaction } from "@/db";
5
+ import { buildDataForTransaction, signGnosisSafeTx } from "@/utils";
6
+ import { addresses } from "@/constants";
7
+ import { ChainId } from "@/types";
8
8
 
9
9
  export interface ISignatureRequest {
10
- type: string,
11
- vnonce: string
10
+ type: 'source' | 'target' ,
11
+ transactionHash: string
12
12
  safeTxGas: string
13
13
  safeNonce: string
14
14
  }
@@ -21,25 +21,25 @@ export class SignatureDialProtocol extends BaseDialProtocol<ISignatureRequest, I
21
21
  protected timeout = 30000;
22
22
 
23
23
  constructor(libp2p) {
24
- super(libp2p, '/signatures')
24
+ super(libp2p, '/interop-x/signatures')
25
25
  }
26
26
 
27
27
  async response(data: ISignatureRequest): Promise<ISignatureResponse> {
28
28
  const signer = config.wallet;
29
29
 
30
- let event: Execution | null;
30
+ let transaction: Transaction | null;
31
31
  let maxTimeout = 20000;
32
32
 
33
33
  do {
34
- event = await Execution.findOne({ where: { vnonce: data.vnonce.toString() } })
34
+ transaction = await Transaction.findOne({ where: { transactionHash: data.transactionHash } })
35
35
 
36
- if (!event) {
36
+ if (!transaction) {
37
37
  await wait(1000);
38
38
  maxTimeout -= 1000;
39
39
  }
40
- } while (!event && maxTimeout > 0)
40
+ } while (!transaction && maxTimeout > 0)
41
41
 
42
- if (!event) {
42
+ if (!transaction) {
43
43
  return {
44
44
  signer: signer.address,
45
45
  data: null,
@@ -47,16 +47,25 @@ export class SignatureDialProtocol extends BaseDialProtocol<ISignatureRequest, I
47
47
  };
48
48
  }
49
49
 
50
+ console.log("signing:", {
51
+ to: addresses[transaction.targetChainId].multisend,
52
+ data: await buildDataForTransaction(transaction, data.type),
53
+ chainId: transaction.targetChainId as ChainId,
54
+ safeTxGas: data.safeTxGas,
55
+ nonce: data.safeNonce,
56
+ });
57
+
50
58
  const signedData = await signGnosisSafeTx({
51
- to: addresses[event.chainId as ChainId].multisend,
52
- data: 'TODO',
53
- chainId: event.chainId as ChainId,
59
+ to: addresses[transaction.targetChainId].multisend,
60
+ data: await buildDataForTransaction(transaction, data.type),
61
+ chainId: transaction.targetChainId as ChainId,
54
62
  safeTxGas: data.safeTxGas,
63
+ nonce: data.safeNonce,
55
64
  }, { signer });
56
65
 
57
66
  return {
58
67
  signer: signer.address,
59
- data: signedData,
68
+ data: signedData
60
69
  }
61
70
  }
62
71
  }
@@ -3,8 +3,8 @@ import Libp2p from 'libp2p';
3
3
  import { bufferToInt, rlp } from 'ethereumjs-util'
4
4
  import { SignatureDialProtocol, ISignatureRequest, ISignatureResponse } from "./dial/SignatureDialProtocol";
5
5
  import { IPeerInfo, peerPool } from "..";
6
- import config from "config";
7
- import { Event } from "types";
6
+ import config from "@/config";
7
+ import { Event } from "@/types";
8
8
 
9
9
  export interface ProtocolOptions {
10
10
  /* Handshake timeout in ms (default: 8000) */
@@ -58,7 +58,7 @@ class Protocol extends EventEmitter {
58
58
 
59
59
  start({ libp2p, topic = null, }) {
60
60
  this.libp2p = libp2p
61
- this.topic = topic || 'protocol'
61
+ this.topic = topic || 'itnerop-x-protocol'
62
62
 
63
63
  if (this.libp2p.isStarted()) this.init()
64
64
 
@@ -113,7 +113,7 @@ class Protocol extends EventEmitter {
113
113
  }
114
114
 
115
115
 
116
- public sendPeerInfo(data: Omit<IPeerInfo, 'peerId' | 'updated' | 'idle'>) {
116
+ public sendPeerInfo(data: Pick<IPeerInfo, 'publicAddress'>) {
117
117
  const message = this.protocolMessages.find((m) => m.name === 'PeerInfo')!
118
118
 
119
119
  const encoded = rlp.encode([message.code, message.encode(data)]);
@@ -1,8 +1,7 @@
1
- import config from "config";
2
- import { ethers } from "ethers";
1
+ import config from "@/config";
3
2
  import EventEmitter from "events";
4
3
  import wait from "waait";
5
- import Logger from "../logger";
4
+ import Logger from "@/logger";
6
5
 
7
6
  export interface IBaseTask {
8
7
  pollCheck(): Promise<void>
@@ -38,7 +37,7 @@ export class BaseTask extends EventEmitter implements IBaseTask {
38
37
  await this.pollHandler()
39
38
  }
40
39
  } catch (err) {
41
- this.logger.error(`poll check error: ${err.message}\ntrace: ${err.stack}`)
40
+ this.logger.error(`poll check error:\n${err.message}\ntrace: ${err.stack}`)
42
41
  }
43
42
 
44
43
  await this.postPollHandler()
@@ -0,0 +1,241 @@
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 ProcessDepositEvents extends BaseTask {
57
+ contractAddress: string;
58
+ provider: ethers.providers.JsonRpcProvider;
59
+ contract: InteropXGateway;
60
+ chainId: ChainId;
61
+ leadNodeOnly = true
62
+
63
+ constructor({ chainId }: { chainId: ChainId }) {
64
+ super({
65
+ logger: new Logger("InteropXGateway::ProcessDepositEvents"),
66
+ })
67
+ this.chainId = chainId;
68
+ }
69
+
70
+ async pollHandler() {
71
+ const blockNumber = await this.provider.getBlockNumber()
72
+
73
+ const transaction = await Transaction.findOne({
74
+ where: {
75
+ status: 'pending',
76
+ sourceStatus: 'success',
77
+ targetStatus: 'uninitialised',
78
+ action: 'deposit',
79
+ sourceCreatedAt: {
80
+ [Op.gte]: new Date(Date.now() - 12 * 60 * 60 * 1000),
81
+ },
82
+ targetDelayUntil: {
83
+ [Op.or]: {
84
+ [Op.is]: null,
85
+ [Op.lt]: new Date(),
86
+ }
87
+ },
88
+ sourceBlockNumber: {
89
+ [Op.lt]: blockNumber - 12,
90
+ },
91
+ sourceChainId: this.chainId,
92
+ }
93
+ })
94
+
95
+ if (!transaction) {
96
+ return;
97
+ }
98
+
99
+ console.log(`Processing transaction ${transaction.transactionHash}`);
100
+
101
+ transaction.targetStatus = 'pending';
102
+ await transaction.save();
103
+
104
+ // refresh event data?
105
+
106
+ const targetChainProvider = new ethers.providers.JsonRpcProvider(
107
+ getRpcProviderUrl(transaction.targetChainId as ChainId)
108
+ );
109
+
110
+ const targetWallet = new ethers.Wallet(config.privateKey!, targetChainProvider);
111
+
112
+ const safeAddress = addresses[transaction.targetChainId].gnosisSafe;
113
+
114
+
115
+ const safeContract = getContract<GnosisSafe>(
116
+ safeAddress,
117
+ abi.gnosisSafe,
118
+ targetWallet
119
+ )
120
+
121
+ const ownersThreshold = await safeContract.getThreshold();
122
+ await wait(10000);
123
+
124
+ let gnosisTx = await generateGnosisTransaction({
125
+ baseGas: "0",
126
+ data: await buildDataForTransaction(transaction),
127
+ gasPrice: "0",
128
+ gasToken: "0x0000000000000000000000000000000000000000",
129
+ nonce: '0',
130
+ operation: "1",
131
+ refundReceiver: "0x0000000000000000000000000000000000000000",
132
+ safeAddress: safeAddress,
133
+ safeTxGas: "79668",
134
+ to: addresses[transaction.targetChainId].multisend,
135
+ value: "0",
136
+ }, safeContract);
137
+
138
+ const owners = await safeContract.getOwners().then(owners => owners.map(owner => owner.toLowerCase()));
139
+
140
+ const ownerPeerIds = peerPool.activePeers.filter(peer => owners.includes(peer.publicAddress.toLowerCase())).map(peer => peer.id)
141
+
142
+ console.log(`Collecting signatures for execution ${transaction.transactionHash}`)
143
+
144
+ console.log(ownerPeerIds);
145
+
146
+ const signatures = await protocol.requestSignatures({
147
+ type: 'source',
148
+ transactionHash: transaction.transactionHash,
149
+ safeTxGas: gnosisTx.safeTxGas,
150
+ safeNonce: gnosisTx.nonce
151
+ }, ownerPeerIds)
152
+
153
+
154
+ const validSignatures = signatures.filter(s => !!s.data && s.data !== '0x') as Signature[];
155
+
156
+ console.log({ signatures, validSignatures, ownersThreshold: ownersThreshold.toString() });
157
+
158
+ if (validSignatures.length === 0 || ownersThreshold.gt(validSignatures.length)) {
159
+ await transaction.save();
160
+ transaction.targetDelayUntil = new Date(Date.now() + 30 * 1000);
161
+ transaction.targetStatus = 'uninitialised'
162
+
163
+ await transaction.save();
164
+ const errorMessage = signatures.find(s => !!s.error)?.error;
165
+ throw new Error(`Not enough signatures` + (errorMessage ? `: ${errorMessage}` : ''));
166
+ }
167
+
168
+
169
+ console.log(`Executing transaction for execution ${transaction.transactionHash}`)
170
+
171
+ const { data: txData } = await safeContract.populateTransaction.execTransaction(
172
+ gnosisTx.to,
173
+ gnosisTx.value,
174
+ gnosisTx.data,
175
+ gnosisTx.operation,
176
+ gnosisTx.safeTxGas,
177
+ gnosisTx.baseGas,
178
+ gnosisTx.gasPrice,
179
+ gnosisTx.gasToken,
180
+ gnosisTx.refundReceiver,
181
+ buildSignatureBytes(validSignatures)
182
+ );
183
+
184
+ console.log({
185
+ from: targetWallet.address,
186
+ gasPrice: BigNumber.from(120 * 10 ** 9).toString(),
187
+ to: safeAddress,
188
+ data: txData,
189
+ })
190
+
191
+
192
+ const txSent = await targetWallet.sendTransaction({
193
+ from: targetWallet.address,
194
+ gasPrice: BigNumber.from(120 * 10 ** 9),
195
+ to: safeAddress,
196
+ data: txData,
197
+ })
198
+
199
+ const receipt = await txSent.wait();
200
+
201
+ const parsedLogs: LogDescription[] = [];
202
+
203
+ receipt.logs.forEach((log) => {
204
+ try {
205
+ parsedLogs.push(safeContract.interface.parseLog(log));
206
+ } catch (e) { }
207
+ });
208
+
209
+ if (parsedLogs.find(e => e.name === 'ExecutionSuccess')) {
210
+ console.log('ExecutionSuccess')
211
+ transaction.targetStatus = 'success'
212
+ transaction.status = 'success'
213
+ await transaction.save();
214
+ } else {
215
+ console.log('ExecutionFailure')
216
+ transaction.targetStatus = 'failed'
217
+ transaction.status = 'failed'
218
+ await transaction.save();
219
+ }
220
+ }
221
+
222
+ async start(): Promise<void> {
223
+ this.logger.info(`Starting execution watcher on interop chain`);
224
+
225
+ this.contractAddress = addresses[this.chainId].interopXGateway;
226
+
227
+ this.provider = new ethers.providers.JsonRpcProvider(
228
+ getRpcProviderUrl(this.chainId)
229
+ );
230
+
231
+ this.contract = getContract<InteropXGateway>(
232
+ this.contractAddress,
233
+ abi.interopXGateway,
234
+ new ethers.Wallet(config.privateKey!, this.provider)
235
+ );
236
+
237
+ await super.start()
238
+ }
239
+ }
240
+
241
+ export default ProcessDepositEvents;