@morpho-org/blue-sdk 1.0.1 → 1.0.3

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 (150) hide show
  1. package/package.json +10 -7
  2. package/src/addresses.ts +247 -0
  3. package/src/chain/chain.constants.ts +235 -0
  4. package/src/chain/chain.test.ts +51 -0
  5. package/src/chain/chain.types.ts +42 -0
  6. package/src/chain/chain.utils.ts +44 -0
  7. package/src/constants.ts +18 -0
  8. package/src/errors.ts +75 -0
  9. package/src/ethers/ethers.test.ts +17 -0
  10. package/src/ethers/safeGetAddress.ts +4 -0
  11. package/src/ethers/safeParseUnits.ts +29 -0
  12. package/src/evm.ts +172 -0
  13. package/src/helpers/format/format.test.ts +340 -0
  14. package/src/helpers/format/format.ts +416 -0
  15. package/src/helpers/getChecksumedAddress.ts +15 -0
  16. package/{lib/helpers/isZeroAddressOrUnset.d.ts → src/helpers/isZeroAddressOrUnset.ts} +7 -1
  17. package/src/helpers/locale.ts +108 -0
  18. package/src/holding/Holding.ts +109 -0
  19. package/src/market/Market.ts +479 -0
  20. package/src/market/MarketConfig.ts +108 -0
  21. package/src/market/MarketUtils.test.ts +25 -0
  22. package/src/market/MarketUtils.ts +467 -0
  23. package/src/maths/AdaptiveCurveIrmLib.ts +143 -0
  24. package/src/maths/MathLib.ts +208 -0
  25. package/src/maths/MathUtils.ts +31 -0
  26. package/src/maths/SharesMath.ts +40 -0
  27. package/src/notifications.ts +167 -0
  28. package/src/position/Position.ts +251 -0
  29. package/src/signatures/index.ts +18 -0
  30. package/src/signatures/manager.ts +50 -0
  31. package/src/signatures/permit.ts +126 -0
  32. package/src/signatures/permit2.ts +120 -0
  33. package/src/signatures/types.ts +18 -0
  34. package/src/signatures/utils.ts +83 -0
  35. package/src/tests/mocks/markets.ts +110 -0
  36. package/src/token/ERC20Metadata.ts +124 -0
  37. package/src/token/Token.ts +83 -0
  38. package/src/token/TokenNamespace.ts +76 -0
  39. package/src/token/WrappedToken.ts +142 -0
  40. package/src/types.ts +37 -0
  41. package/src/user/User.ts +32 -0
  42. package/src/user/user.types.ts +25 -0
  43. package/src/vault/Vault.ts +370 -0
  44. package/src/vault/VaultAllocation.ts +58 -0
  45. package/src/vault/VaultConfig.ts +55 -0
  46. package/src/vault/VaultUtils.ts +47 -0
  47. package/lib/addresses.d.ts +0 -168
  48. package/lib/addresses.js +0 -169
  49. package/lib/chain/chain.constants.d.ts +0 -3
  50. package/lib/chain/chain.constants.js +0 -232
  51. package/lib/chain/chain.types.d.ts +0 -20
  52. package/lib/chain/chain.types.js +0 -30
  53. package/lib/chain/chain.utils.d.ts +0 -14
  54. package/lib/chain/chain.utils.js +0 -30
  55. package/lib/chain/index.js +0 -18
  56. package/lib/constants.d.ts +0 -8
  57. package/lib/constants.js +0 -13
  58. package/lib/errors.d.ts +0 -37
  59. package/lib/errors.js +0 -71
  60. package/lib/ethers/index.js +0 -18
  61. package/lib/ethers/safeGetAddress.d.ts +0 -1
  62. package/lib/ethers/safeGetAddress.js +0 -6
  63. package/lib/ethers/safeParseUnits.d.ts +0 -2
  64. package/lib/ethers/safeParseUnits.js +0 -25
  65. package/lib/evm.d.ts +0 -36
  66. package/lib/evm.js +0 -113
  67. package/lib/helpers/format/format.d.ts +0 -98
  68. package/lib/helpers/format/format.js +0 -301
  69. package/lib/helpers/format/index.js +0 -17
  70. package/lib/helpers/getChecksumedAddress.d.ts +0 -7
  71. package/lib/helpers/getChecksumedAddress.js +0 -17
  72. package/lib/helpers/index.js +0 -20
  73. package/lib/helpers/isZeroAddressOrUnset.js +0 -14
  74. package/lib/helpers/locale.d.ts +0 -36
  75. package/lib/helpers/locale.js +0 -86
  76. package/lib/holding/Holding.d.ts +0 -60
  77. package/lib/holding/Holding.js +0 -31
  78. package/lib/holding/index.js +0 -17
  79. package/lib/index.d.ts +0 -33
  80. package/lib/market/Market.d.ts +0 -159
  81. package/lib/market/Market.js +0 -240
  82. package/lib/market/MarketConfig.d.ts +0 -44
  83. package/lib/market/MarketConfig.js +0 -56
  84. package/lib/market/MarketUtils.d.ts +0 -165
  85. package/lib/market/MarketUtils.js +0 -182
  86. package/lib/market/index.js +0 -19
  87. package/lib/maths/AdaptiveCurveIrmLib.d.ts +0 -37
  88. package/lib/maths/AdaptiveCurveIrmLib.js +0 -116
  89. package/lib/maths/MathLib.d.ts +0 -94
  90. package/lib/maths/MathLib.js +0 -153
  91. package/lib/maths/MathUtils.d.ts +0 -15
  92. package/lib/maths/MathUtils.js +0 -33
  93. package/lib/maths/SharesMath.d.ts +0 -12
  94. package/lib/maths/SharesMath.js +0 -22
  95. package/lib/maths/index.js +0 -20
  96. package/lib/notifications.d.ts +0 -98
  97. package/lib/notifications.js +0 -52
  98. package/lib/position/Position.d.ts +0 -118
  99. package/lib/position/Position.js +0 -145
  100. package/lib/position/index.js +0 -17
  101. package/lib/signatures/index.d.ts +0 -12
  102. package/lib/signatures/index.js +0 -39
  103. package/lib/signatures/manager.d.ts +0 -10
  104. package/lib/signatures/manager.js +0 -37
  105. package/lib/signatures/permit.d.ts +0 -21
  106. package/lib/signatures/permit.js +0 -101
  107. package/lib/signatures/permit2.d.ts +0 -20
  108. package/lib/signatures/permit2.js +0 -91
  109. package/lib/signatures/types.d.ts +0 -13
  110. package/lib/signatures/types.js +0 -2
  111. package/lib/signatures/utils.d.ts +0 -6
  112. package/lib/signatures/utils.js +0 -44
  113. package/lib/tests/mocks/markets.d.ts +0 -17
  114. package/lib/tests/mocks/markets.js +0 -108
  115. package/lib/token/ERC20Metadata.d.ts +0 -249
  116. package/lib/token/ERC20Metadata.js +0 -81
  117. package/lib/token/Token.d.ts +0 -45
  118. package/lib/token/Token.js +0 -39
  119. package/lib/token/TokenNamespace.d.ts +0 -18
  120. package/lib/token/TokenNamespace.js +0 -55
  121. package/lib/token/WrappedToken.d.ts +0 -42
  122. package/lib/token/WrappedToken.js +0 -87
  123. package/lib/token/index.js +0 -18
  124. package/lib/types.d.ts +0 -29
  125. package/lib/types.js +0 -23
  126. package/lib/user/User.d.ts +0 -20
  127. package/lib/user/User.js +0 -11
  128. package/lib/user/index.js +0 -18
  129. package/lib/user/user.types.d.ts +0 -18
  130. package/lib/user/user.types.js +0 -2
  131. package/lib/vault/Vault.d.ts +0 -167
  132. package/lib/vault/Vault.js +0 -156
  133. package/lib/vault/VaultAllocation.d.ts +0 -38
  134. package/lib/vault/VaultAllocation.js +0 -18
  135. package/lib/vault/VaultConfig.d.ts +0 -23
  136. package/lib/vault/VaultConfig.js +0 -26
  137. package/lib/vault/VaultUtils.d.ts +0 -17
  138. package/lib/vault/VaultUtils.js +0 -17
  139. package/lib/vault/index.js +0 -20
  140. /package/{lib/chain/index.d.ts → src/chain/index.ts} +0 -0
  141. /package/{lib/ethers/index.d.ts → src/ethers/index.ts} +0 -0
  142. /package/{lib/helpers/format/index.d.ts → src/helpers/format/index.ts} +0 -0
  143. /package/{lib/helpers/index.d.ts → src/helpers/index.ts} +0 -0
  144. /package/{lib/holding/index.d.ts → src/holding/index.ts} +0 -0
  145. /package/{lib/market/index.d.ts → src/market/index.ts} +0 -0
  146. /package/{lib/maths/index.d.ts → src/maths/index.ts} +0 -0
  147. /package/{lib/position/index.d.ts → src/position/index.ts} +0 -0
  148. /package/{lib/token/index.d.ts → src/token/index.ts} +0 -0
  149. /package/{lib/user/index.d.ts → src/user/index.ts} +0 -0
  150. /package/{lib/vault/index.d.ts → src/vault/index.ts} +0 -0
@@ -0,0 +1,416 @@
1
+ import { parseUnits } from "ethers";
2
+
3
+ import { getEnUSNumberToLocalParts } from "../locale";
4
+
5
+ enum Format {
6
+ number = "number",
7
+ commas = "commas",
8
+ short = "short",
9
+ hex = "hex",
10
+ percent = "percent",
11
+ }
12
+
13
+ interface BaseFormatOptions {
14
+ format: Format;
15
+ digits?: number;
16
+ removeTrailingZero?: boolean;
17
+ min?: number;
18
+ max?: number;
19
+ sign?: boolean;
20
+ unit?: string;
21
+ readable?: boolean;
22
+ locale?: string;
23
+ }
24
+
25
+ interface FormatShortOptions extends BaseFormatOptions {
26
+ format: Format.short;
27
+ smallValuesWithCommas?: boolean;
28
+ }
29
+ interface FormatHexOptions {
30
+ format: Format.hex;
31
+ }
32
+ interface FormatCommasOptions extends BaseFormatOptions {
33
+ format: Format.commas;
34
+ }
35
+ interface FormatNumberOptions extends BaseFormatOptions {
36
+ format: Format.number;
37
+ }
38
+
39
+ interface FormatPercentOptions extends BaseFormatOptions {
40
+ format: Format.percent;
41
+ }
42
+
43
+ type FormatOptions =
44
+ | FormatHexOptions
45
+ | FormatShortOptions
46
+ | FormatNumberOptions
47
+ | FormatCommasOptions
48
+ | FormatPercentOptions;
49
+
50
+ declare global {
51
+ interface String {
52
+ insert(index: number, substr: string, fillWith?: string): string;
53
+ }
54
+ }
55
+
56
+ String.prototype.insert = function (index, substr, fillWith) {
57
+ if (index < 0) index = this.length + index;
58
+
59
+ let filler = "";
60
+ if (index < 0) {
61
+ if (fillWith) filler = fillWith.repeat(-index).slice(index);
62
+ index = 0;
63
+ }
64
+ return this.slice(0, index) + substr + filler + this.slice(index);
65
+ };
66
+
67
+ const RANGES = [
68
+ {
69
+ minDecimals: 24,
70
+ symbol: "Y",
71
+ },
72
+ {
73
+ minDecimals: 21,
74
+ symbol: "Z",
75
+ },
76
+ {
77
+ minDecimals: 18,
78
+ symbol: "E",
79
+ },
80
+ {
81
+ minDecimals: 15,
82
+ symbol: "P",
83
+ },
84
+ {
85
+ minDecimals: 12,
86
+ symbol: "T",
87
+ },
88
+ {
89
+ minDecimals: 9,
90
+ symbol: "B",
91
+ },
92
+ {
93
+ minDecimals: 6,
94
+ symbol: "M",
95
+ },
96
+ {
97
+ minDecimals: 4,
98
+ power: 3,
99
+ symbol: "k",
100
+ },
101
+ ];
102
+ const _formatShort = (
103
+ bi: bigint,
104
+ decimals: number,
105
+ formatOptions: Omit<FormatShortOptions, "format">
106
+ ) => {
107
+ const stringValue = bi.toString();
108
+ const params = RANGES.find(
109
+ (range) => stringValue.length > range.minDecimals + decimals
110
+ );
111
+ if (params) {
112
+ return (
113
+ _applyOptions(
114
+ stringValue.insert(
115
+ -((params.power ?? params.minDecimals) + decimals),
116
+ ".",
117
+ "0"
118
+ ),
119
+ formatOptions
120
+ ) + params.symbol
121
+ );
122
+ }
123
+ if (formatOptions.smallValuesWithCommas) {
124
+ return _formatCommas(bi, decimals, formatOptions);
125
+ }
126
+ return _applyOptions(stringValue.insert(-decimals, ".", "0"), formatOptions);
127
+ };
128
+
129
+ const _formatCommas = (
130
+ bi: bigint,
131
+ decimals: number,
132
+ formatOptions: Omit<FormatCommasOptions, "format">
133
+ ) => {
134
+ const stringValue = decimals
135
+ ? bi.toString().insert(-decimals, ".", "0")
136
+ : bi.toString();
137
+
138
+ const [wholePart, decimalPart] = stringValue.split(".");
139
+
140
+ return _applyOptions(
141
+ wholePart!
142
+ .split("")
143
+ .reduce(
144
+ (formattedNumber, digit, i, arr) =>
145
+ `${formattedNumber}${!i || (arr.length - i) % 3 ? "" : ","}${digit}`,
146
+ ""
147
+ ) + (decimalPart ? "." + decimalPart : ""),
148
+ formatOptions
149
+ );
150
+ };
151
+
152
+ const _formatNumber = (
153
+ bi: bigint,
154
+ decimals: number,
155
+ formatOptions: Omit<FormatNumberOptions, "format">
156
+ ) => {
157
+ if (decimals === 0) return _applyOptions(bi.toString(), formatOptions);
158
+ return _applyOptions(
159
+ bi.toString().insert(-decimals, ".", "0"),
160
+ formatOptions
161
+ );
162
+ };
163
+
164
+ const _withUnit = (value: string, unit: string) => {
165
+ switch (unit) {
166
+ case "$":
167
+ return `$${value}`;
168
+ case "":
169
+ case "%":
170
+ return `${value}${unit}`;
171
+ default:
172
+ return `${value} ${unit}`;
173
+ }
174
+ };
175
+
176
+ const _applyOptions = (
177
+ value: string,
178
+ formatOptions: Omit<BaseFormatOptions, "format">
179
+ ) => {
180
+ let [wholePart, decimalPart = ""] = value.split(".");
181
+ const isZero = value.match(/[1-9]/)?.index === undefined;
182
+
183
+ if (formatOptions.digits !== undefined) {
184
+ decimalPart = decimalPart + "0".repeat(formatOptions.digits);
185
+ decimalPart = decimalPart.slice(0, formatOptions.digits);
186
+ }
187
+
188
+ if (formatOptions.removeTrailingZero) {
189
+ decimalPart = decimalPart.replace(/\.?0+$/, "");
190
+ }
191
+
192
+ value = (wholePart || "0") + (decimalPart ? "." + decimalPart : "");
193
+
194
+ const { value: _value, decimalSymbol } = getEnUSNumberToLocalParts(
195
+ value,
196
+ formatOptions.locale
197
+ );
198
+ value = _value;
199
+
200
+ const firstNonZero = value.match(/[1-9]/);
201
+ if (
202
+ firstNonZero?.index === undefined &&
203
+ formatOptions.digits &&
204
+ !isZero &&
205
+ formatOptions.readable
206
+ )
207
+ return `< 0${decimalSymbol}${"0".repeat(formatOptions.digits - 1)}1`;
208
+
209
+ return value;
210
+ };
211
+
212
+ function formatBI(
213
+ bi: bigint,
214
+ decimals: number,
215
+ formatOptions: FormatOptions = { format: Format.hex }
216
+ ): string {
217
+ if (formatOptions.format === Format.hex) return bi.toString(16);
218
+
219
+ const maxBI =
220
+ formatOptions.max !== undefined &&
221
+ parseUnits(formatOptions.max.toString(), decimals);
222
+ if (maxBI && bi > maxBI) {
223
+ return `> ${formatBI(maxBI, decimals, formatOptions)}`;
224
+ }
225
+ const minBI =
226
+ formatOptions.min !== undefined &&
227
+ parseUnits(formatOptions.min.toString(), decimals);
228
+ if (minBI !== false && bi < minBI && bi !== 0n) {
229
+ return `< ${formatBI(minBI, decimals, formatOptions)}`;
230
+ }
231
+
232
+ let value: string;
233
+ const isNegative = bi < 0n;
234
+ const absBI = bi > 0n ? bi : -bi;
235
+
236
+ switch (formatOptions.format) {
237
+ case Format.commas:
238
+ value = _formatCommas(absBI, decimals, formatOptions);
239
+ break;
240
+ case Format.number:
241
+ value = _formatNumber(absBI, decimals, formatOptions);
242
+ break;
243
+ case Format.short:
244
+ value = _formatShort(absBI, decimals, formatOptions);
245
+ break;
246
+ case Format.percent:
247
+ value = _formatNumber(absBI * 100n, decimals, formatOptions);
248
+ break;
249
+ }
250
+
251
+ const formattedValue =
252
+ (isNegative && !/^0\.0+$/.test(value)
253
+ ? "-"
254
+ : formatOptions.sign
255
+ ? "+"
256
+ : "") + value;
257
+
258
+ if (formatOptions.unit) {
259
+ return _withUnit(formattedValue, formatOptions.unit);
260
+ }
261
+
262
+ return formattedValue;
263
+ }
264
+
265
+ /**
266
+ * returns a string representation of a number, always in a decimal format (avoid the 1.34e-15 format for small numbers)
267
+ * @param number
268
+ */
269
+ const safeNumberToString = (number: number) => {
270
+ const str = number.toString();
271
+
272
+ const [a, n] = str.split(/[eE]/);
273
+ if (a == null || n == null) return str;
274
+
275
+ if (n[0] === "+") {
276
+ const [whole, decimal = ""] = a.split(".");
277
+ return whole + decimal + "0".repeat(+n - decimal.length);
278
+ }
279
+
280
+ if (n[0] === "-") {
281
+ const isNegative = a[0] === "-";
282
+ return (
283
+ (isNegative ? "-" : "") +
284
+ "0." +
285
+ "0".repeat(-+n - 1) +
286
+ (isNegative ? a.slice(1) : a).split(".").join("")
287
+ );
288
+ }
289
+
290
+ throw new Error(`Unhandled case: ${str}`);
291
+ };
292
+
293
+ export abstract class BaseFormatter {
294
+ protected abstract _options: FormatOptions;
295
+
296
+ constructor() {}
297
+
298
+ of(value: bigint, decimals: number): string;
299
+ of(value: number): string;
300
+ of(value: bigint | number, decimals?: number) {
301
+ let _decimals: number;
302
+
303
+ if (typeof value === "number") {
304
+ const strNumber = safeNumberToString(value);
305
+ let [, d = ""] = strNumber.split(".");
306
+ _decimals = d.length;
307
+ value = parseUnits(strNumber, _decimals);
308
+ } else {
309
+ _decimals = decimals!;
310
+ }
311
+
312
+ return formatBI(value, _decimals, this._options);
313
+ }
314
+ }
315
+
316
+ export class HexFormatter extends BaseFormatter {
317
+ protected _options = { format: Format.hex };
318
+ }
319
+
320
+ export abstract class CommonFormatter extends BaseFormatter {
321
+ protected abstract _options: BaseFormatOptions;
322
+
323
+ digits(_d: number) {
324
+ this._options.digits = _d;
325
+ return this;
326
+ }
327
+
328
+ removeTrailingZero() {
329
+ this._options.removeTrailingZero = true;
330
+ return this;
331
+ }
332
+
333
+ readable() {
334
+ this._options.readable = true;
335
+ return this;
336
+ }
337
+
338
+ min(_m: number) {
339
+ this._options.min = _m;
340
+ return this;
341
+ }
342
+
343
+ max(_m: number) {
344
+ this._options.max = _m;
345
+ return this;
346
+ }
347
+
348
+ sign() {
349
+ this._options.sign = true;
350
+ return this;
351
+ }
352
+
353
+ unit(_u: string) {
354
+ this._options.unit = _u;
355
+ return this;
356
+ }
357
+
358
+ locale(_l: string) {
359
+ this._options.locale = _l;
360
+ return this;
361
+ }
362
+ }
363
+
364
+ export class NumberFormatter extends CommonFormatter {
365
+ protected _options: FormatNumberOptions = { format: Format.number };
366
+ }
367
+
368
+ export class CommasFormatter extends CommonFormatter {
369
+ protected _options: FormatCommasOptions = { format: Format.commas };
370
+ }
371
+
372
+ export class ShortFormatter extends CommonFormatter {
373
+ protected _options: FormatShortOptions = { format: Format.short };
374
+
375
+ smallValuesWithCommas() {
376
+ this._options.smallValuesWithCommas = true;
377
+ return this;
378
+ }
379
+ }
380
+
381
+ export class PercentFormatter extends CommonFormatter {
382
+ protected _options: FormatPercentOptions = { format: Format.percent };
383
+ }
384
+
385
+ export const format = {
386
+ /**
387
+ * Return the value as an integer in hex format
388
+ */
389
+ get hex() {
390
+ return new HexFormatter();
391
+ },
392
+ /**
393
+ * Return the value as a stringified number (12345.6789)
394
+ */
395
+ get number() {
396
+ return new NumberFormatter();
397
+ },
398
+ /**
399
+ * Return the value as a commas-separated stringified number (12,345.6789)
400
+ */
401
+ get commas() {
402
+ return new CommasFormatter();
403
+ },
404
+ /**
405
+ * Return the value as a shorted stringified number (12.3456789k)
406
+ */
407
+ get short() {
408
+ return new ShortFormatter();
409
+ },
410
+ /**
411
+ * Return the value as a percent based stringified number (10.00 instead of 0.1)
412
+ */
413
+ get percent() {
414
+ return new PercentFormatter();
415
+ },
416
+ };
@@ -0,0 +1,15 @@
1
+ import { AddressLike, getAddress as _getAddress } from "ethers";
2
+
3
+ /**
4
+ * Transform an AddressLike into a checksumed address
5
+ *
6
+ * @param address Address to transform
7
+ */
8
+ export const getChecksumedAddress = async (address: AddressLike) => {
9
+ const awaited = await address;
10
+ // Ethers getAddress function is throwing an error if the address is already checksumed
11
+
12
+ if (typeof awaited === "string") return _getAddress(awaited.toLowerCase());
13
+
14
+ return _getAddress((await awaited.getAddress()).toLowerCase());
15
+ };
@@ -1,7 +1,13 @@
1
+ import { ZeroAddress } from "ethers";
2
+
1
3
  /**
2
4
  * Check if an address is the zero address, null, or undefined.
3
5
  *
4
6
  * @param address - The address to check, which can be a valid address, null, or undefined.
5
7
  * @returns True if the address is zero, null, or undefined; otherwise, false.
6
8
  */
7
- export declare function isZeroAddressOrUnset(address: string | null | undefined): boolean;
9
+ export function isZeroAddressOrUnset(
10
+ address: string | null | undefined
11
+ ): boolean {
12
+ return address === undefined || address === null || address === ZeroAddress;
13
+ }
@@ -0,0 +1,108 @@
1
+ type LocaleSymbols = {
2
+ decimalSymbol: string;
3
+ groupSymbol: string;
4
+ locale: string;
5
+ };
6
+
7
+ export type LocaleParts = LocaleSymbols & {
8
+ value: string;
9
+ };
10
+
11
+ const _convertEnNumStrToLocale = (
12
+ numStr: string,
13
+ localSymbols: LocaleSymbols
14
+ ) => {
15
+ return numStr
16
+ .replaceAll(",", "#TEMP#")
17
+ .replaceAll(".", localSymbols.decimalSymbol)
18
+ .replaceAll("#TEMP#", localSymbols.groupSymbol);
19
+ };
20
+
21
+ /**
22
+ * @returns the locale symbols for the given locale defaulting to en-US
23
+ */
24
+ export const getLocaleSymbols = (locale: string): LocaleSymbols => {
25
+ let formatter: Intl.NumberFormat;
26
+ const formatterOptions = {
27
+ useGrouping: true,
28
+ maximumFractionDigits: 1,
29
+ minimumFractionDigits: 1,
30
+ };
31
+
32
+ try {
33
+ formatter = new Intl.NumberFormat(locale, formatterOptions);
34
+ } catch {
35
+ formatter = new Intl.NumberFormat("en-US", formatterOptions);
36
+ }
37
+
38
+ const parts = formatter.formatToParts(12345.6);
39
+
40
+ const decimalSymbol = parts.find((part) => part.type === "decimal")!.value;
41
+ const groupSymbol = parts.find((part) => part.type === "group")!.value;
42
+
43
+ return { decimalSymbol, groupSymbol, locale };
44
+ };
45
+
46
+ /**
47
+ * @returns the effective browser locale
48
+ */
49
+ export const getEffectiveLocale = () => {
50
+ if (typeof window !== "undefined") {
51
+ try {
52
+ const locale =
53
+ navigator?.language || document?.documentElement?.lang || "en-US";
54
+ new Intl.NumberFormat(locale);
55
+ return locale;
56
+ } catch (e) {
57
+ return "en-US";
58
+ }
59
+ }
60
+ return "en-US";
61
+ };
62
+
63
+ /**
64
+ * @returns the value as a string with the given locale symbols
65
+ * @param numStr the number as a string in the "from" locale (e.g. "1,2345.6" for en-US)
66
+ * @param from the locale the numStr is in (e.g. "en-US")
67
+ * @param to the locale to convert to (e.g. "fr-FR")
68
+ */
69
+ export const convertNumStrToLocal = (
70
+ numStr: string,
71
+ from: string,
72
+ to: string
73
+ ) => {
74
+ const fromSymbols = getLocaleSymbols(from);
75
+ const toSymbols = getLocaleSymbols(to);
76
+
77
+ return numStr
78
+ .replaceAll(fromSymbols.groupSymbol, "#GROUP#")
79
+ .replaceAll(fromSymbols.decimalSymbol, "#DECIMAL#")
80
+ .replaceAll("#GROUP#", toSymbols.groupSymbol)
81
+ .replaceAll("#DECIMAL#", toSymbols.decimalSymbol);
82
+ };
83
+
84
+ /**
85
+ * @returns the value as a string in the effective browser locale
86
+ * @param numStr the number as a string in the effective browser locale (e.g. "1,2345.6" for en-US)
87
+ * @param to the locale to use (e.g. "fr-FR")
88
+ */
89
+ export const convertNumStrFromEffectiveTo = (numStr: string, to: string) => {
90
+ const from = getEffectiveLocale();
91
+ return convertNumStrToLocal(numStr, from, to);
92
+ };
93
+
94
+ /**
95
+ * @returns the value as a string with the given locale symbols either from the given locale or the effective browser locale
96
+ * @param numStr the number as a string in english format (e.g. "1,2345.6")
97
+ * @param locale optional - the locale to use (e.g. "fr-FR")
98
+ */
99
+ export const getEnUSNumberToLocalParts = (
100
+ numStr: string,
101
+ locale?: string
102
+ ): LocaleParts => {
103
+ const _locale = locale || getEffectiveLocale();
104
+ const localSymbols = getLocaleSymbols(_locale);
105
+ const value = _convertEnNumStrToLocale(numStr, localSymbols);
106
+
107
+ return { ...localSymbols, value };
108
+ };
@@ -0,0 +1,109 @@
1
+ import { BigNumberish, toBigInt } from "ethers";
2
+
3
+ import { entries, fromEntries } from "@morpho-org/morpho-ts";
4
+
5
+ import { AddressLabel, NATIVE_ADDRESS } from "../addresses";
6
+ import { Address } from "../types";
7
+
8
+ export const ERC20_ALLOWANCE_RECIPIENTS = [
9
+ "morpho",
10
+ "permit2",
11
+ "bundler",
12
+ ] as const satisfies readonly AddressLabel[];
13
+
14
+ export const PERMIT2_ALLOWANCE_RECIPIENTS = [
15
+ "morpho",
16
+ "bundler",
17
+ ] as const satisfies readonly Exclude<AddressLabel, "permit2">[];
18
+
19
+ export type Erc20AllowanceRecipient =
20
+ (typeof ERC20_ALLOWANCE_RECIPIENTS)[number];
21
+
22
+ export type Permit2AllowanceRecipient =
23
+ (typeof PERMIT2_ALLOWANCE_RECIPIENTS)[number];
24
+
25
+ export interface Permit2Allowance {
26
+ amount: bigint;
27
+ expiration: bigint;
28
+ nonce: bigint;
29
+ }
30
+
31
+ export interface InputHolding {
32
+ user: Address;
33
+ token: Address;
34
+ erc20Allowances: {
35
+ [key in Erc20AllowanceRecipient]: BigNumberish;
36
+ };
37
+ permit2Allowances: {
38
+ [key in Permit2AllowanceRecipient]: Permit2Allowance;
39
+ };
40
+ erc2612Nonce?: BigNumberish;
41
+ canTransfer?: boolean;
42
+ balance: BigNumberish;
43
+ }
44
+
45
+ export class Holding implements InputHolding {
46
+ /**
47
+ * The user of this holding.
48
+ */
49
+ public readonly user: Address;
50
+
51
+ /**
52
+ * The token in which this holding is denominated.
53
+ */
54
+ public readonly token: Address;
55
+
56
+ /**
57
+ * The balance of the user for this token.
58
+ */
59
+ public balance: bigint;
60
+
61
+ /**
62
+ * Whether the user is allowed to transfer this holding's balance.
63
+ */
64
+ public canTransfer?: boolean;
65
+
66
+ /**
67
+ * ERC20 allowance for this token from the user to the allowance recipient.
68
+ */
69
+ public readonly erc20Allowances: {
70
+ [key in Erc20AllowanceRecipient]: bigint;
71
+ };
72
+
73
+ /**
74
+ * Permit2 allowance for this token from the user to the allowance recipient.
75
+ */
76
+ public readonly permit2Allowances: {
77
+ [key in Permit2AllowanceRecipient]: Permit2Allowance;
78
+ };
79
+
80
+ /**
81
+ * ERC-2612 Permit nonce of the user for this token.
82
+ * `undefined` if the token does not support ERC-2612.
83
+ */
84
+ public erc2612Nonce?: bigint;
85
+
86
+ constructor({
87
+ user,
88
+ token,
89
+ erc20Allowances,
90
+ permit2Allowances,
91
+ balance,
92
+ erc2612Nonce,
93
+ canTransfer = true,
94
+ }: InputHolding) {
95
+ this.user = user;
96
+ this.token = token;
97
+ this.balance = toBigInt(balance);
98
+ this.canTransfer = token === NATIVE_ADDRESS || canTransfer;
99
+ this.erc20Allowances = fromEntries(
100
+ entries(erc20Allowances).map(([address, allowance]) => [
101
+ address,
102
+ toBigInt(allowance),
103
+ ])
104
+ );
105
+ this.permit2Allowances = permit2Allowances;
106
+
107
+ if (erc2612Nonce != null) this.erc2612Nonce = toBigInt(erc2612Nonce);
108
+ }
109
+ }