@metamask/utils 11.4.2 → 11.6.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.
package/dist/index.mjs CHANGED
@@ -19,4 +19,5 @@ export * from "./superstruct.mjs";
19
19
  export * from "./time.mjs";
20
20
  export * from "./transaction-types.mjs";
21
21
  export * from "./versions.mjs";
22
+ export { toWei, fromWei, numberToString, getValueOfUnit, unitMap } from "./unitsConversion.mjs";
22
23
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,6BAAyB;AACzB,6BAAyB;AACzB,4BAAwB;AACxB,iCAA6B;AAC7B,+BAA2B;AAC3B,+BAA2B;AAC3B,kCAA8B;AAC9B,uCAAmC;AACnC,6BAAyB;AAEzB,OAAO,EACL,SAAS,EACT,eAAe,EACf,gBAAgB,EAChB,wBAAwB,EACxB,WAAW,EACX,iBAAiB,EACjB,YAAY,EACZ,oBAAoB,EACpB,iBAAiB,EACjB,uBAAuB,EACvB,iBAAiB,EACjB,kBAAkB,EAClB,sBAAsB,EACtB,KAAK,EACL,QAAQ,EACT,kBAAc;AACf,2BAAuB;AACvB,8BAA0B;AAC1B,8BAA0B;AAC1B,2BAAuB;AACvB,6BAAyB;AACzB,6BAAyB;AACzB,8BAA0B;AAC1B,kCAA8B;AAC9B,2BAAuB;AACvB,wCAAoC;AACpC,+BAA2B","sourcesContent":["export * from './assert';\nexport * from './base64';\nexport * from './bytes';\nexport * from './caip-types';\nexport * from './checksum';\nexport * from './coercers';\nexport * from './collections';\nexport * from './encryption-types';\nexport * from './errors';\nexport type { Hex } from './hex';\nexport {\n HexStruct,\n StrictHexStruct,\n HexAddressStruct,\n HexChecksumAddressStruct,\n isHexString,\n isStrictHexString,\n isHexAddress,\n isHexChecksumAddress,\n assertIsHexString,\n assertIsStrictHexString,\n isValidHexAddress,\n getChecksumAddress,\n isValidChecksumAddress,\n add0x,\n remove0x,\n} from './hex';\nexport * from './json';\nexport * from './keyring';\nexport * from './logging';\nexport * from './misc';\nexport * from './number';\nexport * from './opaque';\nexport * from './promise';\nexport * from './superstruct';\nexport * from './time';\nexport * from './transaction-types';\nexport * from './versions';\n"]}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,6BAAyB;AACzB,6BAAyB;AACzB,4BAAwB;AACxB,iCAA6B;AAC7B,+BAA2B;AAC3B,+BAA2B;AAC3B,kCAA8B;AAC9B,uCAAmC;AACnC,6BAAyB;AAEzB,OAAO,EACL,SAAS,EACT,eAAe,EACf,gBAAgB,EAChB,wBAAwB,EACxB,WAAW,EACX,iBAAiB,EACjB,YAAY,EACZ,oBAAoB,EACpB,iBAAiB,EACjB,uBAAuB,EACvB,iBAAiB,EACjB,kBAAkB,EAClB,sBAAsB,EACtB,KAAK,EACL,QAAQ,EACT,kBAAc;AACf,2BAAuB;AACvB,8BAA0B;AAC1B,8BAA0B;AAC1B,2BAAuB;AACvB,6BAAyB;AACzB,6BAAyB;AACzB,8BAA0B;AAC1B,kCAA8B;AAC9B,2BAAuB;AACvB,wCAAoC;AACpC,+BAA2B;AAC3B,OAAO,EACL,KAAK,EACL,OAAO,EACP,cAAc,EACd,cAAc,EACd,OAAO,EACR,8BAA0B","sourcesContent":["export * from './assert';\nexport * from './base64';\nexport * from './bytes';\nexport * from './caip-types';\nexport * from './checksum';\nexport * from './coercers';\nexport * from './collections';\nexport * from './encryption-types';\nexport * from './errors';\nexport type { Hex } from './hex';\nexport {\n HexStruct,\n StrictHexStruct,\n HexAddressStruct,\n HexChecksumAddressStruct,\n isHexString,\n isStrictHexString,\n isHexAddress,\n isHexChecksumAddress,\n assertIsHexString,\n assertIsStrictHexString,\n isValidHexAddress,\n getChecksumAddress,\n isValidChecksumAddress,\n add0x,\n remove0x,\n} from './hex';\nexport * from './json';\nexport * from './keyring';\nexport * from './logging';\nexport * from './misc';\nexport * from './number';\nexport * from './opaque';\nexport * from './promise';\nexport * from './superstruct';\nexport * from './time';\nexport * from './transaction-types';\nexport * from './versions';\nexport {\n toWei,\n fromWei,\n numberToString,\n getValueOfUnit,\n unitMap,\n} from './unitsConversion';\n"]}
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ /* eslint-disable operator-assignment */
3
+ /*
4
+ Primary Attribution
5
+ Richard Moore <ricmoo@me.com>
6
+ https://github.com/ethers-io
7
+
8
+ Note, Richard is a god of ether gods. Follow and respect him, and use Ethers.io!
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.toWei = exports.fromWei = exports.numberToString = exports.getValueOfUnit = exports.unitMap = exports.numericToBigInt = void 0;
12
+ const zero = BigInt(0);
13
+ const negative1 = BigInt(-1);
14
+ /**
15
+ * Converts a string, number, or bigint to a bigint.
16
+ *
17
+ * @param arg - The value to convert to bigint.
18
+ * @returns The bigint representation of the input.
19
+ * @throws Error if the input type cannot be converted to bigint.
20
+ */
21
+ function numericToBigInt(arg) {
22
+ if (typeof arg === 'string') {
23
+ return BigInt(arg);
24
+ }
25
+ if (typeof arg === 'number') {
26
+ return BigInt(arg);
27
+ }
28
+ if (typeof arg === 'bigint') {
29
+ return arg;
30
+ }
31
+ throw new Error(`Cannot convert ${typeof arg} to BigInt`);
32
+ }
33
+ exports.numericToBigInt = numericToBigInt;
34
+ // complete ethereum unit map
35
+ exports.unitMap = {
36
+ noether: '0',
37
+ wei: '1',
38
+ kwei: '1000',
39
+ Kwei: '1000',
40
+ babbage: '1000',
41
+ femtoether: '1000',
42
+ mwei: '1000000',
43
+ Mwei: '1000000',
44
+ lovelace: '1000000',
45
+ picoether: '1000000',
46
+ gwei: '1000000000',
47
+ Gwei: '1000000000',
48
+ shannon: '1000000000',
49
+ nanoether: '1000000000',
50
+ nano: '1000000000',
51
+ szabo: '1000000000000',
52
+ microether: '1000000000000',
53
+ micro: '1000000000000',
54
+ finney: '1000000000000000',
55
+ milliether: '1000000000000000',
56
+ milli: '1000000000000000',
57
+ ether: '1000000000000000000',
58
+ kether: '1000000000000000000000',
59
+ grand: '1000000000000000000000',
60
+ mether: '1000000000000000000000000',
61
+ gether: '1000000000000000000000000000',
62
+ tether: '1000000000000000000000000000000',
63
+ };
64
+ // Pre-computed unit values as BigInt for performance
65
+ const unitMapBigInt = Object.fromEntries(Object.entries(exports.unitMap).map(([key, value]) => [key, BigInt(value)]));
66
+ const unitLengths = Object.fromEntries(Object.entries(exports.unitMap).map(([key, value]) => [key, value.length - 1 || 1]));
67
+ const NUMBER_REGEX = /^-?[0-9.]+$/u;
68
+ const FRACTION_REGEX = /^([0-9]*[1-9]|0)(0*)/u;
69
+ const COMMIFY_REGEX = /\B(?=(\d{3})+(?!\d))/gu;
70
+ /**
71
+ * Returns value of unit in Wei.
72
+ *
73
+ * @param unitInput - The unit to convert to, default ether.
74
+ * @returns Value of the unit (in Wei).
75
+ * @throws Error if the unit is not correct.
76
+ */
77
+ function getValueOfUnit(unitInput = 'ether') {
78
+ const unit = unitInput.toLowerCase();
79
+ const unitValue = unitMapBigInt[unit];
80
+ if (unitValue === undefined) {
81
+ throw new Error(`The unit provided ${unitInput} doesn't exist, please use the one of the following units ${JSON.stringify(exports.unitMap, null, 2)}`);
82
+ }
83
+ return unitValue;
84
+ }
85
+ exports.getValueOfUnit = getValueOfUnit;
86
+ /**
87
+ * Converts a number to a string.
88
+ *
89
+ * @param arg - The number to convert to a string.
90
+ * @returns The string representation of the number.
91
+ * @throws Error if the number is invalid.
92
+ */
93
+ function numberToString(arg) {
94
+ if (typeof arg === 'string') {
95
+ if (!NUMBER_REGEX.test(arg)) {
96
+ throw new Error(`while converting number to string, invalid number value '${arg}', should be a number matching (^-?[0-9.]+).`);
97
+ }
98
+ return arg;
99
+ }
100
+ if (typeof arg === 'number') {
101
+ return String(arg);
102
+ }
103
+ if (typeof arg === 'bigint') {
104
+ return arg.toString();
105
+ }
106
+ throw new Error(`while converting number to string, invalid number value '${String(arg)}' type ${typeof arg}.`);
107
+ }
108
+ exports.numberToString = numberToString;
109
+ /**
110
+ * Converts a number from Wei to a string.
111
+ *
112
+ * @param weiInput - The number to convert from Wei.
113
+ * @param unit - The unit to convert to, default ether.
114
+ * @param optionsInput - The options to use for the conversion.
115
+ * @param optionsInput.pad - Whether to pad the fractional part with zeros.
116
+ * @param optionsInput.commify - Whether to add commas to separate thousands.
117
+ * @returns The string representation of the number.
118
+ * @throws Error if the number is invalid.
119
+ */
120
+ function fromWei(weiInput, unit, optionsInput) {
121
+ let wei = numericToBigInt(weiInput);
122
+ const negative = wei < zero;
123
+ const unitLower = unit.toLowerCase();
124
+ const base = unitMapBigInt[unitLower];
125
+ const baseLength = unitLengths[unitLower];
126
+ const options = optionsInput ?? {};
127
+ if (base === undefined) {
128
+ throw new Error(`The unit provided ${unit} doesn't exist, please use the one of the following units ${JSON.stringify(exports.unitMap, null, 2)}`);
129
+ }
130
+ // Handle special case of noether (base = 0)
131
+ if (base === zero) {
132
+ return negative ? '-0' : '0';
133
+ }
134
+ if (negative) {
135
+ wei = wei * negative1;
136
+ }
137
+ let fraction = (wei % base).toString();
138
+ fraction = fraction.padStart(baseLength, '0');
139
+ if (!options.pad) {
140
+ const fractionMatch = fraction.match(FRACTION_REGEX);
141
+ // istanbul ignore next: defensive fallback that's never reachable but necessary to satisfy TS
142
+ fraction = fractionMatch?.[1] ?? '0';
143
+ }
144
+ let whole = (wei / base).toString();
145
+ if (options.commify) {
146
+ whole = whole.replace(COMMIFY_REGEX, ',');
147
+ }
148
+ let value = `${whole}${fraction === '0' ? '' : `.${fraction}`}`;
149
+ if (negative) {
150
+ value = `-${value}`;
151
+ }
152
+ return value;
153
+ }
154
+ exports.fromWei = fromWei;
155
+ /**
156
+ * Converts a number to Wei.
157
+ *
158
+ * @param etherInput - The number to convert to Wei.
159
+ * @param unit - The unit to convert to, default ether.
160
+ * @returns The number in Wei.
161
+ * @throws Error if the number is invalid.
162
+ */
163
+ function toWei(etherInput, unit) {
164
+ const unitLower = unit.toLowerCase();
165
+ const base = unitMapBigInt[unitLower];
166
+ const baseLength = unitLengths[unitLower];
167
+ if (base === undefined) {
168
+ throw new Error(`The unit provided ${unit} doesn't exist, please use the one of the following units ${JSON.stringify(exports.unitMap, null, 2)}`);
169
+ }
170
+ // Handle special case of noether (base = 0)
171
+ if (base === zero) {
172
+ return zero;
173
+ }
174
+ // Fast path for bigint inputs when unit is wei (no conversion needed)
175
+ if (typeof etherInput === 'bigint' && unitLower === 'wei') {
176
+ return etherInput;
177
+ }
178
+ // Fast path for bigint inputs with whole units (no fractional part)
179
+ if (typeof etherInput === 'bigint') {
180
+ return etherInput * base;
181
+ }
182
+ let ether = numberToString(etherInput);
183
+ // Is it negative?
184
+ const negative = ether.startsWith('-');
185
+ if (negative) {
186
+ ether = ether.substring(1);
187
+ }
188
+ if (ether === '.') {
189
+ throw new Error(`While converting number ${etherInput} to wei, invalid value`);
190
+ }
191
+ // Split it into a whole and fractional part
192
+ const comps = ether.split('.');
193
+ if (comps.length > 2) {
194
+ throw new Error(`While converting number ${etherInput} to wei, too many decimal points`);
195
+ }
196
+ let whole = comps[0];
197
+ let fraction = comps[1];
198
+ if (!whole) {
199
+ whole = '0';
200
+ }
201
+ if (!fraction) {
202
+ fraction = '0';
203
+ }
204
+ if (fraction.length > baseLength) {
205
+ throw new Error(`While converting number ${etherInput} to wei, too many decimal places`);
206
+ }
207
+ fraction = fraction.padEnd(baseLength, '0');
208
+ const wholeBigInt = BigInt(whole);
209
+ const fractionBigInt = BigInt(fraction);
210
+ let wei = wholeBigInt * base + fractionBigInt;
211
+ if (negative) {
212
+ wei = wei * negative1;
213
+ }
214
+ return wei;
215
+ }
216
+ exports.toWei = toWei;
217
+ //# sourceMappingURL=unitsConversion.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unitsConversion.cjs","sourceRoot":"","sources":["../src/unitsConversion.ts"],"names":[],"mappings":";AAAA,wCAAwC;AACxC;;;;;;EAME;;;AAEF,MAAM,I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AAC;IAE9C,IAAI,QAAQ,EAAE;QACZ,GAAG,GAAG,GAAG,GAAG,SAAS,CAAC;KACvB;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAjFD,sBAiFC","sourcesContent":["/* eslint-disable operator-assignment */\n/*\nPrimary Attribution\nRichard Moore <ricmoo@me.com>\nhttps://github.com/ethers-io\n\nNote, Richard is a god of ether gods. Follow and respect him, and use Ethers.io!\n*/\n\nconst zero = BigInt(0);\nconst negative1 = BigInt(-1);\n\n/**\n * Converts a string, number, or bigint to a bigint.\n *\n * @param arg - The value to convert to bigint.\n * @returns The bigint representation of the input.\n * @throws Error if the input type cannot be converted to bigint.\n */\nexport function numericToBigInt(arg: string | number | bigint): bigint {\n if (typeof arg === 'string') {\n return BigInt(arg);\n }\n if (typeof arg === 'number') {\n return BigInt(arg);\n }\n if (typeof arg === 'bigint') {\n return arg;\n }\n\n throw new Error(`Cannot convert ${typeof arg} to BigInt`);\n}\n\n// complete ethereum unit map\nexport const unitMap = {\n noether: '0',\n wei: '1',\n kwei: '1000',\n Kwei: '1000',\n babbage: '1000',\n femtoether: '1000',\n mwei: '1000000',\n Mwei: '1000000',\n lovelace: '1000000',\n picoether: '1000000',\n gwei: '1000000000',\n Gwei: '1000000000',\n shannon: '1000000000',\n nanoether: '1000000000',\n nano: '1000000000',\n szabo: '1000000000000',\n microether: '1000000000000',\n micro: '1000000000000',\n finney: '1000000000000000',\n milliether: '1000000000000000',\n milli: '1000000000000000',\n ether: '1000000000000000000',\n kether: '1000000000000000000000',\n grand: '1000000000000000000000',\n mether: '1000000000000000000000000',\n gether: '1000000000000000000000000000',\n tether: '1000000000000000000000000000000',\n} as const;\n\n// Pre-computed unit values as BigInt for performance\nconst unitMapBigInt = Object.fromEntries(\n Object.entries(unitMap).map(([key, value]) => [key, BigInt(value)]),\n) as Record<EthereumUnit, bigint>;\n\nconst unitLengths = Object.fromEntries(\n Object.entries(unitMap).map(([key, value]) => [key, value.length - 1 || 1]),\n) as Record<EthereumUnit, number>;\n\nconst NUMBER_REGEX = /^-?[0-9.]+$/u;\nconst FRACTION_REGEX = /^([0-9]*[1-9]|0)(0*)/u;\nconst COMMIFY_REGEX = /\\B(?=(\\d{3})+(?!\\d))/gu;\n\ntype EthereumUnit = keyof typeof unitMap;\n\n/**\n * Returns value of unit in Wei.\n *\n * @param unitInput - The unit to convert to, default ether.\n * @returns Value of the unit (in Wei).\n * @throws Error if the unit is not correct.\n */\nexport function getValueOfUnit(unitInput: EthereumUnit = 'ether'): bigint {\n const unit = unitInput.toLowerCase() as EthereumUnit;\n const unitValue = unitMapBigInt[unit];\n\n if (unitValue === undefined) {\n throw new Error(\n `The unit provided ${unitInput} doesn't exist, please use the one of the following units ${JSON.stringify(\n unitMap,\n null,\n 2,\n )}`,\n );\n }\n\n return unitValue;\n}\n\n/**\n * Converts a number to a string.\n *\n * @param arg - The number to convert to a string.\n * @returns The string representation of the number.\n * @throws Error if the number is invalid.\n */\nexport function numberToString(arg: string | number | bigint) {\n if (typeof arg === 'string') {\n if (!NUMBER_REGEX.test(arg)) {\n throw new Error(\n `while converting number to string, invalid number value '${arg}', should be a number matching (^-?[0-9.]+).`,\n );\n }\n return arg;\n }\n if (typeof arg === 'number') {\n return String(arg);\n }\n if (typeof arg === 'bigint') {\n return arg.toString();\n }\n throw new Error(\n `while converting number to string, invalid number value '${String(\n arg,\n )}' type ${typeof arg}.`,\n );\n}\n\n/**\n * Converts a number from Wei to a string.\n *\n * @param weiInput - The number to convert from Wei.\n * @param unit - The unit to convert to, default ether.\n * @param optionsInput - The options to use for the conversion.\n * @param optionsInput.pad - Whether to pad the fractional part with zeros.\n * @param optionsInput.commify - Whether to add commas to separate thousands.\n * @returns The string representation of the number.\n * @throws Error if the number is invalid.\n */\nexport function fromWei(\n weiInput: string | number | bigint,\n unit: EthereumUnit,\n optionsInput?: { pad?: boolean; commify?: boolean },\n) {\n let wei = numericToBigInt(weiInput);\n const negative = wei < zero;\n const unitLower = unit.toLowerCase() as EthereumUnit;\n const base = unitMapBigInt[unitLower];\n const baseLength = unitLengths[unitLower];\n const options = optionsInput ?? {};\n\n if (base === undefined) {\n throw new Error(\n `The unit provided ${unit} doesn't exist, please use the one of the following units ${JSON.stringify(\n unitMap,\n null,\n 2,\n )}`,\n );\n }\n\n // Handle special case of noether (base = 0)\n if (base === zero) {\n return negative ? '-0' : '0';\n }\n\n if (negative) {\n wei = wei * negative1;\n }\n\n let fraction = (wei % base).toString();\n\n fraction = fraction.padStart(baseLength, '0');\n\n if (!options.pad) {\n const fractionMatch = fraction.match(FRACTION_REGEX);\n // istanbul ignore next: defensive fallback that's never reachable but necessary to satisfy TS\n fraction = fractionMatch?.[1] ?? '0';\n }\n\n let whole = (wei / base).toString();\n\n if (options.commify) {\n whole = whole.replace(COMMIFY_REGEX, ',');\n }\n\n let value = `${whole}${fraction === '0' ? '' : `.${fraction}`}`;\n\n if (negative) {\n value = `-${value}`;\n }\n\n return value;\n}\n\n/**\n * Converts a number to Wei.\n *\n * @param etherInput - The number to convert to Wei.\n * @param unit - The unit to convert to, default ether.\n * @returns The number in Wei.\n * @throws Error if the number is invalid.\n */\nexport function toWei(\n etherInput: string | number | bigint,\n unit: EthereumUnit,\n): bigint {\n const unitLower = unit.toLowerCase() as EthereumUnit;\n const base = unitMapBigInt[unitLower];\n const baseLength = unitLengths[unitLower];\n\n if (base === undefined) {\n throw new Error(\n `The unit provided ${unit} doesn't exist, please use the one of the following units ${JSON.stringify(\n unitMap,\n null,\n 2,\n )}`,\n );\n }\n\n // Handle special case of noether (base = 0)\n if (base === zero) {\n return zero;\n }\n\n // Fast path for bigint inputs when unit is wei (no conversion needed)\n if (typeof etherInput === 'bigint' && unitLower === 'wei') {\n return etherInput;\n }\n\n // Fast path for bigint inputs with whole units (no fractional part)\n if (typeof etherInput === 'bigint') {\n return etherInput * base;\n }\n\n let ether = numberToString(etherInput);\n\n // Is it negative?\n const negative = ether.startsWith('-');\n if (negative) {\n ether = ether.substring(1);\n }\n\n if (ether === '.') {\n throw new Error(\n `While converting number ${etherInput} to wei, invalid value`,\n );\n }\n\n // Split it into a whole and fractional part\n const comps = ether.split('.');\n if (comps.length > 2) {\n throw new Error(\n `While converting number ${etherInput} to wei, too many decimal points`,\n );\n }\n\n let whole = comps[0];\n let fraction = comps[1];\n\n if (!whole) {\n whole = '0';\n }\n if (!fraction) {\n fraction = '0';\n }\n if (fraction.length > baseLength) {\n throw new Error(\n `While converting number ${etherInput} to wei, too many decimal places`,\n );\n }\n\n fraction = fraction.padEnd(baseLength, '0');\n\n const wholeBigInt = BigInt(whole);\n const fractionBigInt = BigInt(fraction);\n let wei = wholeBigInt * base + fractionBigInt;\n\n if (negative) {\n wei = wei * negative1;\n }\n\n return wei;\n}\n"]}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Converts a string, number, or bigint to a bigint.
3
+ *
4
+ * @param arg - The value to convert to bigint.
5
+ * @returns The bigint representation of the input.
6
+ * @throws Error if the input type cannot be converted to bigint.
7
+ */
8
+ export declare function numericToBigInt(arg: string | number | bigint): bigint;
9
+ export declare const unitMap: {
10
+ readonly noether: "0";
11
+ readonly wei: "1";
12
+ readonly kwei: "1000";
13
+ readonly Kwei: "1000";
14
+ readonly babbage: "1000";
15
+ readonly femtoether: "1000";
16
+ readonly mwei: "1000000";
17
+ readonly Mwei: "1000000";
18
+ readonly lovelace: "1000000";
19
+ readonly picoether: "1000000";
20
+ readonly gwei: "1000000000";
21
+ readonly Gwei: "1000000000";
22
+ readonly shannon: "1000000000";
23
+ readonly nanoether: "1000000000";
24
+ readonly nano: "1000000000";
25
+ readonly szabo: "1000000000000";
26
+ readonly microether: "1000000000000";
27
+ readonly micro: "1000000000000";
28
+ readonly finney: "1000000000000000";
29
+ readonly milliether: "1000000000000000";
30
+ readonly milli: "1000000000000000";
31
+ readonly ether: "1000000000000000000";
32
+ readonly kether: "1000000000000000000000";
33
+ readonly grand: "1000000000000000000000";
34
+ readonly mether: "1000000000000000000000000";
35
+ readonly gether: "1000000000000000000000000000";
36
+ readonly tether: "1000000000000000000000000000000";
37
+ };
38
+ type EthereumUnit = keyof typeof unitMap;
39
+ /**
40
+ * Returns value of unit in Wei.
41
+ *
42
+ * @param unitInput - The unit to convert to, default ether.
43
+ * @returns Value of the unit (in Wei).
44
+ * @throws Error if the unit is not correct.
45
+ */
46
+ export declare function getValueOfUnit(unitInput?: EthereumUnit): bigint;
47
+ /**
48
+ * Converts a number to a string.
49
+ *
50
+ * @param arg - The number to convert to a string.
51
+ * @returns The string representation of the number.
52
+ * @throws Error if the number is invalid.
53
+ */
54
+ export declare function numberToString(arg: string | number | bigint): string;
55
+ /**
56
+ * Converts a number from Wei to a string.
57
+ *
58
+ * @param weiInput - The number to convert from Wei.
59
+ * @param unit - The unit to convert to, default ether.
60
+ * @param optionsInput - The options to use for the conversion.
61
+ * @param optionsInput.pad - Whether to pad the fractional part with zeros.
62
+ * @param optionsInput.commify - Whether to add commas to separate thousands.
63
+ * @returns The string representation of the number.
64
+ * @throws Error if the number is invalid.
65
+ */
66
+ export declare function fromWei(weiInput: string | number | bigint, unit: EthereumUnit, optionsInput?: {
67
+ pad?: boolean;
68
+ commify?: boolean;
69
+ }): string;
70
+ /**
71
+ * Converts a number to Wei.
72
+ *
73
+ * @param etherInput - The number to convert to Wei.
74
+ * @param unit - The unit to convert to, default ether.
75
+ * @returns The number in Wei.
76
+ * @throws Error if the number is invalid.
77
+ */
78
+ export declare function toWei(etherInput: string | number | bigint, unit: EthereumUnit): bigint;
79
+ export {};
80
+ //# sourceMappingURL=unitsConversion.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unitsConversion.d.cts","sourceRoot":"","sources":["../src/unitsConversion.ts"],"names":[],"mappings":"AAYA;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAYrE;AAGD,eAAO,MAAM,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BV,CAAC;AAeX,KAAK,YAAY,GAAG,MAAM,OAAO,OAAO,CAAC;AAEzC;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,SAAS,GAAE,YAAsB,GAAG,MAAM,CAexE;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,UAoB3D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,OAAO,CACrB,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EAClC,IAAI,EAAE,YAAY,EAClB,YAAY,CAAC,EAAE;IAAE,GAAG,CAAC,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,UAmDpD;AAED;;;;;;;GAOG;AACH,wBAAgB,KAAK,CACnB,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EACpC,IAAI,EAAE,YAAY,GACjB,MAAM,CA8ER"}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Converts a string, number, or bigint to a bigint.
3
+ *
4
+ * @param arg - The value to convert to bigint.
5
+ * @returns The bigint representation of the input.
6
+ * @throws Error if the input type cannot be converted to bigint.
7
+ */
8
+ export declare function numericToBigInt(arg: string | number | bigint): bigint;
9
+ export declare const unitMap: {
10
+ readonly noether: "0";
11
+ readonly wei: "1";
12
+ readonly kwei: "1000";
13
+ readonly Kwei: "1000";
14
+ readonly babbage: "1000";
15
+ readonly femtoether: "1000";
16
+ readonly mwei: "1000000";
17
+ readonly Mwei: "1000000";
18
+ readonly lovelace: "1000000";
19
+ readonly picoether: "1000000";
20
+ readonly gwei: "1000000000";
21
+ readonly Gwei: "1000000000";
22
+ readonly shannon: "1000000000";
23
+ readonly nanoether: "1000000000";
24
+ readonly nano: "1000000000";
25
+ readonly szabo: "1000000000000";
26
+ readonly microether: "1000000000000";
27
+ readonly micro: "1000000000000";
28
+ readonly finney: "1000000000000000";
29
+ readonly milliether: "1000000000000000";
30
+ readonly milli: "1000000000000000";
31
+ readonly ether: "1000000000000000000";
32
+ readonly kether: "1000000000000000000000";
33
+ readonly grand: "1000000000000000000000";
34
+ readonly mether: "1000000000000000000000000";
35
+ readonly gether: "1000000000000000000000000000";
36
+ readonly tether: "1000000000000000000000000000000";
37
+ };
38
+ type EthereumUnit = keyof typeof unitMap;
39
+ /**
40
+ * Returns value of unit in Wei.
41
+ *
42
+ * @param unitInput - The unit to convert to, default ether.
43
+ * @returns Value of the unit (in Wei).
44
+ * @throws Error if the unit is not correct.
45
+ */
46
+ export declare function getValueOfUnit(unitInput?: EthereumUnit): bigint;
47
+ /**
48
+ * Converts a number to a string.
49
+ *
50
+ * @param arg - The number to convert to a string.
51
+ * @returns The string representation of the number.
52
+ * @throws Error if the number is invalid.
53
+ */
54
+ export declare function numberToString(arg: string | number | bigint): string;
55
+ /**
56
+ * Converts a number from Wei to a string.
57
+ *
58
+ * @param weiInput - The number to convert from Wei.
59
+ * @param unit - The unit to convert to, default ether.
60
+ * @param optionsInput - The options to use for the conversion.
61
+ * @param optionsInput.pad - Whether to pad the fractional part with zeros.
62
+ * @param optionsInput.commify - Whether to add commas to separate thousands.
63
+ * @returns The string representation of the number.
64
+ * @throws Error if the number is invalid.
65
+ */
66
+ export declare function fromWei(weiInput: string | number | bigint, unit: EthereumUnit, optionsInput?: {
67
+ pad?: boolean;
68
+ commify?: boolean;
69
+ }): string;
70
+ /**
71
+ * Converts a number to Wei.
72
+ *
73
+ * @param etherInput - The number to convert to Wei.
74
+ * @param unit - The unit to convert to, default ether.
75
+ * @returns The number in Wei.
76
+ * @throws Error if the number is invalid.
77
+ */
78
+ export declare function toWei(etherInput: string | number | bigint, unit: EthereumUnit): bigint;
79
+ export {};
80
+ //# sourceMappingURL=unitsConversion.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unitsConversion.d.mts","sourceRoot":"","sources":["../src/unitsConversion.ts"],"names":[],"mappings":"AAYA;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAYrE;AAGD,eAAO,MAAM,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BV,CAAC;AAeX,KAAK,YAAY,GAAG,MAAM,OAAO,OAAO,CAAC;AAEzC;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,SAAS,GAAE,YAAsB,GAAG,MAAM,CAexE;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,UAoB3D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,OAAO,CACrB,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EAClC,IAAI,EAAE,YAAY,EAClB,YAAY,CAAC,EAAE;IAAE,GAAG,CAAC,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,UAmDpD;AAED;;;;;;;GAOG;AACH,wBAAgB,KAAK,CACnB,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EACpC,IAAI,EAAE,YAAY,GACjB,MAAM,CA8ER"}
@@ -0,0 +1,209 @@
1
+ /* eslint-disable operator-assignment */
2
+ /*
3
+ Primary Attribution
4
+ Richard Moore <ricmoo@me.com>
5
+ https://github.com/ethers-io
6
+
7
+ Note, Richard is a god of ether gods. Follow and respect him, and use Ethers.io!
8
+ */
9
+ const zero = BigInt(0);
10
+ const negative1 = BigInt(-1);
11
+ /**
12
+ * Converts a string, number, or bigint to a bigint.
13
+ *
14
+ * @param arg - The value to convert to bigint.
15
+ * @returns The bigint representation of the input.
16
+ * @throws Error if the input type cannot be converted to bigint.
17
+ */
18
+ export function numericToBigInt(arg) {
19
+ if (typeof arg === 'string') {
20
+ return BigInt(arg);
21
+ }
22
+ if (typeof arg === 'number') {
23
+ return BigInt(arg);
24
+ }
25
+ if (typeof arg === 'bigint') {
26
+ return arg;
27
+ }
28
+ throw new Error(`Cannot convert ${typeof arg} to BigInt`);
29
+ }
30
+ // complete ethereum unit map
31
+ export const unitMap = {
32
+ noether: '0',
33
+ wei: '1',
34
+ kwei: '1000',
35
+ Kwei: '1000',
36
+ babbage: '1000',
37
+ femtoether: '1000',
38
+ mwei: '1000000',
39
+ Mwei: '1000000',
40
+ lovelace: '1000000',
41
+ picoether: '1000000',
42
+ gwei: '1000000000',
43
+ Gwei: '1000000000',
44
+ shannon: '1000000000',
45
+ nanoether: '1000000000',
46
+ nano: '1000000000',
47
+ szabo: '1000000000000',
48
+ microether: '1000000000000',
49
+ micro: '1000000000000',
50
+ finney: '1000000000000000',
51
+ milliether: '1000000000000000',
52
+ milli: '1000000000000000',
53
+ ether: '1000000000000000000',
54
+ kether: '1000000000000000000000',
55
+ grand: '1000000000000000000000',
56
+ mether: '1000000000000000000000000',
57
+ gether: '1000000000000000000000000000',
58
+ tether: '1000000000000000000000000000000',
59
+ };
60
+ // Pre-computed unit values as BigInt for performance
61
+ const unitMapBigInt = Object.fromEntries(Object.entries(unitMap).map(([key, value]) => [key, BigInt(value)]));
62
+ const unitLengths = Object.fromEntries(Object.entries(unitMap).map(([key, value]) => [key, value.length - 1 || 1]));
63
+ const NUMBER_REGEX = /^-?[0-9.]+$/u;
64
+ const FRACTION_REGEX = /^([0-9]*[1-9]|0)(0*)/u;
65
+ const COMMIFY_REGEX = /\B(?=(\d{3})+(?!\d))/gu;
66
+ /**
67
+ * Returns value of unit in Wei.
68
+ *
69
+ * @param unitInput - The unit to convert to, default ether.
70
+ * @returns Value of the unit (in Wei).
71
+ * @throws Error if the unit is not correct.
72
+ */
73
+ export function getValueOfUnit(unitInput = 'ether') {
74
+ const unit = unitInput.toLowerCase();
75
+ const unitValue = unitMapBigInt[unit];
76
+ if (unitValue === undefined) {
77
+ throw new Error(`The unit provided ${unitInput} doesn't exist, please use the one of the following units ${JSON.stringify(unitMap, null, 2)}`);
78
+ }
79
+ return unitValue;
80
+ }
81
+ /**
82
+ * Converts a number to a string.
83
+ *
84
+ * @param arg - The number to convert to a string.
85
+ * @returns The string representation of the number.
86
+ * @throws Error if the number is invalid.
87
+ */
88
+ export function numberToString(arg) {
89
+ if (typeof arg === 'string') {
90
+ if (!NUMBER_REGEX.test(arg)) {
91
+ throw new Error(`while converting number to string, invalid number value '${arg}', should be a number matching (^-?[0-9.]+).`);
92
+ }
93
+ return arg;
94
+ }
95
+ if (typeof arg === 'number') {
96
+ return String(arg);
97
+ }
98
+ if (typeof arg === 'bigint') {
99
+ return arg.toString();
100
+ }
101
+ throw new Error(`while converting number to string, invalid number value '${String(arg)}' type ${typeof arg}.`);
102
+ }
103
+ /**
104
+ * Converts a number from Wei to a string.
105
+ *
106
+ * @param weiInput - The number to convert from Wei.
107
+ * @param unit - The unit to convert to, default ether.
108
+ * @param optionsInput - The options to use for the conversion.
109
+ * @param optionsInput.pad - Whether to pad the fractional part with zeros.
110
+ * @param optionsInput.commify - Whether to add commas to separate thousands.
111
+ * @returns The string representation of the number.
112
+ * @throws Error if the number is invalid.
113
+ */
114
+ export function fromWei(weiInput, unit, optionsInput) {
115
+ let wei = numericToBigInt(weiInput);
116
+ const negative = wei < zero;
117
+ const unitLower = unit.toLowerCase();
118
+ const base = unitMapBigInt[unitLower];
119
+ const baseLength = unitLengths[unitLower];
120
+ const options = optionsInput ?? {};
121
+ if (base === undefined) {
122
+ throw new Error(`The unit provided ${unit} doesn't exist, please use the one of the following units ${JSON.stringify(unitMap, null, 2)}`);
123
+ }
124
+ // Handle special case of noether (base = 0)
125
+ if (base === zero) {
126
+ return negative ? '-0' : '0';
127
+ }
128
+ if (negative) {
129
+ wei = wei * negative1;
130
+ }
131
+ let fraction = (wei % base).toString();
132
+ fraction = fraction.padStart(baseLength, '0');
133
+ if (!options.pad) {
134
+ const fractionMatch = fraction.match(FRACTION_REGEX);
135
+ // istanbul ignore next: defensive fallback that's never reachable but necessary to satisfy TS
136
+ fraction = fractionMatch?.[1] ?? '0';
137
+ }
138
+ let whole = (wei / base).toString();
139
+ if (options.commify) {
140
+ whole = whole.replace(COMMIFY_REGEX, ',');
141
+ }
142
+ let value = `${whole}${fraction === '0' ? '' : `.${fraction}`}`;
143
+ if (negative) {
144
+ value = `-${value}`;
145
+ }
146
+ return value;
147
+ }
148
+ /**
149
+ * Converts a number to Wei.
150
+ *
151
+ * @param etherInput - The number to convert to Wei.
152
+ * @param unit - The unit to convert to, default ether.
153
+ * @returns The number in Wei.
154
+ * @throws Error if the number is invalid.
155
+ */
156
+ export function toWei(etherInput, unit) {
157
+ const unitLower = unit.toLowerCase();
158
+ const base = unitMapBigInt[unitLower];
159
+ const baseLength = unitLengths[unitLower];
160
+ if (base === undefined) {
161
+ throw new Error(`The unit provided ${unit} doesn't exist, please use the one of the following units ${JSON.stringify(unitMap, null, 2)}`);
162
+ }
163
+ // Handle special case of noether (base = 0)
164
+ if (base === zero) {
165
+ return zero;
166
+ }
167
+ // Fast path for bigint inputs when unit is wei (no conversion needed)
168
+ if (typeof etherInput === 'bigint' && unitLower === 'wei') {
169
+ return etherInput;
170
+ }
171
+ // Fast path for bigint inputs with whole units (no fractional part)
172
+ if (typeof etherInput === 'bigint') {
173
+ return etherInput * base;
174
+ }
175
+ let ether = numberToString(etherInput);
176
+ // Is it negative?
177
+ const negative = ether.startsWith('-');
178
+ if (negative) {
179
+ ether = ether.substring(1);
180
+ }
181
+ if (ether === '.') {
182
+ throw new Error(`While converting number ${etherInput} to wei, invalid value`);
183
+ }
184
+ // Split it into a whole and fractional part
185
+ const comps = ether.split('.');
186
+ if (comps.length > 2) {
187
+ throw new Error(`While converting number ${etherInput} to wei, too many decimal points`);
188
+ }
189
+ let whole = comps[0];
190
+ let fraction = comps[1];
191
+ if (!whole) {
192
+ whole = '0';
193
+ }
194
+ if (!fraction) {
195
+ fraction = '0';
196
+ }
197
+ if (fraction.length > baseLength) {
198
+ throw new Error(`While converting number ${etherInput} to wei, too many decimal places`);
199
+ }
200
+ fraction = fraction.padEnd(baseLength, '0');
201
+ const wholeBigInt = BigInt(whole);
202
+ const fractionBigInt = BigInt(fraction);
203
+ let wei = wholeBigInt * base + fractionBigInt;
204
+ if (negative) {
205
+ wei = wei * negative1;
206
+ }
207
+ return wei;
208
+ }
209
+ //# sourceMappingURL=unitsConversion.mjs.map