@meantjs/format 0.0.0-bootstrap → 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/README.md +123 -4
- package/package.json +39 -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/README.md
CHANGED
|
@@ -1,5 +1,124 @@
|
|
|
1
|
-
# @meantjs/format
|
|
1
|
+
# @meantjs/format
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@meantjs/format",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
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
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -9,8 +9,43 @@
|
|
|
9
9
|
"directory": "profile/packages/format"
|
|
10
10
|
},
|
|
11
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
|
+
},
|
|
12
36
|
"files": [
|
|
13
|
-
"
|
|
37
|
+
"src",
|
|
38
|
+
"CHANGELOG.md",
|
|
14
39
|
"LICENSE"
|
|
15
|
-
]
|
|
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
|
+
}
|
|
16
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
|
+
}
|
package/src/bytes.mjs
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// `bytes` (spec §5.3): a blob shown and read as utf8, hex or base64.
|
|
2
|
+
//
|
|
3
|
+
// utf8 input is plain text encoded as UTF-8; input starting with 0x is read as hex.
|
|
4
|
+
// Display is the decoded text when the bytes are valid UTF-8 without control
|
|
5
|
+
// characters, else 0x followed by lowercase hex.
|
|
6
|
+
// hex input and display carry a 0x prefix (the prefix is optional on input).
|
|
7
|
+
// base64 RFC 4648 standard alphabet; padding optional on input, always written on display.
|
|
8
|
+
// max_len counts bytes after encoding.
|
|
9
|
+
//
|
|
10
|
+
// Two display rules go beyond the literal text so that parse(display(x)) = x always holds and so
|
|
11
|
+
// that nothing misleading is shown (both are listed in docs/proposals/w3a-spec-5-3-clarifications.md):
|
|
12
|
+
// - utf8 text that itself starts with 0x/0X is displayed as hex, because as text it would be read back as hex;
|
|
13
|
+
// - besides control characters (Cc), text with format characters (Cf, for example bidirectional
|
|
14
|
+
// overrides, zero-width joiners and the byte order mark) or line and paragraph separators
|
|
15
|
+
// (Zl, Zp) is displayed as hex.
|
|
16
|
+
|
|
17
|
+
import { CODES, fail } from "./errors.mjs";
|
|
18
|
+
import { UNSAFE_DISPLAY_CHAR, bytesToHex, hexToBytes, toBytes } from "./util.mjs";
|
|
19
|
+
|
|
20
|
+
export const BYTES_ENCODINGS = ["utf8", "hex", "base64"];
|
|
21
|
+
|
|
22
|
+
/** Bound on the size of a text input (bounded work, spec §11.6). */
|
|
23
|
+
const MAX_BYTES_INPUT_CHARS = 4 * 1024 * 1024;
|
|
24
|
+
const HEX_PREFIX = /^0[xX]/;
|
|
25
|
+
|
|
26
|
+
const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
27
|
+
const B64_VALUE = (() => {
|
|
28
|
+
const t = new Int8Array(128).fill(-1);
|
|
29
|
+
for (let i = 0; i < 64; i++) t[B64.charCodeAt(i)] = i;
|
|
30
|
+
return t;
|
|
31
|
+
})();
|
|
32
|
+
|
|
33
|
+
function base64Encode(bytes) {
|
|
34
|
+
let out = "";
|
|
35
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
36
|
+
const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
|
|
37
|
+
out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63];
|
|
38
|
+
out += i + 1 < bytes.length ? B64[(n >> 6) & 63] : "=";
|
|
39
|
+
out += i + 2 < bytes.length ? B64[n & 63] : "=";
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Strict: standard alphabet, canonical padding or none, no stray characters, zero spare bits. */
|
|
45
|
+
function base64Decode(text) {
|
|
46
|
+
const m = /^([A-Za-z0-9+/]*)(={0,2})$/.exec(text);
|
|
47
|
+
if (!m) {
|
|
48
|
+
fail(CODES.BASE64, "not base64: use the standard alphabet (A-Z, a-z, 0-9, + and /) with no spaces, line breaks or URL-safe characters");
|
|
49
|
+
}
|
|
50
|
+
const [, body, pad] = m;
|
|
51
|
+
const rem = body.length % 4;
|
|
52
|
+
if (rem === 1) fail(CODES.BASE64, "not base64: the length is impossible (one character too many or too few)");
|
|
53
|
+
if (pad && (rem === 0 || pad.length !== 4 - rem)) fail(CODES.BASE64, "not base64: the '=' padding is wrong");
|
|
54
|
+
const out = new Uint8Array(Math.floor((body.length * 3) / 4));
|
|
55
|
+
let acc = 0;
|
|
56
|
+
let bits = 0;
|
|
57
|
+
let o = 0;
|
|
58
|
+
for (let i = 0; i < body.length; i++) {
|
|
59
|
+
acc = (acc << 6) | B64_VALUE[body.charCodeAt(i)];
|
|
60
|
+
bits += 6;
|
|
61
|
+
if (bits >= 8) {
|
|
62
|
+
out[o++] = (acc >> (bits - 8)) & 255;
|
|
63
|
+
bits -= 8;
|
|
64
|
+
}
|
|
65
|
+
acc &= (1 << bits) - 1;
|
|
66
|
+
}
|
|
67
|
+
if (acc !== 0) fail(CODES.BASE64, "not canonical base64: the unused trailing bits must be zero");
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function parseHex(text, what) {
|
|
72
|
+
const bytes = hexToBytes(text.replace(HEX_PREFIX, ""));
|
|
73
|
+
if (bytes === null) fail(CODES.HEX, `${what} is not hexadecimal: use an even number of digits 0-9 and a-f, for example "0x1a2b" (no spaces)`);
|
|
74
|
+
return bytes;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function checkMaxLen(maxLen) {
|
|
78
|
+
if (maxLen === undefined || maxLen === null) return null;
|
|
79
|
+
let n = maxLen;
|
|
80
|
+
if (typeof n === "bigint" || (typeof n === "string" && /^(?:0|[1-9][0-9]*)$/.test(n))) n = Number(n);
|
|
81
|
+
if (!Number.isSafeInteger(n) || n < 0) fail(CODES.ARG, `max_len must be a non-negative integer, got ${String(maxLen)}`);
|
|
82
|
+
return n;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @param {string} input
|
|
87
|
+
* @param {{ encoding: "utf8"|"hex"|"base64", maxLen?: number }} opts `maxLen` is the tag's max_len, in bytes
|
|
88
|
+
* @returns {Uint8Array}
|
|
89
|
+
*/
|
|
90
|
+
export function parseBytes(input, { encoding, maxLen } = {}) {
|
|
91
|
+
if (!BYTES_ENCODINGS.includes(encoding)) fail(CODES.ARG, `bytes encoding must be one of ${BYTES_ENCODINGS.join(", ")}, got ${JSON.stringify(encoding)}`);
|
|
92
|
+
const max = checkMaxLen(maxLen);
|
|
93
|
+
if (typeof input !== "string") fail(CODES.TYPE, `bytes input must be a string, got ${typeof input}`);
|
|
94
|
+
if (input.length > MAX_BYTES_INPUT_CHARS) fail(CODES.TOO_LONG, `bytes input is longer than ${MAX_BYTES_INPUT_CHARS} characters`);
|
|
95
|
+
let bytes;
|
|
96
|
+
if (encoding === "utf8") {
|
|
97
|
+
if (HEX_PREFIX.test(input)) bytes = parseHex(input, "text starting with 0x (read as hex)");
|
|
98
|
+
else {
|
|
99
|
+
// TextEncoder would replace a lone surrogate with U+FFFD without saying so.
|
|
100
|
+
if (!input.isWellFormed()) fail(CODES.UTF8, "the text contains an unpaired surrogate and cannot be encoded as UTF-8");
|
|
101
|
+
bytes = new TextEncoder().encode(input);
|
|
102
|
+
}
|
|
103
|
+
} else if (encoding === "hex") {
|
|
104
|
+
bytes = parseHex(input, "the value");
|
|
105
|
+
} else {
|
|
106
|
+
bytes = base64Decode(input);
|
|
107
|
+
}
|
|
108
|
+
if (max !== null && bytes.length > max) fail(CODES.MAX_LEN, `the value is ${bytes.length} bytes after encoding but at most ${max} are allowed`);
|
|
109
|
+
return bytes;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {Uint8Array | number[]} value
|
|
114
|
+
* @param {{ encoding: "utf8"|"hex"|"base64" }} opts
|
|
115
|
+
* @returns {string}
|
|
116
|
+
*/
|
|
117
|
+
export function displayBytes(value, { encoding } = {}) {
|
|
118
|
+
if (!BYTES_ENCODINGS.includes(encoding)) fail(CODES.ARG, `bytes encoding must be one of ${BYTES_ENCODINGS.join(", ")}, got ${JSON.stringify(encoding)}`);
|
|
119
|
+
const bytes = toBytes(value, "bytes");
|
|
120
|
+
if (encoding === "hex") return `0x${bytesToHex(bytes)}`;
|
|
121
|
+
if (encoding === "base64") return base64Encode(bytes);
|
|
122
|
+
let text;
|
|
123
|
+
try {
|
|
124
|
+
// ignoreBOM keeps a leading U+FEFF in the string instead of silently dropping its three bytes
|
|
125
|
+
text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
126
|
+
} catch {
|
|
127
|
+
return `0x${bytesToHex(bytes)}`;
|
|
128
|
+
}
|
|
129
|
+
if (UNSAFE_DISPLAY_CHAR.test(text) || HEX_PREFIX.test(text)) return `0x${bytesToHex(bytes)}`;
|
|
130
|
+
return text;
|
|
131
|
+
}
|
package/src/errors.mjs
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Every rejection in this package is a FormatError with a stable `code`.
|
|
2
|
+
// Callers (arm C tool layer, the ICRC-21 generator) switch on `code`; `message` is written for a
|
|
3
|
+
// model or a person and says how to fix the input.
|
|
4
|
+
|
|
5
|
+
export class FormatError extends Error {
|
|
6
|
+
/**
|
|
7
|
+
* @param {string} code one of CODES
|
|
8
|
+
* @param {string} message
|
|
9
|
+
*/
|
|
10
|
+
constructor(code, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "FormatError";
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export const CODES = Object.freeze({
|
|
18
|
+
// shared
|
|
19
|
+
TYPE: "E_TYPE", // wrong JavaScript type for an input, for example a number where a decimal string is required
|
|
20
|
+
SYNTAX: "E_SYNTAX", // the text does not match the grammar
|
|
21
|
+
RANGE: "E_RANGE", // outside the range of the Candid type or of the representable calendar
|
|
22
|
+
TOO_LONG: "E_TOO_LONG", // input longer than the bound on work
|
|
23
|
+
ARG: "E_ARG", // a tag argument is missing or invalid
|
|
24
|
+
TAG_TYPE: "E_TAG_TYPE", // the tag does not apply to this Candid type
|
|
25
|
+
TAG_CONFLICT: "E_TAG_CONFLICT", // two formatting tags at one position
|
|
26
|
+
REF_UNRESOLVED: "E_REF_UNRESOLVED", // a dynamic value was not supplied by the caller
|
|
27
|
+
// amount
|
|
28
|
+
EXCESS_PRECISION: "E_EXCESS_PRECISION", // more fractional digits than decimals (never rounded)
|
|
29
|
+
NEGATIVE: "E_NEGATIVE", // negative input for an unsigned Candid type
|
|
30
|
+
SYMBOL_MISMATCH: "E_SYMBOL_MISMATCH", // the symbol in the input is not the token's symbol
|
|
31
|
+
// time
|
|
32
|
+
INEXACT: "E_INEXACT", // the value cannot be represented exactly in the requested unit
|
|
33
|
+
CALENDAR_UNIT: "E_CALENDAR_UNIT", // years and months have no fixed length
|
|
34
|
+
NEEDS_NOW: "E_NEEDS_NOW", // relative time without a `now`
|
|
35
|
+
// account, subaccount, bytes
|
|
36
|
+
CHECKSUM: "E_CHECKSUM", // checksum does not match
|
|
37
|
+
CHECKSUM_MISSING: "E_CHECKSUM_MISSING",
|
|
38
|
+
NOT_CANONICAL: "E_NOT_CANONICAL", // a valid value written in a non-canonical way
|
|
39
|
+
PRINCIPAL: "E_PRINCIPAL", // invalid principal text
|
|
40
|
+
HEX: "E_HEX",
|
|
41
|
+
BASE64: "E_BASE64",
|
|
42
|
+
UTF8: "E_UTF8", // text that cannot be encoded as UTF-8 (lone surrogate)
|
|
43
|
+
LENGTH: "E_LENGTH", // wrong length in bytes
|
|
44
|
+
MAX_LEN: "E_MAX_LEN", // longer than the tag's max_len
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
export function fail(code, message) {
|
|
48
|
+
throw new FormatError(code, message);
|
|
49
|
+
}
|