@meantjs/format 0.0.0-stage → 0.1.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/CHANGELOG.md +21 -0
- package/LICENSE +202 -0
- package/README.md +123 -2
- package/package.json +49 -4
- package/src/account.mjs +78 -0
- package/src/amount.mjs +92 -0
- package/src/bytes.mjs +131 -0
- package/src/errors.mjs +49 -0
- package/src/formatter.mjs +272 -0
- package/src/index.d.mts +169 -0
- package/src/index.mjs +17 -0
- package/src/names.mjs +59 -0
- package/src/principal.mjs +117 -0
- package/src/subaccount.mjs +49 -0
- package/src/time.mjs +258 -0
- package/src/util.mjs +139 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Changelog: @meantjs/format
|
|
2
|
+
|
|
3
|
+
The five Candid Profile library packages (`@meantjs/profile`, `/format`, `/consent`, `/tools`, `/reconcile`) release together under one version and pin each other exactly; a version appears here even when this package did not change. Release steps: `docs/releasing.md` in the repository.
|
|
4
|
+
|
|
5
|
+
## 0.1.0 — 2026-10-28
|
|
6
|
+
|
|
7
|
+
First published version.
|
|
8
|
+
|
|
9
|
+
Published under the `@meantjs` scope (D-051). Before any release, this package was `@candid-core/profile-format`.
|
|
10
|
+
|
|
11
|
+
- Names (spec §5.3, D-045): `normalizeName`, `resolveName`, `nameOf` and `ownerOf`, the one rule every consumer
|
|
12
|
+
reads a name by, checked against the shared vectors in `spec/names-vectors.json`. `ownerOf` and `nameOf` compare
|
|
13
|
+
Candid values structurally, so two different accounts never share a name.
|
|
14
|
+
- Exact parse and display for the six value tags of Candid Profile v0: `amount`, `timestamp`, `duration`, `account`,
|
|
15
|
+
`subaccount`, `bytes`. Excess precision is refused, never rounded; integers never pass through a JavaScript number.
|
|
16
|
+
- `formatterFor(node, { refs, now })` for a position of a resolved form, with `describe()` for form hints and tool
|
|
17
|
+
descriptions; `FormatError` with stable codes.
|
|
18
|
+
- No dependency, no Node built-in: runs in Node 22+ and in browsers.
|
|
19
|
+
- Bytes from another realm (an iframe, a `node:vm` context) are accepted wherever a `Uint8Array` is; the check is
|
|
20
|
+
exported as `asUint8Array`.
|
|
21
|
+
- TypeScript declarations.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,124 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @meantjs/format
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Exact value conversion for the six value tags of Candid Profile v0 (`docs/profile-v0.md` §5.3): `amount`, `timestamp`, `duration`, `account`, `subaccount` and `bytes`. It turns the text a person or an agent writes (`"1.5 ICP"`, `"+PT24H"`, `"#7"`) into the value a call carries, and back into canonical text for display. The agent tools (`@meantjs/tools`) and the ICRC-21 consent generator (`@meantjs/consent`) both use it, so they cannot disagree about what a value means.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @meantjs/format
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
- **Runs on:** Node 22 or later and browsers: no dependency, no I/O, no Node built-in.
|
|
10
|
+
- **Module format:** ES modules only, with hand-written TypeScript declarations for every entry.
|
|
11
|
+
- **Spec:** [Candid Profile v0](https://github.com/B3Pay/Meant/blob/main/profile/docs/profile-v0.md). **Licence:** Apache-2.0.
|
|
12
|
+
- **Versions:** the five Candid Profile packages (`@meantjs/profile`, `/format`, `/consent`, `/tools`,
|
|
13
|
+
`/reconcile`) release together under one version and pin each other exactly; in 0.x a minor is breaking,
|
|
14
|
+
and so is any change to generated text ([releasing](https://github.com/B3Pay/Meant/blob/main/profile/docs/releasing.md)).
|
|
15
|
+
|
|
16
|
+
- **No rounding, ever** (ground rule 8, D-006): input with excess precision is rejected, a conversion that would lose precision throws, integers never pass through a JavaScript number.
|
|
17
|
+
- **No dependencies** at run time or for tests. Node >= 22.
|
|
18
|
+
- **No I/O.** Dynamic tag arguments (`{ "from": "query:icrc1_decimals" }`) are resolved by the caller and passed in.
|
|
19
|
+
- The choices it made where §5.3 was open were accepted as D-024 and are now in spec §5.3.
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm test -w packages/format # or: npm test at the repo root
|
|
23
|
+
npm run vectors -w packages/format # re-fetch the ICRC-1 examples (needs network; see below)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## API
|
|
27
|
+
|
|
28
|
+
The entry point for consumers:
|
|
29
|
+
|
|
30
|
+
```js
|
|
31
|
+
import { formatterFor } from "@meantjs/format";
|
|
32
|
+
|
|
33
|
+
// node = a position of the resolved form (fixtures/*.resolved.json): { candid, tags, ... }
|
|
34
|
+
const f = formatterFor(node, {
|
|
35
|
+
refs: { "query:icrc1_decimals": 8, "query:icrc1_symbol": "ICP" }, // dynamic args, keyed by their `from`
|
|
36
|
+
now: 1791547200000000000n, // optional default clock, bigint ns
|
|
37
|
+
});
|
|
38
|
+
// f === null when the position has no value tag (render it as Candid text, spec §6)
|
|
39
|
+
|
|
40
|
+
f.tag; // "amount" | "timestamp" | "duration" | "account" | "subaccount" | "bytes"
|
|
41
|
+
f.args; // the tag's arguments with refs resolved, e.g. { decimals: 8, symbol: "ICP" }
|
|
42
|
+
f.parse("1.5 ICP"); // -> "150000000" (throws FormatError)
|
|
43
|
+
f.display("150000000"); // -> "1.5 ICP" (throws FormatError)
|
|
44
|
+
f.safeParse(input, { now }); // -> { ok: true, value } | { ok: false, error: { code, message } }
|
|
45
|
+
f.safeDisplay(value); // same shape
|
|
46
|
+
f.describe(); // -> { summary, examples, pattern? }: the text this position reads, in words
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`describe()` gives a form hint or a tool input's description from the parser itself, so they cannot drift from it (#16). The summary is the grammar in words with the tag's resolved arguments filled in ("at most 8 digits after the point", the symbol), then "For example" and exactly the examples kept. Every kept example parses at this position: one a range or `max_len` refuses is left out (and the summary then quotes none), and a relative time is checked against the formatter's `now` when it was given one, else against a fixed instant, since describing reads no clock. `pattern` (amount and subaccount only, whose grammar is regular) is an ECMAScript regular expression for a JSON Schema `pattern`, valid under the `u` flag. It is a necessary condition only: everything `parse` accepts matches it, and a match can still be refused for its range. `describeInput(tag, args, candid, { accepts })` is the same without a formatter: it refuses the arguments and Candid types `formatterFor` refuses, with the same codes, and keeps the examples `accepts` returns true for (all, by default).
|
|
50
|
+
|
|
51
|
+
`formatterFor` throws a `FormatError` (never returns a half-working formatter) when a ref is missing (`E_REF_UNRESOLVED`), a tag argument is invalid (`E_ARG`), the tag does not apply to the node's Candid type (`E_TAG_TYPE`) or the position carries two value tags (`E_TAG_CONFLICT`). `opt` is the node's `optional` flag: handle absence before calling the formatter.
|
|
52
|
+
|
|
53
|
+
The same functions are exported directly: `parseAmount`, `displayAmount`, `parseTimestamp`, `displayTimestamp`, `parseDuration`, `displayDuration`, `convertUnit`, `alignNow`, `parseAccount`, `displayAccount`, `principalFromText`, `principalToText`, `parseSubaccount`, `displaySubaccount`, `parseBytes`, `displayBytes`, `VALUE_TAGS`, `describeInput`, `CODES`, `FormatError`.
|
|
54
|
+
|
|
55
|
+
### Values
|
|
56
|
+
|
|
57
|
+
| Tag | `parse` returns / `display` takes | Options |
|
|
58
|
+
|---|---|---|
|
|
59
|
+
| `amount` | base-unit integer as a decimal string (a bigint is accepted by `display`; a number is rejected) | `decimals`, `symbol`, `candid` (sign and range) |
|
|
60
|
+
| `timestamp` | integer count of `unit` since the Unix epoch, decimal string | `unit` (`ns` `us` `ms` `s`), `candid`, `now` (bigint ns, relative input only) |
|
|
61
|
+
| `duration` | integer count of `unit`, decimal string | `unit`, `candid` |
|
|
62
|
+
| `account` | `{ owner: <principal text>, subaccount: Uint8Array(32) \| null }`, `null` = the default subaccount | |
|
|
63
|
+
| `subaccount` | `Uint8Array(32)` | |
|
|
64
|
+
| `bytes` | `Uint8Array` | `encoding` (`utf8` `hex` `base64`), `maxLen` (the tag's `max_len`, bytes) |
|
|
65
|
+
|
|
66
|
+
Wherever a `Uint8Array` is taken, one made in another realm (an iframe, a `node:vm` context, a test environment's
|
|
67
|
+
`TextEncoder`) is accepted too, read through its typed-array slot; other typed arrays, `DataView`s and look-alike
|
|
68
|
+
objects are refused with `E_TYPE`, and so are a `Proxy` around a `Uint8Array` (it passed `instanceof` before) and
|
|
69
|
+
a view of a detached buffer. A foreign view's memory is read through the intrinsic typed-array getters, so its own
|
|
70
|
+
properties cannot make it show other bytes. The library imports no Node built-in (`test/browser-bundle.test.mjs`). The check is exported as `asUint8Array(value)`: the value as a `Uint8Array` of this realm viewing the same memory, or `null`. `@meantjs/consent` and `@meantjs/tools` use it, so the three packages agree on what bytes are.
|
|
71
|
+
|
|
72
|
+
Other helpers: `convertUnit(value, from, to)` converts an integer between units and throws `E_INEXACT` when it would lose precision (W4: a ns timestamp with sub-second digits does not fit ICRC-21's `TimestampSeconds`; catch it and fall back to `Text`). `alignNow(nowNs, unit)` floors a clock reading to a unit. `parseTimestamp` already does this to `now` before adding a relative duration (spec §5.3, D-024), so `+PT24H` on a `unit: s` field is exact; `alignNow` is exported for callers that want the aligned value themselves.
|
|
73
|
+
|
|
74
|
+
### Errors
|
|
75
|
+
|
|
76
|
+
Every rejection is a `FormatError` with a stable `code` and a message that says how to fix the input. Codes: `E_TYPE` `E_SYNTAX` `E_RANGE` `E_TOO_LONG` `E_ARG` `E_TAG_TYPE` `E_TAG_CONFLICT` `E_REF_UNRESOLVED` `E_EXCESS_PRECISION` `E_NEGATIVE` `E_SYMBOL_MISMATCH` `E_INEXACT` `E_CALENDAR_UNIT` `E_NEEDS_NOW` `E_CHECKSUM` `E_CHECKSUM_MISSING` `E_NOT_CANONICAL` `E_PRINCIPAL` `E_HEX` `E_BASE64` `E_UTF8` `E_LENGTH` `E_MAX_LEN` (`CODES` lists them with their meaning).
|
|
77
|
+
|
|
78
|
+
## Rules and where they are tested
|
|
79
|
+
|
|
80
|
+
| Spec §5.3 rule | Behavior | Test (`test/rejections.test.mjs` unless noted) |
|
|
81
|
+
|---|---|---|
|
|
82
|
+
| amount: more than `d` fractional digits is rejected, never rounded | `E_EXCESS_PRECISION` (also for trailing zeros, proposal F1) | "amount: input with more than d fractional digits…"; property in `amount.test.mjs` |
|
|
83
|
+
| amount: negative rejected unless signed | `E_NEGATIVE` | "amount: negative input…" |
|
|
84
|
+
| amount: symbol must match, case-insensitive | `E_SYMBOL_MISMATCH` | "amount: a symbol that does not match…" |
|
|
85
|
+
| timestamp: conversion to the unit is exact (an absolute time or a duration finer than the unit) | `E_INEXACT` | "timestamp: a conversion… is not exact"; properties in `time.test.mjs` |
|
|
86
|
+
| timestamp: relative input is resolved against `now` floored to the unit | | "timestamp: a relative time is resolved against now floored…" |
|
|
87
|
+
| timestamp: relative input follows the duration rules | `E_CALENDAR_UNIT`, `E_NEEDS_NOW` | "timestamp: relative input…" (two tests) |
|
|
88
|
+
| duration: only W, D, H, M (after T), S | `E_SYNTAX` | "duration: only W, D, H, M…" |
|
|
89
|
+
| duration: `P1Y`, `P1M` rejected | `E_CALENDAR_UNIT` | "duration: calendar years and months…" |
|
|
90
|
+
| duration: `P1D` is exactly 86,400 s | | "duration: P1D is exactly 86,400 s" |
|
|
91
|
+
| account: checksum verified on input | `E_CHECKSUM`, `E_CHECKSUM_MISSING` | "account: the checksum is verified on input"; the ICRC-1 vectors in `account.test.mjs` |
|
|
92
|
+
| subaccount: `0 <= n < 2^64` | `E_RANGE` | "subaccount: a decimal n outside…" |
|
|
93
|
+
| subaccount: hex is exactly 64 characters | `E_LENGTH` | "subaccount: a hex form with other than exactly 64…" |
|
|
94
|
+
| subaccount: `parse(display(x)) = x` for every 32-byte value | | edge values in `rejections.test.mjs`; property over 20,000 random values in `subaccount.test.mjs` |
|
|
95
|
+
| subaccount: display is `#n` iff the first 24 bytes are zero | | "subaccount: display is #n if and only if…" and the same property |
|
|
96
|
+
| bytes: `max_len` counts bytes after encoding | `E_MAX_LEN` | "bytes: max_len counts bytes after encoding…" |
|
|
97
|
+
| bytes: utf8 input starting with `0x` is hex | `E_HEX` for malformed hex | "bytes: utf8 input starting with 0x is hex…" |
|
|
98
|
+
| §4 / D-006: integers are never JavaScript numbers | `E_TYPE` | "an integer is never a JavaScript number…" |
|
|
99
|
+
|
|
100
|
+
## Why no principal library
|
|
101
|
+
|
|
102
|
+
`principalFromText` and the ICRC-1 checksum need base32 and CRC-32. Options considered:
|
|
103
|
+
|
|
104
|
+
- `@dfinity/principal` 3.4.3: tiny (one dependency, `@noble/hashes`), but **deprecated** on npm in favour of `@icp-sdk/core`, which would put a deprecation warning on every `npm ci`.
|
|
105
|
+
- `@icp-sdk/core` 6.1.0: the supported package, but 2.2 MB unpacked with six direct dependencies (asn1js, two `@scure` BIP packages, `@dfinity/cbor`, `@noble/curves`, `@noble/hashes`) for a feature that is ~60 lines. It also pulls key-handling code into a package whose point is to be small enough to review.
|
|
106
|
+
- **Chosen: implement it** in `src/principal.mjs` (base32 lowercase without padding, CRC-32 with the zlib polynomial, the canonical-dashes rule), with zero dependencies, and check it three ways:
|
|
107
|
+
1. the 7 official ICRC-1 parse examples and 3 `toText` examples, well-known canister ids (`aaaaa-aa`, `2vxsx-fae`, the ICP ledger, NNS governance and registry);
|
|
108
|
+
2. independent oracles in the tests: CRC-32 from `node:zlib`, and a base32 encoder built on big-integer division (a different algorithm from the bit shifter in `src`), compared on thousands of random principals and accounts; plus a property that **every single-character change** to a canonical account text is rejected;
|
|
109
|
+
3. a one-off differential run against `@dfinity/principal` 3.4.3 (installed temporarily, removed again): 60,000 random principals of 0 to 29 bytes, text and bytes in both directions, 0 mismatches. This is **not** in the suite, so it is not reproducible from the repo; the suite's oracles are.
|
|
110
|
+
|
|
111
|
+
## ICRC-1 test vectors
|
|
112
|
+
|
|
113
|
+
`test/vectors/icrc1-textual-encoding.json` holds the examples of the ICRC-1 textual encoding standard, extracted by `scripts/fetch-icrc1-vectors.mjs` from `standards/ICRC-1/TextualEncoding.md` of github.com/dfinity/ICRC-1 at commit `5d670e54d9a58fbf472bf0a25f33743d60cfd0e6` (head of `main` on 2026-10-09; Apache-2.0). The download itself, with its LICENSE, `SOURCE.json` (commit, URLs, sha256) lives alone in `upstream/icrc1/`.
|
|
114
|
+
|
|
115
|
+
The download is **untrusted data**: the script only reads it as text and extracts fields with fixed regular expressions (and aborts if the shape changes), nothing from `upstream/` is ever imported or executed, and the tests read the committed JSON, never the network. A test checks that the recorded sha256 matches the committed bytes and that every vector appears in the document. To move to another commit: `node scripts/fetch-icrc1-vectors.mjs --commit <40-hex sha>`, review the diff of `upstream/` and the vectors, update `PINNED` in the script.
|
|
116
|
+
|
|
117
|
+
## Design notes
|
|
118
|
+
|
|
119
|
+
- **Integers are decimal strings or bigints** (D-006). Nanosecond timestamps (~1.8e18) and 18-decimal amounts exceed 2^53; a JavaScript number is rejected on input and on display.
|
|
120
|
+
- **Calendar math is in BigInt nanoseconds** with the proleptic Gregorian calendar (days-from-civil), not `Date` (millisecond precision). Tests compare against `Date` for millisecond instants and zones.
|
|
121
|
+
- **Display is canonical and total**: it throws on a value that does not fit the Candid type or the calendar instead of producing something misleading.
|
|
122
|
+
- **Untrusted text**: lengths are bounded (1024 characters; 4 MiB for `bytes`), regular expressions are anchored and linear, symbols from a canister's `icrc1_symbol` are checked for control and invisible characters before use.
|
|
123
|
+
- **Escaping is not done here.** `display` returns plain text; a memo can contain Markdown. The template renderer escapes values for its target format (spec §6).
|
|
124
|
+
- **Property tests** use a seeded PRNG (`test/helpers/prng.mjs`, default seed 20261009, override with `FORMAT_TEST_SEED`); every failure message carries the seed.
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@meantjs/format",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Exact value conversion for Candid Profile value tags (amount, timestamp, duration, account, subaccount, bytes): parse human input, display canonical text, never round.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/B3Pay/Meant.git",
|
|
9
|
+
"directory": "profile/packages/format"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/B3Pay/Meant/tree/main/profile/packages/format#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/B3Pay/Meant/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"candid",
|
|
17
|
+
"internet-computer",
|
|
18
|
+
"icp",
|
|
19
|
+
"icrc-1",
|
|
20
|
+
"amount",
|
|
21
|
+
"account",
|
|
22
|
+
"principal",
|
|
23
|
+
"no-rounding"
|
|
24
|
+
],
|
|
25
|
+
"type": "module",
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"main": "./src/index.mjs",
|
|
28
|
+
"types": "./src/index.d.mts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./src/index.d.mts",
|
|
32
|
+
"default": "./src/index.mjs"
|
|
33
|
+
},
|
|
34
|
+
"./package.json": "./package.json"
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"src",
|
|
38
|
+
"CHANGELOG.md",
|
|
39
|
+
"LICENSE"
|
|
40
|
+
],
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=22"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"test": "node --test \"test/*.test.mjs\"",
|
|
46
|
+
"vectors": "node scripts/fetch-icrc1-vectors.mjs"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"esbuild": "0.28.2"
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/account.mjs
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// `account`, encoding `icrc1` (spec §5.3): the ICRC-1 textual encoding of
|
|
2
|
+
// record { owner : principal; subaccount : opt blob }.
|
|
3
|
+
//
|
|
4
|
+
// default subaccount (absent or 32 zero bytes): <principal>
|
|
5
|
+
// any other subaccount: <principal>-<checksum>.<subaccount hex without leading zeros>
|
|
6
|
+
// checksum = base32 (lowercase, no padding) of CRC-32(principal bytes ++ 32 subaccount bytes)
|
|
7
|
+
//
|
|
8
|
+
// Source: dfinity/ICRC-1 standards/ICRC-1/TextualEncoding.md. Value shape here:
|
|
9
|
+
// { owner: <principal text>, subaccount: Uint8Array(32) | null } (null = the default subaccount)
|
|
10
|
+
|
|
11
|
+
import { CODES, fail } from "./errors.mjs";
|
|
12
|
+
import { MAX_INPUT_CHARS, bytesToHex, hexToBytes, requireString, toBytes } from "./util.mjs";
|
|
13
|
+
import { accountChecksum, principalFromText, principalToText } from "./principal.mjs";
|
|
14
|
+
|
|
15
|
+
const CHECKSUM_RE = /^[a-z2-7]{7}$/i;
|
|
16
|
+
|
|
17
|
+
const isZero = (b) => b.every((x) => x === 0);
|
|
18
|
+
|
|
19
|
+
/** Owner as principal bytes, from canonical text or bytes. */
|
|
20
|
+
function ownerBytes(owner) {
|
|
21
|
+
if (typeof owner === "string") return principalFromText(owner);
|
|
22
|
+
const b = toBytes(owner, "owner");
|
|
23
|
+
principalToText(b); // length check
|
|
24
|
+
return b;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Parse an ICRC-1 account text. A bare principal is the default subaccount. The checksum is
|
|
29
|
+
* verified, and non-canonical texts (an explicit default subaccount, leading zeros in the
|
|
30
|
+
* subaccount, wrong dashes) are rejected.
|
|
31
|
+
*
|
|
32
|
+
* @param {string} input
|
|
33
|
+
* @returns {{ owner: string, subaccount: Uint8Array | null }}
|
|
34
|
+
*/
|
|
35
|
+
export function parseAccount(input) {
|
|
36
|
+
const text = requireString(input, "account").trim();
|
|
37
|
+
if (text.length > MAX_INPUT_CHARS) fail(CODES.TOO_LONG, "account is too long");
|
|
38
|
+
const dot = text.indexOf(".");
|
|
39
|
+
if (dot < 0) return { owner: principalToText(principalFromText(text)), subaccount: null };
|
|
40
|
+
if (text.indexOf(".", dot + 1) >= 0) fail(CODES.SYNTAX, `${JSON.stringify(text)} has more than one "."`);
|
|
41
|
+
|
|
42
|
+
const left = text.slice(0, dot);
|
|
43
|
+
const hex = text.slice(dot + 1);
|
|
44
|
+
const dash = left.lastIndexOf("-");
|
|
45
|
+
const checksum = dash < 0 ? "" : left.slice(dash + 1);
|
|
46
|
+
if (!CHECKSUM_RE.test(checksum)) {
|
|
47
|
+
fail(CODES.CHECKSUM_MISSING, `${JSON.stringify(text)} has a subaccount but no checksum: the form is <principal>-<checksum>.<subaccount>`);
|
|
48
|
+
}
|
|
49
|
+
if (hex === "") fail(CODES.NOT_CANONICAL, "the default subaccount is written as the bare principal, without a checksum or a dot");
|
|
50
|
+
if (!/^[0-9a-fA-F]+$/.test(hex)) fail(CODES.HEX, `the subaccount ${JSON.stringify(hex)} is not hexadecimal`);
|
|
51
|
+
if (hex.startsWith("0")) fail(CODES.NOT_CANONICAL, "the subaccount must not have leading zeros; they are removed in the canonical text");
|
|
52
|
+
if (hex.length > 64) fail(CODES.LENGTH, `the subaccount is at most 64 hex digits, got ${hex.length}`);
|
|
53
|
+
|
|
54
|
+
const owner = principalFromText(left.slice(0, dash));
|
|
55
|
+
const sub = hexToBytes(hex.padStart(64, "0"));
|
|
56
|
+
if (accountChecksum(owner, sub) !== checksum.toLowerCase()) {
|
|
57
|
+
fail(CODES.CHECKSUM, `the checksum ${checksum} does not match this principal and subaccount (a character was probably mistyped)`);
|
|
58
|
+
}
|
|
59
|
+
return { owner: principalToText(owner), subaccount: sub };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Display an account in the ICRC-1 textual encoding.
|
|
64
|
+
*
|
|
65
|
+
* @param {{ owner: string | Uint8Array, subaccount?: Uint8Array | number[] | null }} account
|
|
66
|
+
* `subaccount` absent, null or 32 zero bytes means the default subaccount
|
|
67
|
+
* @returns {string}
|
|
68
|
+
*/
|
|
69
|
+
export function displayAccount(account) {
|
|
70
|
+
if (account === null || typeof account !== "object") fail(CODES.TYPE, "account must be { owner, subaccount }");
|
|
71
|
+
const owner = ownerBytes(account.owner);
|
|
72
|
+
const ownerText = principalToText(owner);
|
|
73
|
+
if (account.subaccount === undefined || account.subaccount === null) return ownerText;
|
|
74
|
+
const sub = toBytes(account.subaccount, "subaccount");
|
|
75
|
+
if (sub.length !== 32) fail(CODES.LENGTH, `a subaccount is 32 bytes, got ${sub.length}`);
|
|
76
|
+
if (isZero(sub)) return ownerText;
|
|
77
|
+
return `${ownerText}-${accountChecksum(owner, sub)}.${bytesToHex(sub).replace(/^0+/, "")}`;
|
|
78
|
+
}
|
package/src/amount.mjs
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// `amount` (spec §5.3): exact decimal text <-> base-unit integers.
|
|
2
|
+
//
|
|
3
|
+
// Values are decimal strings (D-006). Nothing here uses a JavaScript number for an amount, and
|
|
4
|
+
// nothing rounds: input with more fractional digits than `decimals` is rejected, even when the
|
|
5
|
+
// extra digits are zeros (the literal reading of "more than d fractional digits MUST be rejected").
|
|
6
|
+
|
|
7
|
+
import { CODES, fail } from "./errors.mjs";
|
|
8
|
+
import { UNSAFE_DISPLAY_CHAR, checkRange, intType, requireString, toBigInt } from "./util.mjs";
|
|
9
|
+
|
|
10
|
+
export const AMOUNT_TYPES = ["nat", "int", "nat8", "nat16", "nat32", "nat64", "int8", "int16", "int32", "int64"];
|
|
11
|
+
|
|
12
|
+
// number, then (after whitespace) an optional symbol. "1.", ".5", "1,5", "1e3" and "+1" do not match.
|
|
13
|
+
const AMOUNT_RE = /^(-?)([0-9]+)(?:\.([0-9]+))?(?:\s+(\S(?:.*\S)?))?$/s;
|
|
14
|
+
|
|
15
|
+
/** ASCII-only case folding: "icp" matches "ICP", but a Kelvin sign never matches "k". */
|
|
16
|
+
const asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
17
|
+
|
|
18
|
+
/** @returns {string | undefined} a validated symbol */
|
|
19
|
+
export function checkSymbol(symbol) {
|
|
20
|
+
if (symbol === undefined || symbol === null) return undefined;
|
|
21
|
+
if (typeof symbol !== "string") fail(CODES.ARG, `amount symbol must be a string, got ${typeof symbol}`);
|
|
22
|
+
const n = [...symbol].length;
|
|
23
|
+
if (n < 1 || n > 32) fail(CODES.ARG, `amount symbol must be 1 to 32 characters, got ${n}`);
|
|
24
|
+
if (symbol !== symbol.trim() || UNSAFE_DISPLAY_CHAR.test(symbol) || !symbol.isWellFormed()) {
|
|
25
|
+
fail(CODES.ARG, `amount symbol ${JSON.stringify(symbol)} has surrounding whitespace, control or invisible characters`);
|
|
26
|
+
}
|
|
27
|
+
return symbol;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function checkDecimals(decimals) {
|
|
31
|
+
let d = decimals;
|
|
32
|
+
if (typeof d === "string" && /^(?:0|[1-9][0-9]{0,2})$/.test(d)) d = Number(d);
|
|
33
|
+
if (typeof d === "bigint" && d >= 0n && d <= 255n) d = Number(d);
|
|
34
|
+
if (!Number.isInteger(d) || d < 0 || d > 255) fail(CODES.ARG, `amount decimals must be an integer from 0 to 255, got ${String(decimals)}`);
|
|
35
|
+
return d;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Parse "1.5" or "1.5 ICP" into a base-unit decimal string.
|
|
40
|
+
*
|
|
41
|
+
* @param {string} input
|
|
42
|
+
* @param {{ decimals: number | bigint | string, symbol?: string, candid?: string }} opts
|
|
43
|
+
* @returns {string}
|
|
44
|
+
*/
|
|
45
|
+
export function parseAmount(input, { decimals, symbol, candid = "nat" }) {
|
|
46
|
+
const d = checkDecimals(decimals);
|
|
47
|
+
const expected = checkSymbol(symbol);
|
|
48
|
+
const type = intType(candid, AMOUNT_TYPES, "amount");
|
|
49
|
+
const text = requireString(input, "amount").trim();
|
|
50
|
+
const m = AMOUNT_RE.exec(text);
|
|
51
|
+
if (!m) {
|
|
52
|
+
fail(
|
|
53
|
+
CODES.SYNTAX,
|
|
54
|
+
`cannot read ${JSON.stringify(text)} as an amount: write digits with an optional decimal point, for example "1.5"${expected ? ` or "1.5 ${expected}"` : ""}; no thousands separators, exponents or signs other than "-"`,
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
const [, sign, whole, frac = "", given] = m;
|
|
58
|
+
if (sign && !type.signed) fail(CODES.NEGATIVE, `negative amounts are not allowed here (the Candid type ${candid} is unsigned)`);
|
|
59
|
+
if (given !== undefined) {
|
|
60
|
+
if (expected === undefined) fail(CODES.SYMBOL_MISMATCH, `this amount has no symbol; remove "${given}" and give the number only`);
|
|
61
|
+
if (asciiLower(given) !== asciiLower(expected)) fail(CODES.SYMBOL_MISMATCH, `the symbol "${given}" is not this token's symbol "${expected}"`);
|
|
62
|
+
}
|
|
63
|
+
if (frac.length > d) {
|
|
64
|
+
fail(
|
|
65
|
+
CODES.EXCESS_PRECISION,
|
|
66
|
+
`${JSON.stringify(text)} has ${frac.length} fractional digits but this token has ${d}; amounts are never rounded, so give at most ${d}`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
const magnitude = BigInt(whole) * 10n ** BigInt(d) + BigInt(frac.padEnd(d, "0") || "0");
|
|
70
|
+
const v = sign ? -magnitude : magnitude;
|
|
71
|
+
checkRange(v, type, "amount");
|
|
72
|
+
return v.toString();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Display a base-unit integer as "1.5 ICP": trailing fractional zeros removed, symbol appended.
|
|
77
|
+
*
|
|
78
|
+
* @param {string | bigint} value
|
|
79
|
+
* @param {{ decimals: number | bigint | string, symbol?: string, candid?: string }} opts
|
|
80
|
+
* @returns {string}
|
|
81
|
+
*/
|
|
82
|
+
export function displayAmount(value, { decimals, symbol, candid = "nat" }) {
|
|
83
|
+
const d = checkDecimals(decimals);
|
|
84
|
+
const sym = checkSymbol(symbol);
|
|
85
|
+
const type = intType(candid, AMOUNT_TYPES, "amount");
|
|
86
|
+
const v = toBigInt(value, "amount");
|
|
87
|
+
checkRange(v, type, "amount");
|
|
88
|
+
const digits = (v < 0n ? -v : v).toString().padStart(d + 1, "0");
|
|
89
|
+
const whole = digits.slice(0, digits.length - d);
|
|
90
|
+
const frac = digits.slice(digits.length - d).replace(/0+$/, "");
|
|
91
|
+
return `${v < 0n ? "-" : ""}${whole}${frac ? `.${frac}` : ""}${sym ? ` ${sym}` : ""}`;
|
|
92
|
+
}
|