-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtoken.ts
More file actions
341 lines (308 loc) · 8.06 KB
/
token.ts
File metadata and controls
341 lines (308 loc) · 8.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import { E8S_PER_TOKEN } from "../constants/constants";
import { FromStringToTokenError } from "../enums/token.enums";
const DECIMALS_CONVERSION_SUPPORTED = 8;
/**
* Receives a string representing a number and returns the big int or error.
*
* @param amount - in string format
* @returns bigint | FromStringToTokenError
*/
export const convertStringToE8s = (
value: string,
): bigint | FromStringToTokenError => {
// replace exponential format (1e-4) with plain (0.0001)
// doesn't support decimals for values >= ~1e16
let amount = value.includes("e")
? Number(value).toLocaleString("en", {
useGrouping: false,
maximumFractionDigits: 20,
})
: value;
// Remove all instances of "," and "'".
amount = amount.trim().replace(/[,']/g, "");
// Verify that the string is of the format 1234.5678
const regexMatch = amount.match(/\d*(\.\d*)?/);
if (!regexMatch || regexMatch[0] !== amount) {
return FromStringToTokenError.InvalidFormat;
}
const [integral, fractional] = amount.split(".");
let e8s = BigInt(0);
if (integral) {
try {
e8s += BigInt(integral) * E8S_PER_TOKEN;
} catch {
return FromStringToTokenError.InvalidFormat;
}
}
if (fractional) {
if (fractional.length > 8) {
return FromStringToTokenError.FractionalMoreThan8Decimals;
}
try {
e8s += BigInt(fractional.padEnd(8, "0"));
} catch {
return FromStringToTokenError.InvalidFormat;
}
}
return e8s;
};
/**
* Receives a string representing a number and returns the big int or error.
*
* @param amount - in string format
* @returns bigint | FromStringToTokenError
*/
const convertStringToUlps = ({
amount,
decimals,
}: {
amount: string;
decimals: number;
}): bigint | FromStringToTokenError => {
// Remove all instances of "," and "'".
amount = amount.trim().replace(/[,']/g, "");
// Verify that the string is of the format 1234.5678
const regexMatch = amount.match(/\d*(\.\d*)?/);
if (!regexMatch || regexMatch[0] !== amount) {
return FromStringToTokenError.InvalidFormat;
}
const [integral, fractional] = amount.split(".");
let ulps = 0n;
const ulpsPerToken = 10n ** BigInt(decimals);
if (integral) {
try {
ulps += BigInt(integral) * ulpsPerToken;
} catch {
return FromStringToTokenError.InvalidFormat;
}
}
if (fractional) {
if (fractional.length > decimals) {
return FromStringToTokenError.FractionalTooManyDecimals;
}
try {
ulps += BigInt(fractional.padEnd(decimals, "0"));
} catch {
return FromStringToTokenError.InvalidFormat;
}
}
return ulps;
};
export interface Token {
symbol: string;
name: string;
decimals: number;
logo?: string;
}
// TODO: Remove this token and use the value from ICP ledger
export const ICPToken: Token = {
symbol: "ICP",
name: "Internet Computer",
decimals: 8,
};
/**
* Deprecated. Use TokenAmountV2 instead which supports decimals !== 8.
*
* Represents an amount of tokens.
*
* @param e8s - The amount of tokens in bigint.
* @param token - The token type.
*/
export class TokenAmount {
private constructor(
protected e8s: bigint,
public token: Token,
) {
if (token.decimals !== 8) {
throw new Error("Use TokenAmountV2 for number of decimals other than 8");
}
}
/**
* Initialize from a bigint. Bigint are considered e8s.
*
* @param {amount: bigint; token?: Token;} params
* @param {bigint} params.amount The amount in bigint format.
* @param {Token} params.token The token type.
*/
public static fromE8s({
amount,
token,
}: {
amount: bigint;
token: Token;
}): TokenAmount {
return new TokenAmount(amount, token);
}
/**
* Initialize from a string. Accepted formats:
*
* 1234567.8901
* 1'234'567.8901
* 1,234,567.8901
*
* @param {amount: string; token?: Token;} params
* @param {string} params.amount The amount in string format.
* @param {Token} params.token The token type.
*/
public static fromString({
amount,
token,
}: {
amount: string;
token: Token;
}): TokenAmount | FromStringToTokenError {
// If parsing the number fails because of the number of decimals, we still
// want the error to be about the number of decimals and not about the
// parsing.
if (token.decimals !== 8) {
throw new Error("Use TokenAmountV2 for number of decimals other than 8");
}
const e8s = convertStringToE8s(amount);
if (typeof e8s === "bigint") {
return new TokenAmount(e8s, token);
}
return e8s;
}
/**
* Initialize from a number.
*
* 1 integer is considered E8S_PER_TOKEN
*
* @param {amount: number; token?: Token;} params
* @param {string} params.amount The amount in number format.
* @param {Token} params.token The token type.
*/
public static fromNumber({
amount,
token,
}: {
amount: number;
token: Token;
}): TokenAmount {
const tokenAmount = TokenAmount.fromString({
amount: amount.toString(),
token,
});
if (tokenAmount instanceof TokenAmount) {
return tokenAmount;
}
if (tokenAmount === FromStringToTokenError.FractionalMoreThan8Decimals) {
throw new Error(`Number ${amount} has more than 8 decimals`);
}
// This should never happen
throw new Error(`Invalid number ${amount}`);
}
/**
*
* @returns The amount of e8s.
*/
public toE8s(): bigint {
return this.e8s;
}
}
/**
* Represents an amount of tokens.
*
* @param upls - The amount of tokens in units in the last place. If the token
* supports N decimals, 10^N ulp = 1 token.
* @param token - The token type.
*/
export class TokenAmountV2 {
private constructor(
protected ulps: bigint,
public token: Token,
) {}
/**
* Initialize from a bigint. Bigint are considered ulps.
*
* @param {amount: bigint; token?: Token;} params
* @param {bigint} params.amount The amount in bigint format.
* @param {Token} params.token The token type.
*/
public static fromUlps({
amount,
token,
}: {
amount: bigint;
token: Token;
}): TokenAmountV2 {
return new TokenAmountV2(amount, token);
}
/**
* Initialize from a string. Accepted formats:
*
* 1234567.8901
* 1'234'567.8901
* 1,234,567.8901
*
* @param {amount: string; token?: Token;} params
* @param {string} params.amount The amount in string format.
* @param {Token} params.token The token type.
*/
public static fromString({
amount,
token,
}: {
amount: string;
token: Token;
}): TokenAmountV2 | FromStringToTokenError {
const ulps = convertStringToUlps({ amount, decimals: token.decimals });
if (typeof ulps === "bigint") {
return new TokenAmountV2(ulps, token);
}
return ulps;
}
/**
* Initialize from a number.
*
* 1 integer is considered 10^{token.decimals} ulps
*
* @param {amount: number; token?: Token;} params
* @param {string} params.amount The amount in number format.
* @param {Token} params.token The token type.
*/
public static fromNumber({
amount,
token,
}: {
amount: number;
token: Token;
}): TokenAmountV2 {
const tokenAmount = TokenAmountV2.fromString({
amount: amount.toFixed(
Math.min(DECIMALS_CONVERSION_SUPPORTED, token.decimals),
),
token,
});
if (tokenAmount instanceof TokenAmountV2) {
return tokenAmount;
}
if (tokenAmount === FromStringToTokenError.FractionalTooManyDecimals) {
throw new Error(
`Number ${amount} has more than ${token.decimals} decimals`,
);
}
// This should never happen
throw new Error(`Invalid number ${amount}`);
}
/**
*
* @returns The amount of ulps.
*/
public toUlps(): bigint {
return this.ulps;
}
/**
*
* @returns The amount of ulps in e8s precision
*/
public toE8s(): bigint {
if (this.token.decimals < 8) {
return this.ulps * 10n ** BigInt(8 - this.token.decimals);
}
if (this.token.decimals === 8) {
return this.ulps;
}
return this.ulps / 10n ** BigInt(this.token.decimals - 8);
}
}