@metamask-previews/utils 11.12.1-preview-9962b7e

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 (112) hide show
  1. package/CHANGELOG.md +584 -0
  2. package/LICENSE +15 -0
  3. package/README.md +106 -0
  4. package/dist/assert.d.ts +61 -0
  5. package/dist/assert.d.ts.map +1 -0
  6. package/dist/assert.js +115 -0
  7. package/dist/assert.js.map +1 -0
  8. package/dist/base64.d.ts +25 -0
  9. package/dist/base64.d.ts.map +1 -0
  10. package/dist/base64.js +30 -0
  11. package/dist/base64.js.map +1 -0
  12. package/dist/bytes.d.ts +198 -0
  13. package/dist/bytes.d.ts.map +1 -0
  14. package/dist/bytes.js +406 -0
  15. package/dist/bytes.js.map +1 -0
  16. package/dist/caip-types.d.ts +294 -0
  17. package/dist/caip-types.d.ts.map +1 -0
  18. package/dist/caip-types.js +369 -0
  19. package/dist/caip-types.js.map +1 -0
  20. package/dist/checksum.d.ts +2 -0
  21. package/dist/checksum.d.ts.map +1 -0
  22. package/dist/checksum.js +4 -0
  23. package/dist/checksum.js.map +1 -0
  24. package/dist/coercers.d.ts +97 -0
  25. package/dist/coercers.d.ts.map +1 -0
  26. package/dist/coercers.js +159 -0
  27. package/dist/coercers.js.map +1 -0
  28. package/dist/collections.d.ts +39 -0
  29. package/dist/collections.d.ts.map +1 -0
  30. package/dist/collections.js +105 -0
  31. package/dist/collections.js.map +1 -0
  32. package/dist/encryption-types.d.ts +7 -0
  33. package/dist/encryption-types.d.ts.map +1 -0
  34. package/dist/encryption-types.js +2 -0
  35. package/dist/encryption-types.js.map +1 -0
  36. package/dist/errors.d.ts +68 -0
  37. package/dist/errors.d.ts.map +1 -0
  38. package/dist/errors.js +121 -0
  39. package/dist/errors.js.map +1 -0
  40. package/dist/fs.d.ts +133 -0
  41. package/dist/fs.d.ts.map +1 -0
  42. package/dist/fs.js +210 -0
  43. package/dist/fs.js.map +1 -0
  44. package/dist/hashing.d.ts +28 -0
  45. package/dist/hashing.d.ts.map +1 -0
  46. package/dist/hashing.js +59 -0
  47. package/dist/hashing.js.map +1 -0
  48. package/dist/hex.d.ts +117 -0
  49. package/dist/hex.d.ts.map +1 -0
  50. package/dist/hex.js +174 -0
  51. package/dist/hex.js.map +1 -0
  52. package/dist/index.d.ts +26 -0
  53. package/dist/index.d.ts.map +1 -0
  54. package/dist/index.js +21 -0
  55. package/dist/index.js.map +1 -0
  56. package/dist/json.d.ts +398 -0
  57. package/dist/json.d.ts.map +1 -0
  58. package/dist/json.js +402 -0
  59. package/dist/json.js.map +1 -0
  60. package/dist/keyring.d.ts +243 -0
  61. package/dist/keyring.d.ts.map +1 -0
  62. package/dist/keyring.js +2 -0
  63. package/dist/keyring.js.map +1 -0
  64. package/dist/logging.d.ts +30 -0
  65. package/dist/logging.d.ts.map +1 -0
  66. package/dist/logging.js +35 -0
  67. package/dist/logging.js.map +1 -0
  68. package/dist/misc.d.ts +127 -0
  69. package/dist/misc.d.ts.map +1 -0
  70. package/dist/misc.js +142 -0
  71. package/dist/misc.js.map +1 -0
  72. package/dist/mnemonic.d.ts +14 -0
  73. package/dist/mnemonic.d.ts.map +1 -0
  74. package/dist/mnemonic.js +25 -0
  75. package/dist/mnemonic.js.map +1 -0
  76. package/dist/node.d.ts +3 -0
  77. package/dist/node.d.ts.map +1 -0
  78. package/dist/node.js +3 -0
  79. package/dist/node.js.map +1 -0
  80. package/dist/number.d.ts +74 -0
  81. package/dist/number.d.ts.map +1 -0
  82. package/dist/number.js +95 -0
  83. package/dist/number.js.map +1 -0
  84. package/dist/opaque.d.ts +6 -0
  85. package/dist/opaque.d.ts.map +1 -0
  86. package/dist/opaque.js +2 -0
  87. package/dist/opaque.js.map +1 -0
  88. package/dist/promise.d.ts +45 -0
  89. package/dist/promise.d.ts.map +1 -0
  90. package/dist/promise.js +40 -0
  91. package/dist/promise.js.map +1 -0
  92. package/dist/superstruct.d.ts +20 -0
  93. package/dist/superstruct.d.ts.map +1 -0
  94. package/dist/superstruct.js +24 -0
  95. package/dist/superstruct.js.map +1 -0
  96. package/dist/time.d.ts +49 -0
  97. package/dist/time.d.ts.map +1 -0
  98. package/dist/time.js +62 -0
  99. package/dist/time.js.map +1 -0
  100. package/dist/transaction-types.d.ts +117 -0
  101. package/dist/transaction-types.d.ts.map +1 -0
  102. package/dist/transaction-types.js +2 -0
  103. package/dist/transaction-types.js.map +1 -0
  104. package/dist/unitsConversion.d.ts +80 -0
  105. package/dist/unitsConversion.d.ts.map +1 -0
  106. package/dist/unitsConversion.js +209 -0
  107. package/dist/unitsConversion.js.map +1 -0
  108. package/dist/versions.d.ts +101 -0
  109. package/dist/versions.d.ts.map +1 -0
  110. package/dist/versions.js +85 -0
  111. package/dist/versions.js.map +1 -0
  112. package/package.json +122 -0
@@ -0,0 +1,117 @@
1
+ import type { Bytes } from './bytes.js';
2
+ import type { Hex } from './hex.js';
3
+ export type Transaction = LegacyTransaction | EIP2930Transaction | EIP1559Transaction;
4
+ export type SignedTransaction = Transaction & Signature;
5
+ export type Signature = {
6
+ /**
7
+ * EC signature parameter
8
+ * 32 bytes long sequence.
9
+ */
10
+ r: Bytes;
11
+ /**
12
+ * EC signature parameter
13
+ * Signature proof.
14
+ * 32 bytes long sequence
15
+ */
16
+ s: Bytes;
17
+ /**
18
+ * Recovery identifier. It can be either 0x1b or 0x1c
19
+ * 1 byte long sequence
20
+ */
21
+ yParity: Bytes;
22
+ };
23
+ /**
24
+ * Base Ethereum Transaction
25
+ */
26
+ export type BaseTransaction = {
27
+ /**
28
+ * Sequentially incrementing counter which indicates the transaction
29
+ * number from the account
30
+ */
31
+ nonce: Bytes;
32
+ /**
33
+ * The address of the sender, that will be signing the transaction
34
+ */
35
+ from: Hex | Uint8Array;
36
+ /**
37
+ * The receiving address.
38
+ * If an externally-owned account, the transaction will transfer value.
39
+ * If a contract account, the transaction will execute the contract code.
40
+ */
41
+ to: Hex | Uint8Array;
42
+ /**
43
+ * The amount of Ether sent.
44
+ */
45
+ value: Bytes;
46
+ /**
47
+ * Maximum amount of gas units that this transaction can consume.
48
+ */
49
+ gasLimit: Bytes;
50
+ /**
51
+ * Arbitrary data.
52
+ */
53
+ data?: Bytes;
54
+ };
55
+ /**
56
+ * Typed Ethereum Transaction
57
+ */
58
+ export type TypedTransaction = BaseTransaction & {
59
+ /**
60
+ * Transaction type.
61
+ */
62
+ type: number;
63
+ };
64
+ /**
65
+ * Ethereum Legacy Transaction
66
+ * Reference: https://ethereum.org/en/developers/docs/transactions/
67
+ */
68
+ export type LegacyTransaction = BaseTransaction & {
69
+ /**
70
+ * Transaction's gas price.
71
+ */
72
+ gasPrice: Bytes | null;
73
+ };
74
+ /**
75
+ * EIP-2930 Transaction: Optional Access Lists
76
+ * Reference: https://eips.ethereum.org/EIPS/eip-2930
77
+ */
78
+ export type EIP2930Transaction = TypedTransaction & {
79
+ /**
80
+ * Transaction type.
81
+ */
82
+ type: 1;
83
+ /**
84
+ * Transaction chain ID
85
+ */
86
+ chainId: Bytes;
87
+ /**
88
+ * List of addresses and storage keys that the transaction plans to access
89
+ */
90
+ accessList: {
91
+ address: Hex;
92
+ storageKeys: Hex[];
93
+ }[] | {
94
+ address: Uint8Array;
95
+ storageKeys: Uint8Array[];
96
+ }[];
97
+ };
98
+ /**
99
+ * EIP-1559 Transaction: Fee market change for ETH 1.0 chain (Type-2)
100
+ *
101
+ * Reference: https://eips.ethereum.org/EIPS/eip-1559
102
+ */
103
+ export type EIP1559Transaction = TypedTransaction & {
104
+ /**
105
+ * Transaction type.
106
+ */
107
+ type: 2;
108
+ /**
109
+ * Maximum fee to give to the miner
110
+ */
111
+ maxPriorityFeePerGas: Bytes;
112
+ /**
113
+ * Maximum total fee
114
+ */
115
+ maxFeePerGas: Bytes;
116
+ };
117
+ //# sourceMappingURL=transaction-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transaction-types.d.ts","sourceRoot":"","sources":["../src/transaction-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK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AAE,OAAO,EAAE,UAAU,CAAC;QAAC,WAAW,EAAE,UAAU,EAAE,CAAA;KAAE,EAAE,CAAC;CAC1D,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG,gBAAgB,GAAG;IAClD;;OAEG;IACH,IAAI,EAAE,CAAC,CAAC;IAER;;OAEG;IACH,oBAAoB,EAAE,KAAK,CAAC;IAE5B;;OAEG;IACH,YAAY,EAAE,KAAK,CAAC;CACrB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=transaction-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transaction-types.js","sourceRoot":"","sources":["../src/transaction-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Bytes } from './bytes.js';\nimport type { Hex } from './hex.js';\n\nexport type Transaction =\n | LegacyTransaction\n | EIP2930Transaction\n | EIP1559Transaction;\n\nexport type SignedTransaction = Transaction & Signature;\n\nexport type Signature = {\n /**\n * EC signature parameter\n * 32 bytes long sequence.\n */\n r: Bytes;\n\n /**\n * EC signature parameter\n * Signature proof.\n * 32 bytes long sequence\n */\n s: Bytes;\n\n /**\n * Recovery identifier. It can be either 0x1b or 0x1c\n * 1 byte long sequence\n */\n yParity: Bytes;\n};\n\n/**\n * Base Ethereum Transaction\n */\nexport type BaseTransaction = {\n /**\n * Sequentially incrementing counter which indicates the transaction\n * number from the account\n */\n nonce: Bytes;\n\n /**\n * The address of the sender, that will be signing the transaction\n */\n from: Hex | Uint8Array;\n\n /**\n * The receiving address.\n * If an externally-owned account, the transaction will transfer value.\n * If a contract account, the transaction will execute the contract code.\n */\n to: Hex | Uint8Array;\n\n /**\n * The amount of Ether sent.\n */\n value: Bytes;\n\n /**\n * Maximum amount of gas units that this transaction can consume.\n */\n gasLimit: Bytes;\n\n /**\n * Arbitrary data.\n */\n data?: Bytes;\n};\n\n/**\n * Typed Ethereum Transaction\n */\nexport type TypedTransaction = BaseTransaction & {\n /**\n * Transaction type.\n */\n type: number;\n};\n\n/**\n * Ethereum Legacy Transaction\n * Reference: https://ethereum.org/en/developers/docs/transactions/\n */\nexport type LegacyTransaction = BaseTransaction & {\n /**\n * Transaction's gas price.\n */\n gasPrice: Bytes | null;\n};\n\n/**\n * EIP-2930 Transaction: Optional Access Lists\n * Reference: https://eips.ethereum.org/EIPS/eip-2930\n */\nexport type EIP2930Transaction = TypedTransaction & {\n /**\n * Transaction type.\n */\n type: 1;\n\n /**\n * Transaction chain ID\n */\n chainId: Bytes;\n\n /**\n * List of addresses and storage keys that the transaction plans to access\n */\n accessList:\n | { address: Hex; storageKeys: Hex[] }[]\n | { address: Uint8Array; storageKeys: Uint8Array[] }[];\n};\n\n/**\n * EIP-1559 Transaction: Fee market change for ETH 1.0 chain (Type-2)\n *\n * Reference: https://eips.ethereum.org/EIPS/eip-1559\n */\nexport type EIP1559Transaction = TypedTransaction & {\n /**\n * Transaction type.\n */\n type: 2;\n\n /**\n * Maximum fee to give to the miner\n */\n maxPriorityFeePerGas: Bytes;\n\n /**\n * Maximum total fee\n */\n maxFeePerGas: Bytes;\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.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unitsConversion.d.ts","s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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.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unitsConversion.js","sourceRoot":"","sources":["../src/unitsConversion.ts"],"names":[],"mappings":"AAAA,wCAAwC;AACxC;;;;;;EAME;AAEF,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,SAAS,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AAE7B;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,GAA6B;IAC3D,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC5B,OAAO,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AC;IACxC,IAAI,GAAG,GAAG,WAAW,GAAG,IAAI,GAAG,cAAc,CAAC;IAE9C,IAAI,QAAQ,EAAE,CAAC;QACb,GAAG,GAAG,GAAG,GAAG,SAAS,CAAC;IACxB,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","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,101 @@
1
+ import type { Struct } from '@metamask/superstruct';
2
+ import type { Opaque } from './opaque.js';
3
+ /**
4
+ * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.
5
+ *
6
+ * @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.
7
+ * ```typescript
8
+ * const unsafeRange: string = dataFromUser();
9
+ * assertIsSemVerRange(unsafeRange);
10
+ * unsafeRange
11
+ * // ^? SemVerRange
12
+ * ```
13
+ * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.
14
+ * ```typescript
15
+ * const unsafeRange: string = dataFromUser();
16
+ * unsafeRange as SemVerRange;
17
+ * // ^? SemVerRange
18
+ * ```
19
+ * @see {@link assertIsSemVerRange}
20
+ * @see {@link isValidSemVerRange}
21
+ */
22
+ export type SemVerRange = Opaque<string, typeof semVerRange>;
23
+ declare const semVerRange: unique symbol;
24
+ /**
25
+ * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.
26
+ *
27
+ * @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.
28
+ * ```typescript
29
+ * const unsafeVersion: string = dataFromUser();
30
+ * assertIsSemVerVersion(unsafeRange);
31
+ * unsafeVersion
32
+ * // ^? SemVerVersion
33
+ * ```
34
+ * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.
35
+ * ```typescript
36
+ * const unsafeVersion: string = dataFromUser();
37
+ * unsafeRange as SemVerVersion;
38
+ * // ^? SemVerVersion
39
+ * ```
40
+ * @see {@link assertIsSemVerVersion}
41
+ * @see {@link isValidSemVerVersion}
42
+ */
43
+ export type SemVerVersion = Opaque<string, typeof semVerVersion>;
44
+ declare const semVerVersion: unique symbol;
45
+ /**
46
+ * A struct for validating a version string.
47
+ */
48
+ export declare const VersionStruct: Struct<SemVerVersion, null>;
49
+ export declare const VersionRangeStruct: Struct<SemVerRange, null>;
50
+ /**
51
+ * Checks whether a SemVer version is valid.
52
+ *
53
+ * @param version - A potential version.
54
+ * @returns `true` if the version is valid, and `false` otherwise.
55
+ */
56
+ export declare function isValidSemVerVersion(version: unknown): version is SemVerVersion;
57
+ /**
58
+ * Checks whether a SemVer version range is valid.
59
+ *
60
+ * @param versionRange - A potential version range.
61
+ * @returns `true` if the version range is valid, and `false` otherwise.
62
+ */
63
+ export declare function isValidSemVerRange(versionRange: unknown): versionRange is SemVerRange;
64
+ /**
65
+ * Asserts that a value is a valid concrete SemVer version.
66
+ *
67
+ * @param version - A potential SemVer concrete version.
68
+ */
69
+ export declare function assertIsSemVerVersion(version: unknown): asserts version is SemVerVersion;
70
+ /**
71
+ * Asserts that a value is a valid SemVer range.
72
+ *
73
+ * @param range - A potential SemVer range.
74
+ */
75
+ export declare function assertIsSemVerRange(range: unknown): asserts range is SemVerRange;
76
+ /**
77
+ * Checks whether a SemVer version is greater than another.
78
+ *
79
+ * @param version1 - The left-hand version.
80
+ * @param version2 - The right-hand version.
81
+ * @returns `version1 > version2`.
82
+ */
83
+ export declare function gtVersion(version1: SemVerVersion, version2: SemVerVersion): boolean;
84
+ /**
85
+ * Checks whether a SemVer version is greater than all possibilities in a range.
86
+ *
87
+ * @param version - A SemvVer version.
88
+ * @param range - The range to check against.
89
+ * @returns `version > range`.
90
+ */
91
+ export declare function gtRange(version: SemVerVersion, range: SemVerRange): boolean;
92
+ /**
93
+ * Returns whether a SemVer version satisfies a SemVer range.
94
+ *
95
+ * @param version - The SemVer version to check.
96
+ * @param versionRange - The SemVer version range to check against.
97
+ * @returns Whether the version satisfied the version range.
98
+ */
99
+ export declare function satisfiesVersionRange(version: SemVerVersion, versionRange: SemVerRange): boolean;
100
+ export {};
101
+ //# sourceMappingURL=versions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"versions.d.ts","sourceRoot":"","sources":["../src/versions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAWpD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAE1C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,WAAW,CAAC,CAAC;AAE7D,OAAO,CAAC,MAAM,WAAW,EAAE,OAAO,MAAM,CAAC;AAEzC;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,aAAa,CAAC,CAAC;AAEjE,OAAO,CAAC,MAAM,aAAa,EAAE,OAAO,MAAM,CAAC;AAE3C;;GAEG;AACH,eAAO,MAAM,aAAa,6BASzB,CAAC;AAEF,eAAO,MAAM,kBAAkB,2BAS9B,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,OAAO,GACf,OAAO,IAAI,aAAa,CAE1B;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,OAAO,GACpB,YAAY,IAAI,WAAW,CAE7B;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,OAAO,GACf,OAAO,CAAC,OAAO,IAAI,aAAa,CAElC;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,KAAK,IAAI,WAAW,CAE9B;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CACvB,QAAQ,EAAE,aAAa,EACvB,QAAQ,EAAE,aAAa,GACtB,OAAO,CAET;AAED;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAE3E;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,aAAa,EACtB,YAAY,EAAE,WAAW,GACxB,OAAO,CAIT"}
@@ -0,0 +1,85 @@
1
+ import { is, refine, string } from '@metamask/superstruct';
2
+ import { gt as gtSemver, gtr as gtrSemver, satisfies as satisfiesSemver, valid as validSemVerVersion, validRange as validSemVerRange, } from 'semver';
3
+ import { assertStruct } from './assert.js';
4
+ /**
5
+ * A struct for validating a version string.
6
+ */
7
+ export const VersionStruct = refine(string(), 'Version', (value) => {
8
+ if (validSemVerVersion(value) === null) {
9
+ return `Expected SemVer version, got "${value}"`;
10
+ }
11
+ return true;
12
+ });
13
+ export const VersionRangeStruct = refine(string(), 'Version range', (value) => {
14
+ if (validSemVerRange(value) === null) {
15
+ return `Expected SemVer range, got "${value}"`;
16
+ }
17
+ return true;
18
+ });
19
+ /**
20
+ * Checks whether a SemVer version is valid.
21
+ *
22
+ * @param version - A potential version.
23
+ * @returns `true` if the version is valid, and `false` otherwise.
24
+ */
25
+ export function isValidSemVerVersion(version) {
26
+ return is(version, VersionStruct);
27
+ }
28
+ /**
29
+ * Checks whether a SemVer version range is valid.
30
+ *
31
+ * @param versionRange - A potential version range.
32
+ * @returns `true` if the version range is valid, and `false` otherwise.
33
+ */
34
+ export function isValidSemVerRange(versionRange) {
35
+ return is(versionRange, VersionRangeStruct);
36
+ }
37
+ /**
38
+ * Asserts that a value is a valid concrete SemVer version.
39
+ *
40
+ * @param version - A potential SemVer concrete version.
41
+ */
42
+ export function assertIsSemVerVersion(version) {
43
+ assertStruct(version, VersionStruct);
44
+ }
45
+ /**
46
+ * Asserts that a value is a valid SemVer range.
47
+ *
48
+ * @param range - A potential SemVer range.
49
+ */
50
+ export function assertIsSemVerRange(range) {
51
+ assertStruct(range, VersionRangeStruct);
52
+ }
53
+ /**
54
+ * Checks whether a SemVer version is greater than another.
55
+ *
56
+ * @param version1 - The left-hand version.
57
+ * @param version2 - The right-hand version.
58
+ * @returns `version1 > version2`.
59
+ */
60
+ export function gtVersion(version1, version2) {
61
+ return gtSemver(version1, version2);
62
+ }
63
+ /**
64
+ * Checks whether a SemVer version is greater than all possibilities in a range.
65
+ *
66
+ * @param version - A SemvVer version.
67
+ * @param range - The range to check against.
68
+ * @returns `version > range`.
69
+ */
70
+ export function gtRange(version, range) {
71
+ return gtrSemver(version, range);
72
+ }
73
+ /**
74
+ * Returns whether a SemVer version satisfies a SemVer range.
75
+ *
76
+ * @param version - The SemVer version to check.
77
+ * @param versionRange - The SemVer version range to check against.
78
+ * @returns Whether the version satisfied the version range.
79
+ */
80
+ export function satisfiesVersionRange(version, versionRange) {
81
+ return satisfiesSemver(version, versionRange, {
82
+ includePrerelease: true,
83
+ });
84
+ }
85
+ //# sourceMappingURL=versions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"versions.js","sourceRoot":"","sources":["../src/versions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EACL,EAAE,IAAI,QAAQ,EACd,GAAG,IAAI,SAAS,EAChB,SAAS,IAAI,eAAe,EAC5B,KAAK,IAAI,kBAAkB,EAC3B,UAAU,IAAI,gBAAgB,GAC/B,MAAM,QAAQ,CAAC;AAEhB,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAiD3C;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,G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C;AAED;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CACnC,OAAsB,EACtB,YAAyB;IAEzB,OAAO,eAAe,CAAC,OAAO,EAAE,YAAY,EAAE;QAC5C,iBAAiB,EAAE,IAAI;KACxB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Struct } from '@metamask/superstruct';\nimport { is, refine, string } from '@metamask/superstruct';\nimport {\n gt as gtSemver,\n gtr as gtrSemver,\n satisfies as satisfiesSemver,\n valid as validSemVerVersion,\n validRange as validSemVerRange,\n} from 'semver';\n\nimport { assertStruct } from './assert.js';\nimport type { Opaque } from './opaque.js';\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.\n *\n * @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * assertIsSemVerRange(unsafeRange);\n * unsafeRange\n * // ^? SemVerRange\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * unsafeRange as SemVerRange;\n * // ^? SemVerRange\n * ```\n * @see {@link assertIsSemVerRange}\n * @see {@link isValidSemVerRange}\n */\nexport type SemVerRange = Opaque<string, typeof semVerRange>;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Branding symbol for the opaque type; used only via `typeof`.\ndeclare const semVerRange: unique symbol;\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.\n *\n * @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * assertIsSemVerVersion(unsafeRange);\n * unsafeVersion\n * // ^? SemVerVersion\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * unsafeRange as SemVerVersion;\n * // ^? SemVerVersion\n * ```\n * @see {@link assertIsSemVerVersion}\n * @see {@link isValidSemVerVersion}\n */\nexport type SemVerVersion = Opaque<string, typeof semVerVersion>;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Branding symbol for the opaque type; used only via `typeof`.\ndeclare const semVerVersion: unique symbol;\n\n/**\n * A struct for validating a version string.\n */\nexport const VersionStruct = refine<SemVerVersion, null>(\n string() as unknown as Struct<SemVerVersion, null>,\n 'Version',\n (value) => {\n if (validSemVerVersion(value) === null) {\n return `Expected SemVer version, got \"${value}\"`;\n }\n return true;\n },\n);\n\nexport const VersionRangeStruct = refine<SemVerRange, null>(\n string() as unknown as Struct<SemVerRange, null>,\n 'Version range',\n (value) => {\n if (validSemVerRange(value) === null) {\n return `Expected SemVer range, got \"${value}\"`;\n }\n return true;\n },\n);\n\n/**\n * Checks whether a SemVer version is valid.\n *\n * @param version - A potential version.\n * @returns `true` if the version is valid, and `false` otherwise.\n */\nexport function isValidSemVerVersion(\n version: unknown,\n): version is SemVerVersion {\n return is(version, VersionStruct);\n}\n\n/**\n * Checks whether a SemVer version range is valid.\n *\n * @param versionRange - A potential version range.\n * @returns `true` if the version range is valid, and `false` otherwise.\n */\nexport function isValidSemVerRange(\n versionRange: unknown,\n): versionRange is SemVerRange {\n return is(versionRange, VersionRangeStruct);\n}\n\n/**\n * Asserts that a value is a valid concrete SemVer version.\n *\n * @param version - A potential SemVer concrete version.\n */\nexport function assertIsSemVerVersion(\n version: unknown,\n): asserts version is SemVerVersion {\n assertStruct(version, VersionStruct);\n}\n\n/**\n * Asserts that a value is a valid SemVer range.\n *\n * @param range - A potential SemVer range.\n */\nexport function assertIsSemVerRange(\n range: unknown,\n): asserts range is SemVerRange {\n assertStruct(range, VersionRangeStruct);\n}\n\n/**\n * Checks whether a SemVer version is greater than another.\n *\n * @param version1 - The left-hand version.\n * @param version2 - The right-hand version.\n * @returns `version1 > version2`.\n */\nexport function gtVersion(\n version1: SemVerVersion,\n version2: SemVerVersion,\n): boolean {\n return gtSemver(version1, version2);\n}\n\n/**\n * Checks whether a SemVer version is greater than all possibilities in a range.\n *\n * @param version - A SemvVer version.\n * @param range - The range to check against.\n * @returns `version > range`.\n */\nexport function gtRange(version: SemVerVersion, range: SemVerRange): boolean {\n return gtrSemver(version, range);\n}\n\n/**\n * Returns whether a SemVer version satisfies a SemVer range.\n *\n * @param version - The SemVer version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns Whether the version satisfied the version range.\n */\nexport function satisfiesVersionRange(\n version: SemVerVersion,\n versionRange: SemVerRange,\n): boolean {\n return satisfiesSemver(version, versionRange, {\n includePrerelease: true,\n });\n}\n"]}