@reyaxyz/common 0.136.0 → 0.138.0

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 (58) hide show
  1. package/README.md +1 -1
  2. package/dist/services/getSocketAddresses.js +12 -22
  3. package/dist/services/getSocketAddresses.js.map +1 -1
  4. package/dist/transactions/executeTransaction.js +45 -4
  5. package/dist/transactions/executeTransaction.js.map +1 -1
  6. package/dist/types/services/getSocketAddresses.d.ts +32 -2
  7. package/dist/types/services/getSocketAddresses.d.ts.map +1 -1
  8. package/dist/types/transactions/executeTransaction.d.ts.map +1 -1
  9. package/dist/types/types.d.ts +1 -9
  10. package/dist/types/types.d.ts.map +1 -1
  11. package/dist/types/utils/network.d.ts +1 -1
  12. package/dist/types/utils/network.d.ts.map +1 -1
  13. package/dist/types/utils/token/batch-token-getters.d.ts +22 -0
  14. package/dist/types/utils/token/batch-token-getters.d.ts.map +1 -0
  15. package/dist/types/utils/token/index.d.ts +6 -0
  16. package/dist/types/utils/token/index.d.ts.map +1 -0
  17. package/dist/types/utils/token/token-getters.d.ts +23 -0
  18. package/dist/types/utils/token/token-getters.d.ts.map +1 -0
  19. package/dist/types/utils/token/token-info-getters.d.ts +6 -0
  20. package/dist/types/utils/token/token-info-getters.d.ts.map +1 -0
  21. package/dist/types/utils/token/token-info.d.ts +3 -0
  22. package/dist/types/utils/token/token-info.d.ts.map +1 -0
  23. package/dist/types/utils/token/utils.d.ts +7 -0
  24. package/dist/types/utils/token/utils.d.ts.map +1 -0
  25. package/dist/types.js.map +1 -1
  26. package/dist/utils/network.js +2 -0
  27. package/dist/utils/network.js.map +1 -1
  28. package/dist/utils/token/batch-token-getters.js +175 -0
  29. package/dist/utils/token/batch-token-getters.js.map +1 -0
  30. package/dist/utils/token/index.js +22 -0
  31. package/dist/utils/token/index.js.map +1 -0
  32. package/dist/utils/token/token-getters.js +104 -0
  33. package/dist/utils/token/token-getters.js.map +1 -0
  34. package/dist/utils/token/token-info-getters.js +49 -0
  35. package/dist/utils/token/token-info-getters.js.map +1 -0
  36. package/dist/utils/{token-info.js → token/token-info.js} +1 -1
  37. package/dist/utils/token/token-info.js.map +1 -0
  38. package/dist/utils/token/utils.js +46 -0
  39. package/dist/utils/token/utils.js.map +1 -0
  40. package/package.json +2 -2
  41. package/src/services/getSocketAddresses.ts +3 -23
  42. package/src/transactions/executeTransaction.ts +51 -1
  43. package/src/types.ts +1 -11
  44. package/src/utils/network.ts +5 -2
  45. package/src/utils/token/batch-token-getters.ts +111 -0
  46. package/src/utils/token/index.ts +5 -0
  47. package/src/utils/token/token-getters.ts +71 -0
  48. package/src/utils/token/token-info-getters.ts +84 -0
  49. package/src/utils/{token-info.ts → token/token-info.ts} +1 -1
  50. package/src/utils/token/utils.ts +49 -0
  51. package/dist/types/utils/token-info.d.ts +0 -3
  52. package/dist/types/utils/token-info.d.ts.map +0 -1
  53. package/dist/types/utils/token.d.ts +0 -49
  54. package/dist/types/utils/token.d.ts.map +0 -1
  55. package/dist/utils/token-info.js.map +0 -1
  56. package/dist/utils/token.js +0 -340
  57. package/dist/utils/token.js.map +0 -1
  58. package/src/utils/token.ts +0 -317
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.convertToAddress = exports.getERC20TokenContract = exports.scale = exports.descale = void 0;
4
+ var ethers_1 = require("ethers");
5
+ var descale = function (tokenDecimals) {
6
+ var f = function (value) {
7
+ return Number(ethers_1.ethers.formatUnits(value.toString(), tokenDecimals));
8
+ };
9
+ return f;
10
+ };
11
+ exports.descale = descale;
12
+ var scale = function (tokenDecimals) {
13
+ return function (value) {
14
+ // Convert the number to a string
15
+ var valueStr = value.toString();
16
+ // Split the string into whole and fractional parts
17
+ // eslint-disable-next-line prefer-const
18
+ var _a = valueStr.split('.'), whole = _a[0], _b = _a[1], fractional = _b === void 0 ? '' : _b;
19
+ // Ensure the fractional part is the correct length, padding with zeros if necessary
20
+ fractional = fractional
21
+ .padEnd(tokenDecimals, '0')
22
+ .substring(0, tokenDecimals);
23
+ // Concatenate the whole part with the correctly length-limited fractional part
24
+ var scaledValueStr = whole + fractional;
25
+ // Convert the concatenated string to a BigInt, assuming it represents a value in wei (or equivalent smallest unit)
26
+ // This is safe as we're not losing precision - just scaling the number to its smallest unit representation
27
+ return BigInt(scaledValueStr);
28
+ };
29
+ };
30
+ exports.scale = scale;
31
+ var getERC20TokenContract = function (tokenAddress, subject) {
32
+ var abi = [
33
+ "function approve(address, uint256) external returns (bool)",
34
+ "function balanceOf(address) external view returns (uint256)",
35
+ "function allowance(address,address) external view returns (uint256)",
36
+ "function approve(address,uint256) external returns (bool)",
37
+ ];
38
+ var contract = new ethers_1.ethers.Contract(tokenAddress, abi, subject);
39
+ return contract;
40
+ };
41
+ exports.getERC20TokenContract = getERC20TokenContract;
42
+ var convertToAddress = function (str) {
43
+ return str.toLowerCase();
44
+ };
45
+ exports.convertToAddress = convertToAddress;
46
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"/","sources":["utils/token/utils.ts"],"names":[],"mappings":";;;AAAA,iCAAgC;AAGzB,IAAM,OAAO,GAAG,UAAC,aAAqB;IAC3C,IAAM,CAAC,GAAG,UAAC,KAAa;QACtB,OAAO,MAAM,CAAC,eAAM,CAAC,WAAW,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,aAAa,CAAC,CAAC,CAAC;IACrE,CAAC,CAAC;IAEF,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AANW,QAAA,OAAO,WAMlB;AAEK,IAAM,KAAK,GAAG,UAAC,aAAqB;IACzC,OAAO,UAAC,KAAa;QACnB,iCAAiC;QACjC,IAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAC;QAClC,mDAAmD;QACnD,wCAAwC;QACpC,IAAA,KAA2B,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,EAA7C,KAAK,QAAA,EAAE,UAAe,EAAf,UAAU,mBAAG,EAAE,KAAuB,CAAC;QACnD,oFAAoF;QACpF,UAAU,GAAG,UAAU;aACpB,MAAM,CAAC,aAAa,EAAE,GAAG,CAAC;aAC1B,SAAS,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;QAC/B,+EAA+E;QAC/E,IAAM,cAAc,GAAG,KAAK,GAAG,UAAU,CAAC;QAC1C,mHAAmH;QACnH,2GAA2G;QAC3G,OAAO,MAAM,CAAC,cAAc,CAAC,CAAC;IAChC,CAAC,CAAC;AACJ,CAAC,CAAC;AAjBW,QAAA,KAAK,SAiBhB;AAEK,IAAM,qBAAqB,GAAG,UACnC,YAAoB,EACpB,OAAwC;IAExC,IAAM,GAAG,GAAa;QACpB,4DAA4D;QAC5D,6DAA6D;QAC7D,qEAAqE;QACrE,2DAA2D;KAC5D,CAAC;IAEF,IAAM,QAAQ,GAAG,IAAI,eAAM,CAAC,QAAQ,CAAC,YAAY,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IAEjE,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC;AAdW,QAAA,qBAAqB,yBAchC;AAEK,IAAM,gBAAgB,GAAG,UAAC,GAAW;IAC1C,OAAO,GAAG,CAAC,WAAW,EAAa,CAAC;AACtC,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B","sourcesContent":["import { ethers } from 'ethers';\nimport { Address } from '../../types';\n\nexport const descale = (tokenDecimals: number) => {\n const f = (value: bigint) => {\n return Number(ethers.formatUnits(value.toString(), tokenDecimals));\n };\n\n return f;\n};\n\nexport const scale = (tokenDecimals: number): ((value: number) => bigint) => {\n return (value: number): bigint => {\n // Convert the number to a string\n const valueStr = value.toString();\n // Split the string into whole and fractional parts\n // eslint-disable-next-line prefer-const\n let [whole, fractional = ''] = valueStr.split('.');\n // Ensure the fractional part is the correct length, padding with zeros if necessary\n fractional = fractional\n .padEnd(tokenDecimals, '0')\n .substring(0, tokenDecimals);\n // Concatenate the whole part with the correctly length-limited fractional part\n const scaledValueStr = whole + fractional;\n // Convert the concatenated string to a BigInt, assuming it represents a value in wei (or equivalent smallest unit)\n // This is safe as we're not losing precision - just scaling the number to its smallest unit representation\n return BigInt(scaledValueStr);\n };\n};\n\nexport const getERC20TokenContract = (\n tokenAddress: string,\n subject: ethers.Signer | ethers.Provider,\n): ethers.Contract => {\n const abi: string[] = [\n `function approve(address, uint256) external returns (bool)`,\n `function balanceOf(address) external view returns (uint256)`,\n `function allowance(address,address) external view returns (uint256)`,\n `function approve(address,uint256) external returns (bool)`,\n ];\n\n const contract = new ethers.Contract(tokenAddress, abi, subject);\n\n return contract;\n};\n\nexport const convertToAddress = (str: string): Address => {\n return str.toLowerCase() as Address;\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reyaxyz/common",
3
- "version": "0.136.0",
3
+ "version": "0.138.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org"
@@ -43,5 +43,5 @@
43
43
  "generate:coverage-badges": "npx istanbul-badges-readme --silent"
44
44
  },
45
45
  "packageManager": "pnpm@8.3.1",
46
- "gitHead": "51ccbadf06f7980fbcbaac1a1fc43157d6c90ad5"
46
+ "gitHead": "92eb511fa25ff6a91083d493a4d566aed5a3cd96"
47
47
  }
@@ -2,7 +2,6 @@ import {
2
2
  ReyaChainId,
3
3
  GetSocketConnectorsParams,
4
4
  Address,
5
- GetSocketControllerParams,
6
5
  MoneyInOutChainId,
7
6
  GetSocketVaultParams,
8
7
  SocketTokenConnectors,
@@ -12,8 +11,8 @@ import {
12
11
  import {
13
12
  getMoneyInOutNetworksFromReyaChainId,
14
13
  getReyaNetworkFromMoneyInOutChainId,
15
- } from '../utils/network';
16
- import { convertToAddress } from '../utils/token';
14
+ convertToAddress,
15
+ } from '../utils';
17
16
 
18
17
  import * as REYA_CRONOS from '../utils/socket/reyaCronos.json';
19
18
  import * as REYA_NETWORK from '../utils/socket/reyaNetwork.json';
@@ -62,7 +61,7 @@ export type SocketConnectorAddresses = {
62
61
  ['FAST']?: string;
63
62
  };
64
63
 
65
- const getSocketDeploymentJSON = (
64
+ export const getSocketDeploymentJSON = (
66
65
  reyaChainId: ReyaChainId,
67
66
  ): SocketDeploymentAddresses => {
68
67
  switch (reyaChainId) {
@@ -111,25 +110,6 @@ export const getSocketConnectors = (
111
110
  };
112
111
  };
113
112
 
114
- export const getSocketController = (
115
- params: GetSocketControllerParams,
116
- ): Address => {
117
- const deploymentJSON = getSocketDeploymentJSON(params.reyaChainId);
118
- const controller = (
119
- deploymentJSON?.[params.reyaChainId]?.[
120
- params.tokenName
121
- ] as SocketAppChainAddresses
122
- )?.[SocketSuperBridgeContracts.Controller];
123
-
124
- if (!controller) {
125
- throw new Error(
126
- `getSocketController: controller not found ${JSON.stringify(params)}`,
127
- );
128
- }
129
-
130
- return convertToAddress(controller);
131
- };
132
-
133
113
  export const getSocketVault = (params: GetSocketVaultParams): Address => {
134
114
  const reyaChainId = getReyaNetworkFromMoneyInOutChainId(
135
115
  params.moneyInOutChainId,
@@ -4,6 +4,7 @@ import { ContractType, getAddress } from './contractAddresses';
4
4
  import { abi } from './abis/Errors.json';
5
5
  import { ErrorDecoder } from 'ethers-decode-error';
6
6
  import type { DecodedError } from 'ethers-decode-error';
7
+ import { getGasBuffer } from './txHelpers';
7
8
 
8
9
  const reyaChainIdRPCMapper: { [key: number]: string } = {
9
10
  [ReyaChainId.reyaNetwork]: 'https://rpc.reya.network',
@@ -68,6 +69,55 @@ export async function estimateGas(
68
69
  return { ...tx, gasLimit };
69
70
  }
70
71
 
72
+ async function estimateGasExternalChains(
73
+ signer: Signer | JsonRpcSigner,
74
+ data: string,
75
+ value: string,
76
+ chainId: number,
77
+ targetContract: ContractType | string,
78
+ ): Promise<
79
+ Transaction & {
80
+ gasLimit: bigint;
81
+ maxPriorityFeePerGas?: bigint;
82
+ maxFeePerGas?: bigint;
83
+ }
84
+ > {
85
+ const accountAddress = await signer.getAddress();
86
+
87
+ const contractAddress = Object.values(ContractType).includes(
88
+ targetContract as ContractType,
89
+ )
90
+ ? getAddress(chainId, targetContract as ContractType)
91
+ : targetContract;
92
+ const tx = {
93
+ from: accountAddress,
94
+ to: contractAddress,
95
+ data,
96
+ ...(value && value !== '0' ? { value: value } : {}),
97
+ };
98
+
99
+ let gasLimit: bigint = BigInt('5000000'); // hardcode to 5m gas limit if fails to get estimate
100
+
101
+ try {
102
+ const gasEstimate = await signer.estimateGas(tx);
103
+ gasLimit = getGasBuffer(gasEstimate);
104
+ } catch (error) {
105
+ const decodedError = await errorDecoder.decode(error);
106
+ const reason = customReasonMapper(decodedError);
107
+ console.error(
108
+ `Error simulating external transaction account address ${accountAddress} reason ${decodedError?.name} ${decodedError} ${error}`,
109
+ );
110
+ throw new Error(reason);
111
+ }
112
+
113
+ if (Object.values(ReyaChainId).includes(chainId as ReyaChainId)) {
114
+ const maxPriorityFeePerGas: bigint = BigInt('0');
115
+ const maxFeePerGas: bigint = BigInt('100000000');
116
+ return { ...tx, gasLimit, maxPriorityFeePerGas, maxFeePerGas };
117
+ }
118
+
119
+ return { ...tx, gasLimit };
120
+ }
71
121
  export async function executeTransaction(
72
122
  signer: Signer | JsonRpcSigner,
73
123
  data: string,
@@ -75,7 +125,7 @@ export async function executeTransaction(
75
125
  chainId: number,
76
126
  targetContract: ContractType | string,
77
127
  ) {
78
- const txData = await estimateGas(
128
+ const txData = await estimateGasExternalChains(
79
129
  signer,
80
130
  data,
81
131
  value,
package/src/types.ts CHANGED
@@ -1,5 +1,3 @@
1
- import { Signer } from 'ethers';
2
-
3
1
  export type Address = Lowercase<string>;
4
2
  export type TokenName = Uppercase<string>;
5
3
 
@@ -279,11 +277,6 @@ export type GetSocketConnectorsParams = {
279
277
  tokenName: TokenName;
280
278
  };
281
279
 
282
- export type GetSocketControllerParams = {
283
- reyaChainId: ReyaChainId;
284
- tokenName: TokenName;
285
- };
286
-
287
280
  export type GetSocketVaultParams = {
288
281
  moneyInOutChainId: MoneyInOutChainId;
289
282
  tokenName: TokenName;
@@ -418,11 +411,8 @@ export type GetFundingRateChartDataResult = {
418
411
  fundingRate: number;
419
412
  };
420
413
 
421
- export type GetERC20AllowanceParams = {
414
+ export type GetBalancesForBridgeArgs = {
422
415
  walletAddress: string;
423
- tokenAddress: LpPoolEntity['tokenAddress'];
424
- spenderAddress: string;
425
- subject: Signer;
426
416
  };
427
417
 
428
418
  export type DepthSimulationState = {
@@ -76,7 +76,10 @@ export const chainIdToExplorerURL: {
76
76
  [ReyaChainId.reyaCronos]: 'https://reya-cronos.blockscout.com',
77
77
  };
78
78
 
79
- export const ChainRpcUrls: { [key in MoneyInOutChainId]: string[] } = {
79
+ export const ChainRpcUrls: {
80
+ [key in MoneyInOutChainId | ReyaChainId]: string[];
81
+ } = {
82
+ [ReyaChainId.reyaNetwork]: ['https://rpc.reya.network'],
80
83
  [MoneyInOutChainId.ethereumMainnet]: [
81
84
  'https://mainnet.gateway.tenderly.co',
82
85
  'https://eth.llamarpc.com',
@@ -118,7 +121,7 @@ export const ChainRpcUrls: { [key in MoneyInOutChainId]: string[] } = {
118
121
  'https://base.gateway.tenderly.co/2LHAD54IBvgXiVQdhE9mIF',
119
122
  ],
120
123
  // Add the rest of the mainnet URLs above
121
-
124
+ [ReyaChainId.reyaCronos]: ['https://rpc.reya-cronos.gelato.digital'],
122
125
  [MoneyInOutChainId.polygonMumbai]: [
123
126
  'https://polygon-mumbai.gateway.tenderly.co',
124
127
  'https://polygon-mumbai-bor-rpc.publicnode.com',
@@ -0,0 +1,111 @@
1
+ import { ethers } from 'ethers';
2
+ import { MoneyInOutChainId, ReyaChainId } from '../../types';
3
+ import { ChainRpcUrls } from '../network';
4
+ import { exponentialBackoff } from '../retry';
5
+ import { descale, getERC20TokenContract } from './utils';
6
+
7
+ export type GetETHBalanceBatchArgs = {
8
+ walletAddress: string;
9
+ chain: MoneyInOutChainId | ReyaChainId;
10
+ };
11
+
12
+ export type GetERC20BalanceBatchArgs = {
13
+ tokenAddress: string;
14
+ tokenDecimals: number;
15
+ walletAddress: string;
16
+ chain: MoneyInOutChainId | ReyaChainId;
17
+ };
18
+
19
+ export type GetERC20AllowanceBatchArgs = {
20
+ tokenAddress: string;
21
+ tokenDecimals: number;
22
+ walletAddress: string;
23
+ spenderAddress: string;
24
+ chain: MoneyInOutChainId | ReyaChainId;
25
+ };
26
+
27
+ export const getETHBalanceBatch = async ({
28
+ walletAddress,
29
+ chain,
30
+ }: GetETHBalanceBatchArgs): Promise<number> => {
31
+ const rpcUrls = ChainRpcUrls[chain];
32
+ if (!rpcUrls || rpcUrls.length === 0) {
33
+ throw new Error('No RPC URLs configured for the chain: ' + chain);
34
+ }
35
+
36
+ let lastError = null;
37
+
38
+ for (const url of rpcUrls) {
39
+ try {
40
+ const provider = new ethers.JsonRpcProvider(url);
41
+ const currentBalance = await exponentialBackoff(() =>
42
+ provider.getBalance(ethers.getAddress(walletAddress)),
43
+ );
44
+ return descale(18)(currentBalance);
45
+ } catch (error) {
46
+ lastError = error;
47
+ }
48
+ }
49
+
50
+ throw new Error('All RPC URLs failed; last error: ' + lastError);
51
+ };
52
+
53
+ export const getERC20BalanceBatch = async ({
54
+ tokenAddress,
55
+ tokenDecimals,
56
+ walletAddress,
57
+ chain,
58
+ }: GetERC20BalanceBatchArgs): Promise<number> => {
59
+ const rpcUrls = ChainRpcUrls[chain];
60
+ if (!rpcUrls || rpcUrls.length === 0) {
61
+ throw new Error('No RPC URLs configured for the chain: ' + chain);
62
+ }
63
+
64
+ let lastError = null;
65
+
66
+ for (const url of rpcUrls) {
67
+ try {
68
+ const provider = new ethers.JsonRpcProvider(url);
69
+ const token = getERC20TokenContract(tokenAddress, provider);
70
+ const currentBalance = await token.balanceOf(walletAddress);
71
+
72
+ return descale(tokenDecimals)(currentBalance);
73
+ } catch (error) {
74
+ lastError = error;
75
+ }
76
+ }
77
+
78
+ throw new Error('All RPC URLs failed; last error: ' + lastError);
79
+ };
80
+
81
+ export const getERC20AllowanceBatch = async ({
82
+ tokenAddress,
83
+ tokenDecimals,
84
+ walletAddress,
85
+ spenderAddress,
86
+ chain,
87
+ }: GetERC20AllowanceBatchArgs): Promise<number> => {
88
+ const rpcUrls = ChainRpcUrls[chain];
89
+ if (!rpcUrls || rpcUrls.length === 0) {
90
+ throw new Error('No RPC URLs configured for the chain: ' + chain);
91
+ }
92
+
93
+ let lastError = null;
94
+
95
+ for (const url of rpcUrls) {
96
+ try {
97
+ const provider = new ethers.JsonRpcProvider(url);
98
+ const token = getERC20TokenContract(tokenAddress, provider);
99
+ const currentBalance = await token.allowance(
100
+ walletAddress,
101
+ spenderAddress,
102
+ );
103
+
104
+ return descale(tokenDecimals)(currentBalance);
105
+ } catch (error) {
106
+ lastError = error;
107
+ }
108
+ }
109
+
110
+ throw new Error('All RPC URLs failed; last error: ' + lastError);
111
+ };
@@ -0,0 +1,5 @@
1
+ export * from './token-getters';
2
+ export * from './batch-token-getters';
3
+ export * from './token-info-getters';
4
+ export * from './utils';
5
+ export * from './token-info';
@@ -0,0 +1,71 @@
1
+ import { ethers } from 'ethers';
2
+ import { exponentialBackoff } from '../retry';
3
+ import { LpPoolEntity } from '../../types';
4
+ import { getERC20TokenContract, scale, descale } from './utils';
5
+
6
+ export type GetERC20BalanceArgs = {
7
+ tokenAddress: string;
8
+ tokenDecimals: number;
9
+ walletAddress: string;
10
+ subject: ethers.Signer | ethers.Provider;
11
+ };
12
+
13
+ export type GetETHBalanceArgs = {
14
+ walletAddress: string;
15
+ subject: ethers.Signer | ethers.Provider;
16
+ };
17
+
18
+ export type GetERC20AllowanceArgs = {
19
+ walletAddress: string;
20
+ tokenAddress: LpPoolEntity['tokenAddress'];
21
+ tokenDecimals: number;
22
+ spenderAddress: string;
23
+ subject: ethers.Signer;
24
+ };
25
+
26
+ export const getERC20Allowance = async ({
27
+ walletAddress,
28
+ tokenAddress,
29
+ tokenDecimals,
30
+ spenderAddress,
31
+ subject,
32
+ }: GetERC20AllowanceArgs): Promise<number> => {
33
+ const tokenContract = getERC20TokenContract(tokenAddress, subject);
34
+
35
+ const allowance = await exponentialBackoff(() =>
36
+ tokenContract.allowance(walletAddress, spenderAddress),
37
+ );
38
+
39
+ return BigInt(allowance) > scale(tokenDecimals)(Number.MAX_SAFE_INTEGER)
40
+ ? Number.MAX_SAFE_INTEGER
41
+ : descale(tokenDecimals)(allowance);
42
+ };
43
+
44
+ export const getERC20Balance = async ({
45
+ tokenAddress,
46
+ tokenDecimals,
47
+ walletAddress,
48
+ subject,
49
+ }: GetERC20BalanceArgs): Promise<number> => {
50
+ const token = getERC20TokenContract(tokenAddress, subject);
51
+
52
+ const currentBalance = await exponentialBackoff(() =>
53
+ token.balanceOf(walletAddress),
54
+ );
55
+
56
+ return descale(tokenDecimals)(currentBalance);
57
+ };
58
+
59
+ export const getETHBalance = async ({
60
+ walletAddress,
61
+ subject,
62
+ }: GetETHBalanceArgs): Promise<number> => {
63
+ const provider = subject.provider;
64
+ if (!provider) throw new Error("User's provider not found");
65
+
66
+ const currentBalance = await exponentialBackoff(() =>
67
+ provider.getBalance(ethers.getAddress(walletAddress)),
68
+ );
69
+
70
+ return descale(18)(currentBalance);
71
+ };
@@ -0,0 +1,84 @@
1
+ import { TOKEN_INFO } from './token-info';
2
+ import {
3
+ Address,
4
+ MoneyInOutChainId,
5
+ ReyaChainId,
6
+ TokenInfo,
7
+ TokenName,
8
+ } from '../../types';
9
+ import { convertToAddress } from './utils';
10
+
11
+ export const getTokenInfoByAddress = (
12
+ tokenAddressParam: Address | string,
13
+ chainId?: ReyaChainId | MoneyInOutChainId,
14
+ ): TokenInfo => {
15
+ const tokenAddress =
16
+ typeof tokenAddressParam === 'string'
17
+ ? convertToAddress(tokenAddressParam)
18
+ : tokenAddressParam;
19
+
20
+ if (chainId) {
21
+ const tokenInfo = TOKEN_INFO[chainId].find(
22
+ (tokenInfo) => tokenInfo.address === tokenAddress,
23
+ );
24
+ if (!tokenInfo) {
25
+ throw new Error(
26
+ `getTokenInfoByAddress: no token info found [chainId ${chainId}, token address ${tokenAddress}]`,
27
+ );
28
+ }
29
+ return tokenInfo;
30
+ } else {
31
+ for (const chainId in TOKEN_INFO) {
32
+ const tokenInfos =
33
+ TOKEN_INFO[chainId as unknown as keyof typeof TOKEN_INFO];
34
+ const tokenInfo = tokenInfos.find(
35
+ (tokenInfo) => tokenInfo.address === tokenAddress,
36
+ );
37
+ if (tokenInfo) {
38
+ return tokenInfo;
39
+ }
40
+ }
41
+ throw new Error(
42
+ `getTokenInfoByAddress: no token info found [token address ${tokenAddress}]`,
43
+ );
44
+ }
45
+ };
46
+
47
+ export const getTokenInfoByName = (
48
+ tokenName: TokenName,
49
+ chainId: ReyaChainId | MoneyInOutChainId,
50
+ ): TokenInfo => {
51
+ const tokenInfo = TOKEN_INFO[chainId].find(
52
+ (tokenInfo) => tokenInfo.name === tokenName,
53
+ );
54
+
55
+ if (!tokenInfo) {
56
+ throw new Error(
57
+ `getTokenInfoByName: no token info found [chain id ${chainId}, token name ${tokenName}]`,
58
+ );
59
+ }
60
+
61
+ return tokenInfo;
62
+ };
63
+
64
+ export const getTokenInfosByChain = (
65
+ chainId: ReyaChainId | MoneyInOutChainId,
66
+ ): TokenInfo[] => {
67
+ return TOKEN_INFO[chainId];
68
+ };
69
+
70
+ export const getRUSDUnderlyingTokenInfo = (
71
+ chainId: ReyaChainId | MoneyInOutChainId,
72
+ ): TokenInfo => {
73
+ const tokenInfo = TOKEN_INFO[chainId].find(
74
+ (tokenInfo) => tokenInfo.isRUSDUnderlying === true,
75
+ );
76
+
77
+ if (!tokenInfo) {
78
+ throw new Error(
79
+ `getRUSDUnderlyingTokenInfo: no token info found [chain id ${chainId}]`,
80
+ );
81
+ }
82
+
83
+ return tokenInfo;
84
+ };
@@ -1,4 +1,4 @@
1
- import { MoneyInOutChainId, ReyaChainId, TokenInfo } from '../types';
1
+ import { MoneyInOutChainId, ReyaChainId, TokenInfo } from '../../types';
2
2
 
3
3
  const defaultTokenThresholds: Pick<
4
4
  TokenInfo,
@@ -0,0 +1,49 @@
1
+ import { ethers } from 'ethers';
2
+ import { Address } from '../../types';
3
+
4
+ export const descale = (tokenDecimals: number) => {
5
+ const f = (value: bigint) => {
6
+ return Number(ethers.formatUnits(value.toString(), tokenDecimals));
7
+ };
8
+
9
+ return f;
10
+ };
11
+
12
+ export const scale = (tokenDecimals: number): ((value: number) => bigint) => {
13
+ return (value: number): bigint => {
14
+ // Convert the number to a string
15
+ const valueStr = value.toString();
16
+ // Split the string into whole and fractional parts
17
+ // eslint-disable-next-line prefer-const
18
+ let [whole, fractional = ''] = valueStr.split('.');
19
+ // Ensure the fractional part is the correct length, padding with zeros if necessary
20
+ fractional = fractional
21
+ .padEnd(tokenDecimals, '0')
22
+ .substring(0, tokenDecimals);
23
+ // Concatenate the whole part with the correctly length-limited fractional part
24
+ const scaledValueStr = whole + fractional;
25
+ // Convert the concatenated string to a BigInt, assuming it represents a value in wei (or equivalent smallest unit)
26
+ // This is safe as we're not losing precision - just scaling the number to its smallest unit representation
27
+ return BigInt(scaledValueStr);
28
+ };
29
+ };
30
+
31
+ export const getERC20TokenContract = (
32
+ tokenAddress: string,
33
+ subject: ethers.Signer | ethers.Provider,
34
+ ): ethers.Contract => {
35
+ const abi: string[] = [
36
+ `function approve(address, uint256) external returns (bool)`,
37
+ `function balanceOf(address) external view returns (uint256)`,
38
+ `function allowance(address,address) external view returns (uint256)`,
39
+ `function approve(address,uint256) external returns (bool)`,
40
+ ];
41
+
42
+ const contract = new ethers.Contract(tokenAddress, abi, subject);
43
+
44
+ return contract;
45
+ };
46
+
47
+ export const convertToAddress = (str: string): Address => {
48
+ return str.toLowerCase() as Address;
49
+ };
@@ -1,3 +0,0 @@
1
- import { MoneyInOutChainId, ReyaChainId, TokenInfo } from '../types';
2
- export declare const TOKEN_INFO: Record<ReyaChainId | MoneyInOutChainId, TokenInfo[]>;
3
- //# sourceMappingURL=token-info.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"token-info.d.ts","sourceRoot":"/","sources":["utils/token-info.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAWrE,eAAO,MAAM,UAAU,EAAE,MAAM,CAAC,WAAW,GAAG,iBAAiB,EAAE,SAAS,EAAE,CA2VzE,CAAC"}
@@ -1,49 +0,0 @@
1
- import { Provider } from 'ethers';
2
- import { Contract, Signer } from 'ethers';
3
- import { Address, GetERC20AllowanceParams, MoneyInOutChainId, ReyaChainId, TokenInfo, TokenName } from '../types';
4
- export declare const descale: (tokenDecimals: number) => (value: bigint) => number;
5
- export declare const scale: (tokenDecimals: number) => (value: number) => bigint;
6
- export declare const getERC20TokenContract: (tokenAddress: string, subject: Signer | Provider) => Contract;
7
- export declare const convertToAddress: (str: string) => Address;
8
- export declare const getTokenInfoByAddress: (tokenAddressParam: Address | string, chainId?: ReyaChainId | MoneyInOutChainId) => TokenInfo;
9
- export declare const getTokenInfoByName: (tokenName: TokenName, chainId: ReyaChainId | MoneyInOutChainId) => TokenInfo;
10
- export declare const getTokenInfosByChain: (chainId: ReyaChainId | MoneyInOutChainId) => TokenInfo[];
11
- export declare const getRUSDUnderlyingTokenInfo: (chainId: ReyaChainId | MoneyInOutChainId) => TokenInfo;
12
- export declare const getERC20Allowance: ({ walletAddress, tokenAddress, spenderAddress, subject, }: GetERC20AllowanceParams) => Promise<number>;
13
- export type GetERC20BalanceArgs = {
14
- tokenAddress: string;
15
- walletAddress: string;
16
- subject: Signer | Provider;
17
- };
18
- export type GetETHBalanceArgs = {
19
- walletAddress: string;
20
- subject: Signer | Provider;
21
- };
22
- export type GetETHBalanceBatchArgs = {
23
- walletAddress: string;
24
- chain: MoneyInOutChainId;
25
- };
26
- export type GetERC20BalanceBatchArgs = {
27
- tokenAddress: string;
28
- walletAddress: string;
29
- chain: MoneyInOutChainId;
30
- };
31
- export type GetReyaETHBalanceArgs = {
32
- walletAddress: string;
33
- chain: ReyaChainId;
34
- };
35
- export type GetReyaERC20BalanceArgs = {
36
- tokenAddress: string;
37
- walletAddress: string;
38
- chain: ReyaChainId;
39
- };
40
- export type GetBalancesForBridgeArgs = {
41
- walletAddress: string;
42
- };
43
- export declare const getERC20Balance: ({ tokenAddress, walletAddress, subject, }: GetERC20BalanceArgs) => Promise<number>;
44
- export declare const getETHBalance: ({ walletAddress, subject, }: GetETHBalanceArgs) => Promise<number>;
45
- export declare const getETHBalanceBatch: ({ walletAddress, chain, }: GetETHBalanceBatchArgs) => Promise<number>;
46
- export declare const getERC20BalanceBatch: ({ tokenAddress, walletAddress, chain, }: GetERC20BalanceBatchArgs) => Promise<number>;
47
- export declare const getReyaETHBalance: ({ walletAddress, chain, }: GetReyaETHBalanceArgs) => Promise<number>;
48
- export declare const getReyaERC20Balance: ({ tokenAddress, walletAddress, chain, }: GetReyaERC20BalanceArgs) => Promise<number>;
49
- //# sourceMappingURL=token.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"token.d.ts","sourceRoot":"/","sources":["utils/token.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAE1C,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAG1C,OAAO,EACL,OAAO,EACP,uBAAuB,EACvB,iBAAiB,EACjB,WAAW,EACX,SAAS,EACT,SAAS,EACV,MAAM,UAAU,CAAC;AAElB,eAAO,MAAM,OAAO,kBAAmB,MAAM,aACzB,MAAM,WAKzB,CAAC;AAEF,eAAO,MAAM,KAAK,kBAAmB,MAAM,aAAY,MAAM,KAAK,MAiBjE,CAAC;AAEF,eAAO,MAAM,qBAAqB,iBAClB,MAAM,WACX,MAAM,GAAG,QAAQ,KACzB,QAWF,CAAC;AAEF,eAAO,MAAM,gBAAgB,QAAS,MAAM,KAAG,OAE9C,CAAC;AAEF,eAAO,MAAM,qBAAqB,sBACb,OAAO,GAAG,MAAM,YACzB,WAAW,GAAG,iBAAiB,KACxC,SA+BF,CAAC;AAEF,eAAO,MAAM,kBAAkB,cAClB,SAAS,WACX,WAAW,GAAG,iBAAiB,KACvC,SAYF,CAAC;AAEF,eAAO,MAAM,oBAAoB,YACtB,WAAW,GAAG,iBAAiB,KACvC,SAAS,EAEX,CAAC;AAEF,eAAO,MAAM,0BAA0B,YAC5B,WAAW,GAAG,iBAAiB,KACvC,SAYF,CAAC;AAEF,eAAO,MAAM,iBAAiB,8DAK3B,uBAAuB,KAAG,QAAQ,MAAM,CAW1C,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,MAAM,GAAG,QAAQ,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,MAAM,GAAG,QAAQ,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,sBAAsB,GAAG;IACnC,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,iBAAiB,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG;IACrC,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,iBAAiB,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IAClC,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,WAAW,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG;IACpC,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,WAAW,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG;IACrC,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,eAAO,MAAM,eAAe,8CAIzB,mBAAmB,KAAG,QAAQ,MAAM,CAUtC,CAAC;AAEF,eAAO,MAAM,aAAa,gCAGvB,iBAAiB,KAAG,QAAQ,MAAM,CASpC,CAAC;AAEF,eAAO,MAAM,kBAAkB,8BAG5B,sBAAsB,KAAG,QAAQ,MAAM,CAqBzC,CAAC;AAEF,eAAO,MAAM,oBAAoB,4CAI9B,wBAAwB,KAAG,QAAQ,MAAM,CAsB3C,CAAC;AAEF,eAAO,MAAM,iBAAiB,8BAG3B,qBAAqB,KAAG,QAAQ,MAAM,CAexC,CAAC;AAEF,eAAO,MAAM,mBAAmB,4CAI7B,uBAAuB,KAAG,QAAQ,MAAM,CAiB1C,CAAC"}