@instadapp/interop-x 0.0.0-dev.d71f27e → 0.0.0-dev.de59649

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.
@@ -1,104 +1,127 @@
1
1
  export const tokens = {
2
- 1: [
3
- {
4
- symbol: "ETH",
5
- name: "Ethereum",
6
- address: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
7
- decimals: 18,
8
- },
9
- {
10
- symbol: "DAI",
11
- name: "DAI Stable",
12
- address: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
13
- decimals: 18,
14
- },
15
- {
16
- symbol: "USDC",
17
- name: "USD Coin",
18
- address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
19
- decimals: 6,
20
- },
21
- {
22
- symbol: "USDT",
23
- name: "Tether USD Coin",
24
- address: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
25
- decimals: 6,
26
- },
27
- {
28
- symbol: "WBTC",
29
- name: "Wrapped BTC",
30
- address: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",
31
- decimals: 8,
32
- },
33
- ],
2
+ // 1: [
3
+ // {
4
+ // aliases: ['eth'],
5
+ // symbol: "ETH",
6
+ // name: "Ethereum",
7
+ // address: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
8
+ // decimals: 18,
9
+ // },
10
+ // {
11
+ // aliases: ['weth'],
12
+ // symbol: "WETH",
13
+ // name: "Wrapped Ethereum",
14
+ // address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
15
+ // decimals: 18,
16
+ // },
17
+ // {
18
+ // aliases: ['dai'],
19
+ // symbol: "DAI",
20
+ // name: "DAI Stable",
21
+ // address: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
22
+ // decimals: 18,
23
+ // },
24
+ // {
25
+ // aliases: ['usdc'],
26
+ // symbol: "USDC",
27
+ // name: "USD Coin",
28
+ // address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
29
+ // decimals: 6,
30
+ // },
31
+ // {
32
+ // aliases: ['usdt'],
33
+ // symbol: "USDT",
34
+ // name: "Tether USD Coin",
35
+ // address: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
36
+ // decimals: 6,
37
+ // },
38
+ // {
39
+ // aliases: ['wbtc'],
40
+ // symbol: "WBTC",
41
+ // name: "Wrapped BTC",
42
+ // address: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",
43
+ // decimals: 8,
44
+ // },
45
+ // ],
34
46
  137: [
35
47
  {
48
+ aliases: ['eth', 'weth'],
36
49
  symbol: "ETH",
37
50
  name: "Ethereum",
38
51
  address: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619",
39
52
  decimals: 18,
40
53
  },
41
54
  {
55
+ aliases: ['dai'],
42
56
  symbol: "DAI",
43
57
  name: "DAI Stable",
44
58
  address: "0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063",
45
59
  decimals: 18,
46
60
  },
47
61
  {
62
+ aliases: ['usdc'],
48
63
  symbol: "USDC",
49
64
  name: "USD Coin",
50
65
  address: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
51
66
  decimals: 6,
52
67
  },
53
68
  {
69
+ aliases: ['usdt'],
54
70
  symbol: "USDT",
55
71
  name: "Tether USD Coin",
56
72
  address: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F",
57
73
  decimals: 6,
58
74
  },
59
75
  {
76
+ aliases: ['wbtc'],
60
77
  symbol: "WBTC",
61
78
  name: "Wrapped BTC",
62
79
  address: "0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6",
63
80
  decimals: 8,
64
81
  },
65
- {
66
- symbol: "AVAX",
67
- name: "Avalanche Token",
68
- address: "0x2C89bbc92BD86F8075d1DEcc58C7F4E0107f286b",
69
- decimals: 18,
70
- },
71
82
  ],
72
83
  43114: [
73
84
  {
85
+ aliases: ['eth', 'weth'],
74
86
  symbol: "ETH",
75
87
  name: "Ethereum",
76
88
  address: "0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB",
77
89
  decimals: 18,
78
90
  },
79
91
  {
92
+ aliases: ['dai'],
80
93
  symbol: "DAI",
81
94
  name: "DAI Stable",
82
95
  address: "0xd586E7F844cEa2F87f50152665BCbc2C279D8d70",
83
96
  decimals: 18,
84
97
  },
85
98
  {
99
+ aliases: ['usdc'],
86
100
  symbol: "USDC",
87
101
  name: "USD Coin",
88
102
  address: "0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664",
89
103
  decimals: 6,
90
104
  },
91
105
  {
92
- symbol: "USDT",
106
+ aliases: ['usdt'],
107
+ symbol: "USDt",
93
108
  name: "Tether USD Coin",
109
+ address: "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",
110
+ decimals: 6,
111
+ },
112
+ {
113
+ aliases: ['usdt'],
114
+ symbol: "USDT.e",
115
+ name: "Tether USD",
94
116
  address: "0xc7198437980c041c805A1EDcbA50c1Ce5db95118",
95
117
  decimals: 6,
96
118
  },
97
119
  {
120
+ aliases: ["wbtc"],
98
121
  symbol: "WBTC",
99
122
  name: "Wrapped BTC",
100
123
  address: "0x50b7545627a5162F82A992c33b87aDc75187B218",
101
124
  decimals: 8,
102
125
  },
103
126
  ],
104
- };
127
+ } as Record<number, { aliases: string[], symbol: string, name: string, address: string, decimals: number }[]>;
@@ -17,7 +17,7 @@ export class Transaction extends Model<InferAttributes<Transaction>, InferCreati
17
17
 
18
18
  declare transactionHash: string;
19
19
 
20
- declare action: string;
20
+ declare actionId: string;
21
21
  declare bridger: string;
22
22
  declare requestTransactionHash: string;
23
23
 
@@ -42,6 +42,7 @@ export class Transaction extends Model<InferAttributes<Transaction>, InferCreati
42
42
  declare targetDelayUntil: CreationOptional<Date>;
43
43
 
44
44
  declare requestEvent: {
45
+ actionId: string;
45
46
  bridger: string;
46
47
  metadata: string;
47
48
  position: IPosition;
@@ -49,6 +50,16 @@ export class Transaction extends Model<InferAttributes<Transaction>, InferCreati
49
50
  targetChainId: number;
50
51
  };
51
52
  declare requestSentEvent: CreationOptional<{
53
+ actionId: string;
54
+ bridger: string;
55
+ metadata: string;
56
+ position: IPosition;
57
+ sourceChainId: number;
58
+ targetChainId: number;
59
+ requestTransactionHash: string;
60
+ }>;
61
+ declare committedEvent: CreationOptional<{
62
+ actionId: string;
52
63
  bridger: string;
53
64
  metadata: string;
54
65
  position: IPosition;
@@ -56,12 +67,8 @@ export class Transaction extends Model<InferAttributes<Transaction>, InferCreati
56
67
  targetChainId: number;
57
68
  requestTransactionHash: string;
58
69
  }>;
59
- declare committedEvent: CreationOptional<any>;
60
70
  declare completedEvent: CreationOptional<any>;
61
71
 
62
- declare position: any;
63
- declare metadata: CreationOptional<any>;
64
-
65
72
  declare status: CreationOptional<string>;
66
73
 
67
74
  declare createdAt: CreationOptional<Date>;
@@ -79,7 +86,7 @@ Transaction.init({
79
86
  requestBlockNumber: DataTypes.NUMBER,
80
87
 
81
88
  transactionHash: DataTypes.STRING,
82
- action: DataTypes.STRING,
89
+ actionId: DataTypes.STRING,
83
90
  bridger: DataTypes.STRING,
84
91
 
85
92
  sourceChainId: DataTypes.NUMBER,
@@ -129,9 +136,6 @@ Transaction.init({
129
136
  committedEvent: DataTypes.JSON,
130
137
  completedEvent: DataTypes.JSON,
131
138
 
132
- position: DataTypes.JSON,
133
- metadata: DataTypes.JSON,
134
-
135
139
  status: {
136
140
  type: DataTypes.STRING,
137
141
  defaultValue: 'pending'
@@ -5,37 +5,121 @@ import { Transaction } from "@/db";
5
5
  import { InteropXContract } from "@/typechain";
6
6
  import { ChainId } from "@/types";
7
7
  import { getContract, getRpcProviderUrl } from "@/utils";
8
- import { ethers } from "ethers";
8
+ import { BigNumber, ethers } from "ethers";
9
9
  import { MetaTransaction, OperationType } from "ethers-multisend";
10
10
 
11
+
12
+ const getBridgeAmounts = async (user: string, tokens: string[], chainId: ChainId) => {
13
+ const sourceChainProvider = new ethers.providers.JsonRpcProvider(getRpcProviderUrl(chainId));
14
+ const sourceWallet = new ethers.Wallet(config.privateKey, sourceChainProvider);
15
+ const contractAddress = addresses[chainId].interopXContract;
16
+ const contract = getContract<InteropXContract>(contractAddress, abi.interopXContract, sourceWallet);
17
+ const data = await contract.getBridgeAmounts(user, tokens);
18
+
19
+
20
+ return data.map((item, index) => ({
21
+ token: tokens[index],
22
+ deposit: item.deposit,
23
+ withdraw: item.withdraw,
24
+ }))
25
+ }
26
+
11
27
  export default async function (transaction: Transaction, type: 'source' | 'target') {
12
28
  const transactions: MetaTransaction[] = [];
13
29
  const logs: any[] = [];
14
30
 
15
- if (transaction.action !== 'withdraw') {
16
- throw new Error(`Invalid action: ${transaction.action}`)
31
+ if (transaction.actionId !== 'withdraw') {
32
+ throw new Error(`Invalid action: ${transaction.actionId}`)
17
33
  }
18
34
 
19
35
  if (type !== 'source') {
20
- throw new Error(`Type not supported: ${type}`)
36
+ throw new Error(`[WIP] Type not supported: ${type}`)
37
+ }
38
+
39
+ if (transaction.sourceStatus === 'pending') {
40
+ throw Error('Source transaction already processesing')
21
41
  }
22
42
 
23
- if (transaction.action === 'withdraw' && transaction.sourceStatus === 'pending') {
24
- throw Error('Cannot build data for pending withdraw transaction');
43
+ if (transaction.sourceStatus === 'pending') {
44
+ throw Error('Source transaction already processed')
25
45
  }
26
46
 
27
47
  if (!transaction.requestEvent) {
28
- throw Error('Cannot build data for transaction without requestEvent');
48
+ throw Error('Something went wrong, source transaction has no request event')
29
49
  }
30
50
 
31
- const { bridger, position, sourceChainId, targetChainId, metadata, } = transaction.requestEvent;
51
+ const { actionId, bridger, position, sourceChainId, targetChainId, metadata } = transaction.requestEvent;
32
52
 
33
- const sourceChainProvider = new ethers.providers.JsonRpcProvider(getRpcProviderUrl(targetChainId as ChainId));
53
+ const sourceChainProvider = new ethers.providers.JsonRpcProvider(getRpcProviderUrl(sourceChainId as ChainId));
34
54
  const sourceWallet = new ethers.Wallet(config.privateKey, sourceChainProvider);
35
55
  const contractAddress = addresses[sourceChainId].interopXContract;
36
56
  const contract = getContract<InteropXContract>(contractAddress, abi.interopXContract, sourceWallet);
37
57
 
58
+ const sourceToken = tokens[sourceChainId].find(t => t.address.toLowerCase() === position.withdraw[0].sourceToken.toLowerCase());
59
+
60
+ if (!sourceToken) {
61
+ throw Error('Source token not found')
62
+ }
63
+
64
+ const targetToken = tokens[targetChainId].find(t => t.address.toLowerCase() === position.withdraw[0].targetToken.toLowerCase());
65
+
66
+ if (!targetToken) {
67
+ throw Error('Target token not found')
68
+ }
69
+
70
+ if (!sourceToken.aliases.some(alias => targetToken.aliases.includes(alias))) {
71
+ throw Error('Source and target token must be the same')
72
+ }
73
+
74
+ const networks: ChainId[] = [137, 43114];
75
+ const networkUserData = {}
76
+ for (const network of networks) {
77
+ networkUserData[network] = await getBridgeAmounts(bridger, tokens[network].map(t => t.address), network)
78
+ }
79
+
80
+ for (const tokenSymbol of ["dai", "usdc", "usdt", "eth", "wbtc"]) {
81
+ let totalDeposit = BigNumber.from(0)
82
+ let totalWithdraw = BigNumber.from(0)
83
+
84
+ for (const network of networks) {
85
+ // on avax might we have 2 usdc/usdt tokens
86
+ const matchedTokens = tokens[network].filter(t => t.aliases.includes(tokenSymbol));
87
+
88
+ for (const matchedToken of matchedTokens) {
89
+ const data = networkUserData[network].find(t => t.token.toLowerCase() === matchedToken.address.toLowerCase());
90
+
91
+ if (data) {
92
+ totalDeposit = totalDeposit.add(data.deposit)
93
+ totalWithdraw = totalWithdraw.add(data.withdraw)
94
+ }
95
+ }
96
+
97
+ // on Mainent add weth too
98
+ if (tokenSymbol === "eth" && network === 1) {
99
+ const weth = tokens[1].find(t => t.symbol === 'WETH');
100
+
101
+ if (weth) {
102
+ const data = networkUserData[1].find(t => t.token.toLowerCase() === weth.address.toLowerCase());
103
+
104
+ if (data) {
105
+ totalDeposit = totalDeposit.add(data.deposit)
106
+ totalWithdraw = totalWithdraw.add(data.withdraw)
107
+ }
108
+ }
109
+ }
110
+
111
+ if (totalWithdraw.gt(totalDeposit)) {
112
+ throw Error(`if withdraw > deposit, user has debt and we can't process the withdraw and reject it`)
113
+ }
114
+
115
+ if (totalWithdraw.lt(totalDeposit)) {
116
+ throw Error('Something went wrong')
117
+ }
118
+ }
119
+ }
120
+
38
121
  const { data } = await contract.populateTransaction.withdrawRequested(
122
+ actionId,
39
123
  bridger,
40
124
  position.withdraw[0].sourceToken,
41
125
  position.withdraw[0].targetToken,
@@ -5,9 +5,9 @@ import actions from "./actions";
5
5
  export const buildGnosisAction = async (transaction: Transaction, type: 'source' | 'target') => {
6
6
  // type = type || (transaction.sourceStatus === 'success' ? 'target' : 'source')
7
7
 
8
- if (actions.hasOwnProperty(transaction.action)) {
8
+ if (actions.hasOwnProperty(transaction.actionId)) {
9
9
 
10
- const { transactions, logs } = await actions[transaction.action](transaction, type);
10
+ const { transactions, logs } = await actions[transaction.actionId](transaction, type);
11
11
 
12
12
  return {
13
13
  data: encodeMulti(transactions).data,
@@ -15,5 +15,5 @@ export const buildGnosisAction = async (transaction: Transaction, type: 'source'
15
15
  };
16
16
  }
17
17
 
18
- throw new Error(`Unknown action: ${transaction.action}`);
18
+ throw new Error(`Unknown action: ${transaction.actionId}`);
19
19
  }
@@ -0,0 +1,125 @@
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
+ sourceStatus: 'success',
60
+ committedEvent: {
61
+ [Op.eq]: null,
62
+ }
63
+ }
64
+ });
65
+
66
+ if (!transaction) {
67
+ continue;
68
+ }
69
+ transaction.targetStatus = 'success'
70
+ transaction.targetBlockNumber = event.blockNumber;
71
+ transaction.targetTransactionHash = event.transactionHash
72
+ transaction.committedEvent = {
73
+ actionId,
74
+ bridger,
75
+ position: {
76
+ withdraw: position.withdraw.map((v) => ({
77
+ sourceToken: v.sourceToken,
78
+ targetToken: v.targetToken,
79
+ amount: v.amount.toString()
80
+ })),
81
+ supply: position.supply.map((v) => ({
82
+ sourceToken: v.sourceToken,
83
+ targetToken: v.targetToken,
84
+ amount: v.amount.toString()
85
+ })),
86
+ },
87
+ sourceChainId: sourceChainId,
88
+ targetChainId: targetChainId,
89
+ metadata,
90
+ requestTransactionHash,
91
+ }
92
+
93
+ transaction.status = 'success';
94
+ await transaction.save()
95
+
96
+ this.logger.info(
97
+ `New bridge committed received: ${transactionHash} `
98
+ );
99
+ } catch (error) {
100
+ this.logger.error(error);
101
+ }
102
+ }
103
+
104
+ if (processedEvents > 0)
105
+ this.logger.info(`${processedEvents} events processed`);
106
+ }
107
+
108
+ async start(): Promise<void> {
109
+ this.contractAddress = addresses[this.chainId].interopXContract;
110
+
111
+ this.provider = new ethers.providers.JsonRpcProvider(
112
+ getRpcProviderUrl(this.chainId)
113
+ );
114
+
115
+ this.contract = getContract<InteropXContract>(
116
+ this.contractAddress,
117
+ abi.interopXContract,
118
+ new ethers.Wallet(config.privateKey!, this.provider)
119
+ );
120
+
121
+ await super.start()
122
+ }
123
+ }
124
+
125
+ export default SyncBridgeCommittedEvents;
@@ -40,10 +40,10 @@ class SyncBridgeRequestEvents extends BaseTask {
40
40
  continue;
41
41
  }
42
42
 
43
- const { bridger, position, sourceChainId, targetChainId, metadata } = event.args;
43
+ const { actionId, bridger, position, sourceChainId, targetChainId, metadata } = event.args;
44
44
 
45
45
  const uniqueIdentifier = {
46
- action: 'withdraw', //todo
46
+ actionId,
47
47
  bridger,
48
48
  requestTransactionHash: event.transactionHash,
49
49
  sourceChainId: sourceChainId.toNumber(),
@@ -61,10 +61,9 @@ class SyncBridgeRequestEvents extends BaseTask {
61
61
  await Transaction.create({
62
62
  transactionHash,
63
63
  ...uniqueIdentifier,
64
- position,
65
- metadata,
66
64
  requestBlockNumber: event.blockNumber,
67
65
  requestEvent: {
66
+ actionId,
68
67
  bridger,
69
68
  position: {
70
69
  withdraw: position.withdraw.map((v) => ({
@@ -41,10 +41,10 @@ class SyncBridgeRequestSentEvents extends BaseTask {
41
41
  continue;
42
42
  }
43
43
 
44
- const { bridger, position, sourceChainId, targetChainId, requestTransactionHash, metadata } = event.args;
44
+ const { actionId, bridger, position, sourceChainId, targetChainId, requestTransactionHash, metadata } = event.args;
45
45
 
46
46
  const uniqueIdentifier = {
47
- action: 'withdraw',
47
+ actionId,
48
48
  bridger,
49
49
  requestTransactionHash,
50
50
  sourceChainId: sourceChainId,
@@ -55,8 +55,8 @@ class SyncBridgeRequestSentEvents extends BaseTask {
55
55
 
56
56
  const transaction = await Transaction.findOne({
57
57
  where: {
58
- transactionHash, sourceStatus: {
59
- [Op.ne]: 'success',
58
+ transactionHash, requestSentEvent: {
59
+ [Op.eq]: null,
60
60
  }
61
61
  }
62
62
  });
@@ -68,6 +68,7 @@ class SyncBridgeRequestSentEvents extends BaseTask {
68
68
  transaction.sourceBlockNumber = event.blockNumber;
69
69
  transaction.sourceTransactionHash = event.transactionHash
70
70
  transaction.requestSentEvent = {
71
+ actionId,
71
72
  bridger,
72
73
  position: {
73
74
  withdraw: position.withdraw.map((v) => ({
@@ -8,6 +8,7 @@ import AutoUpdateTask from "./AutoUpdateTask";
8
8
  import SyncBridgeRequestEvents from "./InteropXContract/SyncBridgeRequestEvents";
9
9
  import ProccessBridgeRequestEvents from "./InteropXContract/ProcessBridgeRequestEvents";
10
10
  import SyncBridgeRequestSentEvents from "./InteropXContract/SyncBridgeRequestSentEvents";
11
+ import SyncBridgeCommittedEvents from "./InteropXContract/SyncBridgeCommittedEvents";
11
12
 
12
13
  export class Tasks {
13
14
 
@@ -23,6 +24,9 @@ export class Tasks {
23
24
  new SyncBridgeRequestSentEvents({ chainId: 137 }),
24
25
  new SyncBridgeRequestSentEvents({ chainId: 43114 }),
25
26
 
27
+ new SyncBridgeCommittedEvents({ chainId: 137 }),
28
+ new SyncBridgeCommittedEvents({ chainId: 43114 }),
29
+
26
30
  new ProccessBridgeRequestEvents({ chainId: 137 }),
27
31
  new ProccessBridgeRequestEvents({ chainId: 43114 }),
28
32
  ];