@meantjs/reconcile 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 +15 -0
- package/README.md +69 -4
- package/package.json +39 -4
- package/src/index.d.mts +101 -0
- package/src/index.mjs +333 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Changelog: @meantjs/reconcile
|
|
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-reconcile`.
|
|
10
|
+
|
|
11
|
+
- After an unknown outcome, the ICRC-3 block an ICRC-1/2 write leaves (`expectedTransaction`) and whether the blocks
|
|
12
|
+
read since the first send hold it: found, absent, not yet, or unreadable with a lookalike (`matchBlocks`). Every
|
|
13
|
+
rule errs on the safe side: never "absent" while a send may still land.
|
|
14
|
+
- No transport and no Node built-in: runs in browsers.
|
|
15
|
+
- TypeScript declarations.
|
package/README.md
CHANGED
|
@@ -1,5 +1,70 @@
|
|
|
1
|
-
# @meantjs/reconcile
|
|
1
|
+
# @meantjs/reconcile
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
Consumer rule 1 (`docs/profile-v0.md` section 7.3) without a transport: after an unknown outcome, before any new
|
|
4
|
+
attempt, is the original in the ledger's ICRC-3 history? One dependency: `@meantjs/format` (principal
|
|
5
|
+
text to bytes).
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @meantjs/reconcile
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
- **Runs on:** Node 22 or later and browsers: no Node built-in, no `Buffer` (`test/browser-bundle.test.mjs`).
|
|
12
|
+
- **Module format:** ES modules only, with hand-written TypeScript declarations for every entry.
|
|
13
|
+
- **Spec:** [Candid Profile v0](https://github.com/B3Pay/Meant/blob/main/profile/docs/profile-v0.md). **Licence:** Apache-2.0.
|
|
14
|
+
- **Versions:** the five Candid Profile packages (`@meantjs/profile`, `/format`, `/consent`, `/tools`,
|
|
15
|
+
`/reconcile`) release together under one version and pin each other exactly; in 0.x a minor is breaking,
|
|
16
|
+
and so is any change to generated text ([releasing](https://github.com/B3Pay/Meant/blob/main/profile/docs/releasing.md)).
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
import { expectedTransaction, matchBlocks } from "@meantjs/reconcile";
|
|
20
|
+
|
|
21
|
+
const expected = expectedTransaction("icrc1_transfer", arg, callerText, { minting }); // minting: icrc1_minting_account
|
|
22
|
+
// Read the blocks yourself (certified, archives followed): every index from `floor` to `logLength - 1`.
|
|
23
|
+
const r = matchBlocks(blocks, expected, { logLength, floor, inFlight: true, ledgerTime, windowNs }); // windowNs: the ledger's TX_WINDOW + PERMITTED_DRIFT
|
|
24
|
+
r.status; // "found" (r.block) | "absent" (r.closedBy) | "not_yet" (r.openUntil) | "unreadable" (r.reason, r.lookalike?)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
| Input | Shape |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `arg` | the call's argument record as candid-core values: `amount`, `created_at_time`, `fee` bigint; accounts `{ owner: <principal text>, subaccount: Uint8Array \| null }`; `memo` Uint8Array or null |
|
|
30
|
+
| `blocks` | `[{ id: bigint, block }]`, `block` an ICRC-3 value in `{ tag, value }` form (`Map`, `Array`, `Nat`, `Text`, `Blob`) |
|
|
31
|
+
|
|
32
|
+
Rules, all in the safe direction (`src/index.mjs` header):
|
|
33
|
+
|
|
34
|
+
- An absent field is part of the match: an empty memo is not no memo. An optional Nat (`fee`, `expires_at`,
|
|
35
|
+
`expected_allowance`) in another shape equals nothing, not even an absent one.
|
|
36
|
+
- The operation is the block's `btype` when it has one (`1xfer`, `2xfer`, `1mint`, `1burn`, `2approve`; ICRC-3 makes
|
|
37
|
+
it authoritative), else the legacy `tx.op`. An unknown `btype` matches nothing, and a `btype` that is present but
|
|
38
|
+
not Text makes the block unreadable (no fallback to `tx.op`). A transfer also needs the btype its
|
|
39
|
+
method leaves (`1xfer` for `icrc1_transfer`, `2xfer` for `icrc2_transfer_from`) when the block has one.
|
|
40
|
+
- A transfer from the minting account is a `mint`, one to it a `burn` (the same for a `transfer_from` from or to it);
|
|
41
|
+
a spender's own `transfer_from` matches only under a `2xfer` btype, with or without `spender` in the block: ICRC-3 lets an `icrc1_transfer` block carry `tx.spender` too, so a legacy block (no btype) reads the same and is a lookalike. A mint or burn through `transfer_from` with no `spender` in the block stays a lookalike: another spender's call reads the same.
|
|
42
|
+
A block with a `spender` the call does not have is another call.
|
|
43
|
+
- A legacy `xfer` block with neither `btype` nor `spender` is the `icrc1_transfer`'s, by the owner's decision of
|
|
44
|
+
2026-10-19 (#29 review). ICRC-3 would also let another principal's `icrc2_transfer_from` with the caller's exact
|
|
45
|
+
stamp, amount, accounts, fee and memo leave such a block, so the match accepts that case. **Fact:** the pinned
|
|
46
|
+
DFINITY ledger writes no `btype` and records `spender` in every `transfer_from` block (the key set in
|
|
47
|
+
`test/reconcile.test.mjs:1-6`), so there such a block can only be the transfer. Treating it as a lookalike would
|
|
48
|
+
leave every `icrc1_transfer` on that ledger held for a person to review. In the accepted case the funds still moved
|
|
49
|
+
where the call asked, so a `found` cannot pay twice.
|
|
50
|
+
- A call whose subaccount is not bytes maps to no block (`undefined`), so no side is dropped from the match.
|
|
51
|
+
- A block with the call's stamp and amount from the call's account (or from an account it cannot read) in another
|
|
52
|
+
shape is a **lookalike**: `unreadable`
|
|
53
|
+
with that block, never `absent`. An amount above u64::MAX counts as u64::MAX (the DFINITY ledger's u64 build caps
|
|
54
|
+
an approval and writes the capped amount). A block of the same operation naming another recipient or spender is
|
|
55
|
+
another call. `notOriginal` takes blocks the person rejected out of the next read.
|
|
56
|
+
- `absent` only when nothing can still land: every send answered (`answered`), a TooOld (`too_old`), or the
|
|
57
|
+
ledger's clock past stamp + `windowNs` (`window_passed`). `windowNs` is the ledger's own window (spec section 7.3:
|
|
58
|
+
the ledger defines it); without it nothing closes by the clock and the answer is `not_yet` with a `reason`.
|
|
59
|
+
`DEDUP_WINDOW_NS` (24 h 2 min, the DFINITY ledger's default) is exported for a caller that has checked its ledger
|
|
60
|
+
uses it. Otherwise `not_yet`. Without a ledger clock, the later of `ledgerTimeAtLeast` and the tip block's time stands in.
|
|
61
|
+
- Blocks that do not cover `floor..logLength-1`, or a block in that range whose operation or amount (or stamp, when
|
|
62
|
+
it has one) cannot be read, are `unreadable`.
|
|
63
|
+
|
|
64
|
+
Tests: `test/reconcile.test.mjs`, on blocks built in the shapes W2 recorded from the pinned DFINITY ledger wasm
|
|
65
|
+
(`docs/status/W2.md`, 2026-10-09). **Fact:** each rule above has a test that fails when the rule is removed
|
|
66
|
+
(memo lenience, mint mapping, u64 cap, the window, the coverage check, `btype`, the spender rule, unreadable blocks). **Not observed on a real ledger:** a `burn`,
|
|
67
|
+
a spender's own `transfer_from`, a mint through `transfer_from` and a `btype` block; they follow ICRC-1/2/3 as written.
|
|
68
|
+
|
|
69
|
+
Arm C's own matcher (`packages/mcp-adapters/src/arm-c/history.mjs`) does not use this module yet: that is an arm C
|
|
70
|
+
change under D-015, proposed in `docs/proposals/w3b-reconcile-module.md`.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@meantjs/reconcile",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Consumer rule 1 without a transport: the ICRC-3 block an ICRC-1/2 write leaves, and whether the blocks a caller read since its first send hold it (found, absent, not yet, or unreadable with a lookalike). Browser-safe.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -9,8 +9,43 @@
|
|
|
9
9
|
"directory": "profile/packages/reconcile"
|
|
10
10
|
},
|
|
11
11
|
"homepage": "https://github.com/B3Pay/Meant/tree/main/profile/packages/reconcile#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/B3Pay/Meant/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"candid",
|
|
17
|
+
"internet-computer",
|
|
18
|
+
"icp",
|
|
19
|
+
"icrc-3",
|
|
20
|
+
"idempotency",
|
|
21
|
+
"reconcile"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"main": "./src/index.mjs",
|
|
26
|
+
"types": "./src/index.d.mts",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./src/index.d.mts",
|
|
30
|
+
"default": "./src/index.mjs"
|
|
31
|
+
},
|
|
32
|
+
"./package.json": "./package.json"
|
|
33
|
+
},
|
|
12
34
|
"files": [
|
|
13
|
-
"
|
|
35
|
+
"src",
|
|
36
|
+
"CHANGELOG.md",
|
|
14
37
|
"LICENSE"
|
|
15
|
-
]
|
|
38
|
+
],
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=22"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"test": "node --test \"test/*.test.mjs\""
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"@meantjs/format": "0.1.0"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"esbuild": "0.28.2"
|
|
50
|
+
}
|
|
16
51
|
}
|
package/src/index.d.mts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Types for @meantjs/reconcile. Hand-written; the source is src/index.mjs.
|
|
2
|
+
// test/types.test.mjs keeps the declared names equal to the runtime exports, and `npm run types` compiles a consumer
|
|
3
|
+
// against these declarations under strict TypeScript.
|
|
4
|
+
|
|
5
|
+
/** ICRC-1 TX_WINDOW plus PERMITTED_DRIFT of the DFINITY ledger (24 h 2 min, in ns). */
|
|
6
|
+
export const DEDUP_WINDOW_NS: bigint;
|
|
7
|
+
/** u64::MAX: where the DFINITY ledger's u64 build caps an approval above it. */
|
|
8
|
+
export const U64_MAX: bigint;
|
|
9
|
+
/** The methods this module maps to a block. */
|
|
10
|
+
export const METHODS: readonly ["icrc1_transfer", "icrc2_approve", "icrc2_transfer_from"];
|
|
11
|
+
export type ReconciledMethod = (typeof METHODS)[number];
|
|
12
|
+
|
|
13
|
+
/** An account as ICRC-3 compares it: owner bytes and a 64-hex subaccount (all zero for the default). */
|
|
14
|
+
export interface AccountKey {
|
|
15
|
+
owner: string;
|
|
16
|
+
subaccount: string;
|
|
17
|
+
}
|
|
18
|
+
/** An ICRC-1 account in candid-core's domain shape. */
|
|
19
|
+
export interface Account {
|
|
20
|
+
owner: string;
|
|
21
|
+
subaccount?: Uint8Array | null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The ICRC-3 transaction a call leaves in the log, as `expectedTransaction` maps it. */
|
|
25
|
+
export interface ExpectedTransaction {
|
|
26
|
+
op: "xfer" | "mint" | "burn" | "approve";
|
|
27
|
+
/** `1xfer` or `2xfer` for a transfer (ICRC-3 makes `btype` authoritative when a block has one). */
|
|
28
|
+
btype?: "1xfer" | "2xfer";
|
|
29
|
+
ts: bigint;
|
|
30
|
+
amt: bigint;
|
|
31
|
+
/** Hex, or null for no memo (an empty memo is not no memo). */
|
|
32
|
+
memo: string | null;
|
|
33
|
+
fee: bigint | null;
|
|
34
|
+
from?: AccountKey;
|
|
35
|
+
to?: AccountKey;
|
|
36
|
+
spender?: AccountKey;
|
|
37
|
+
/** A mint by `transfer_from` whose spender is the minting account may leave `spender` out. */
|
|
38
|
+
spenderOptional?: true;
|
|
39
|
+
expires_at?: bigint | null;
|
|
40
|
+
expected_allowance?: bigint | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The ICRC-3 transaction a call leaves. `arg` is the call's argument record as candid-core values (`amount` and
|
|
45
|
+
* `created_at_time` bigint, accounts `{ owner: <principal text>, subaccount: Uint8Array | null }`, `memo` Uint8Array
|
|
46
|
+
* or null). Undefined for a method this module does not map, a call without a stamp, or an unreadable caller.
|
|
47
|
+
*
|
|
48
|
+
* @param options.minting the ledger's `icrc1_minting_account`: a transfer from it is a mint, to it a burn
|
|
49
|
+
*/
|
|
50
|
+
export function expectedTransaction(
|
|
51
|
+
method: string,
|
|
52
|
+
arg: Record<string, unknown>,
|
|
53
|
+
caller: string,
|
|
54
|
+
options?: { minting?: Account | null },
|
|
55
|
+
): ExpectedTransaction | undefined;
|
|
56
|
+
|
|
57
|
+
/** An ICRC-3 value in the `{ tag, value }` shape. */
|
|
58
|
+
export type Icrc3Value =
|
|
59
|
+
| { tag: "Map"; value: [string, Icrc3Value][] }
|
|
60
|
+
| { tag: "Array"; value: Icrc3Value[] }
|
|
61
|
+
| { tag: "Nat"; value: bigint }
|
|
62
|
+
| { tag: "Int"; value: bigint }
|
|
63
|
+
| { tag: "Text"; value: string }
|
|
64
|
+
| { tag: "Blob"; value: Uint8Array };
|
|
65
|
+
|
|
66
|
+
/** Whether an ICRC-3 block carries exactly this transaction. */
|
|
67
|
+
export function blockMatches(block: Icrc3Value, expected: ExpectedTransaction | undefined): boolean;
|
|
68
|
+
|
|
69
|
+
export interface MatchOptions {
|
|
70
|
+
/** The log length when the blocks were read (`icrc3_get_blocks` `log_length`). */
|
|
71
|
+
logLength: bigint;
|
|
72
|
+
/** The log length before the first send (default 0). */
|
|
73
|
+
floor?: bigint;
|
|
74
|
+
/** A send of the call had an unknown outcome, so it may still execute until refused. */
|
|
75
|
+
inFlight: boolean;
|
|
76
|
+
/** A send was answered TooOld (sound only for blocks read after that answer). */
|
|
77
|
+
stampExpired?: boolean;
|
|
78
|
+
/** The ledger's clock (ns), where the caller has it. */
|
|
79
|
+
ledgerTime?: bigint;
|
|
80
|
+
/** A time the ledger's clock is at least. */
|
|
81
|
+
ledgerTimeAtLeast?: bigint;
|
|
82
|
+
/** How long after its stamp a call can still execute (`DEDUP_WINDOW_NS` for the DFINITY ledger). */
|
|
83
|
+
windowNs?: bigint;
|
|
84
|
+
/** Blocks the person said are not the original. */
|
|
85
|
+
notOriginal?: bigint[];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type ClockReading = { at: bigint; by: string };
|
|
89
|
+
export type MatchResult =
|
|
90
|
+
| { status: "found"; block: bigint }
|
|
91
|
+
| { status: "absent"; closedBy: "answered" | "too_old" | "window_passed"; clock?: ClockReading }
|
|
92
|
+
| { status: "not_yet"; openUntil?: bigint; reason?: string; clock?: ClockReading }
|
|
93
|
+
| { status: "unreadable"; reason: string; lookalike?: { block: bigint; op: string; capped: boolean } };
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Judge the blocks a caller read since the call's first send: found, absent, not yet, or unreadable (never
|
|
97
|
+
* "absent" while a send may still land or a block in the range could not be read).
|
|
98
|
+
*
|
|
99
|
+
* @param blocks ICRC-3 blocks with their indices, together holding every index from `floor` to `logLength - 1`
|
|
100
|
+
*/
|
|
101
|
+
export function matchBlocks(blocks: { id: bigint; block: Icrc3Value }[], expected: ExpectedTransaction | undefined, options: MatchOptions): MatchResult;
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
// Consumer rule 1 (docs/profile-v0.md section 7.3) without a transport. After an unknown outcome, before any new
|
|
2
|
+
// attempt, look for the original in the ledger's history: the ICRC-3 blocks since the first send, matched on the
|
|
3
|
+
// operation, the stamp, the amount, the fee, the accounts (the caller's included), the memo and, for an approval,
|
|
4
|
+
// its expiry and expected allowance.
|
|
5
|
+
//
|
|
6
|
+
// The caller reads the blocks (certified, and from archives when it needs them) and passes them in; this module
|
|
7
|
+
// only maps a call to the block it leaves and judges the blocks. It imports no Node built-in and needs no codec:
|
|
8
|
+
// arguments are candid-core values (bigint, Uint8Array, principal text) and blocks are ICRC-3 values in the
|
|
9
|
+
// `{ tag, value }` shape (`Map`, `Array`, `Nat`, `Int`, `Text`, `Blob`).
|
|
10
|
+
//
|
|
11
|
+
// Rules, each one in the safe direction:
|
|
12
|
+
// - An absent field is part of the match: an empty memo is not no memo (a ledger keeps an empty memo and
|
|
13
|
+
// deduplicates it apart from none), and a block with a `spender` the call has not is another call.
|
|
14
|
+
// - The operation is the block's `btype` when it has one (ICRC-3 makes it authoritative), else its legacy `tx.op`.
|
|
15
|
+
// - A block in the range whose operation or amount (or stamp, when it has one) cannot be read is `unreadable`,
|
|
16
|
+
// never "no match".
|
|
17
|
+
// - A call whose accounts cannot be read (a subaccount that is not bytes) maps to no block, so it is never
|
|
18
|
+
// matched with a side left out.
|
|
19
|
+
// - A block that carries the call's stamp and amount from the call's account, in a shape the mapping does not know,
|
|
20
|
+
// is a lookalike: the answer is `unreadable` with that block, never `absent`. An amount above u64::MAX counts as
|
|
21
|
+
// u64::MAX here, because the DFINITY ledger's u64 build caps an approval there and writes the capped amount.
|
|
22
|
+
// - A block of the call's own operation that names another recipient or spender is another call, not a lookalike.
|
|
23
|
+
// - No block settles nothing while a send of the call may still land: `absent` only when no send is unknown, a send
|
|
24
|
+
// was answered TooOld, or the ledger's clock is past the stamp's window; otherwise `not_yet`.
|
|
25
|
+
// - Blocks that do not cover every index from the first send to the tip are `unreadable`, never `absent`.
|
|
26
|
+
//
|
|
27
|
+
// Ledger knowledge the profile does not carry yet (no pack says it): the call-to-block mapping per method, the
|
|
28
|
+
// minting account turning a transfer into a mint or a burn, and the window (ICRC-1 TX_WINDOW plus PERMITTED_DRIFT,
|
|
29
|
+
// the DFINITY ledger's 24 hours and 2 minutes). The window is an option.
|
|
30
|
+
import { principalFromText } from "@meantjs/format";
|
|
31
|
+
|
|
32
|
+
/** ICRC-1 TX_WINDOW plus PERMITTED_DRIFT of the DFINITY ledger: how long after its stamp a call can still execute. */
|
|
33
|
+
export const DEDUP_WINDOW_NS = (24n * 60n + 2n) * 60n * 1_000_000_000n;
|
|
34
|
+
/** u64::MAX: where the DFINITY ledger's u64 build caps an approval above it. */
|
|
35
|
+
export const U64_MAX = 2n ** 64n - 1n;
|
|
36
|
+
/** The methods this module maps to a block. */
|
|
37
|
+
export const METHODS = Object.freeze(["icrc1_transfer", "icrc2_approve", "icrc2_transfer_from"]);
|
|
38
|
+
|
|
39
|
+
const ZERO = "0".repeat(64);
|
|
40
|
+
const TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
41
|
+
const typedArrayTag = Object.getOwnPropertyDescriptor(TypedArrayPrototype, Symbol.toStringTag).get;
|
|
42
|
+
const typedArrayValues = TypedArrayPrototype.values;
|
|
43
|
+
/**
|
|
44
|
+
* Whether a view's memory can be read now: not detached, and not out of bounds after its resizable buffer shrank.
|
|
45
|
+
* The intrinsic `values` validates the view the way reading it does (ValidateTypedArray) and throws otherwise.
|
|
46
|
+
*/
|
|
47
|
+
function isReadable(view) {
|
|
48
|
+
try {
|
|
49
|
+
typedArrayValues.call(view);
|
|
50
|
+
return true;
|
|
51
|
+
} catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** A Uint8Array from any realm whose memory can be read (not detached, not out of bounds). */
|
|
56
|
+
const isBytes = (v) => ArrayBuffer.isView(v) && typedArrayTag.call(v) === "Uint8Array" && isReadable(v);
|
|
57
|
+
const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
58
|
+
|
|
59
|
+
/** An account as owner bytes and a 64-hex subaccount (zero for none): how ICRC-3 compares accounts. */
|
|
60
|
+
function keyOf(owner, subaccount) {
|
|
61
|
+
let bytes;
|
|
62
|
+
try {
|
|
63
|
+
bytes = principalFromText(owner);
|
|
64
|
+
} catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
if (subaccount !== null && subaccount !== undefined && !isBytes(subaccount)) return undefined;
|
|
68
|
+
return { owner: hex(bytes), subaccount: subaccount === null || subaccount === undefined ? ZERO : hex(subaccount) };
|
|
69
|
+
}
|
|
70
|
+
const accountKey = (account) => (account === null || account === undefined || typeof account !== "object" ? undefined : keyOf(account.owner, account.subaccount));
|
|
71
|
+
const sameKey = (a, b) => a !== undefined && b !== undefined && a.owner === b.owner && a.subaccount === b.subaccount;
|
|
72
|
+
const natOrNull = (v) => (typeof v === "bigint" ? v : null);
|
|
73
|
+
const present = (key, value) => (value === undefined ? {} : { [key]: value });
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The ICRC-3 transaction a call leaves in the log.
|
|
77
|
+
*
|
|
78
|
+
* @param {string} method `icrc1_transfer`, `icrc2_approve` or `icrc2_transfer_from`
|
|
79
|
+
* @param {Record<string, unknown>} arg the call's argument record as candid-core values (`amount` and
|
|
80
|
+
* `created_at_time` bigint, accounts `{ owner: <principal text>, subaccount: Uint8Array | null }`, `memo`
|
|
81
|
+
* Uint8Array or null)
|
|
82
|
+
* @param {string} caller the caller's principal text
|
|
83
|
+
* @param {{ minting?: { owner: string, subaccount?: Uint8Array | null } | null }} [options] the ledger's
|
|
84
|
+
* `icrc1_minting_account`: a transfer from it is a `mint` (no `from`), one to it a `burn` (no `to`)
|
|
85
|
+
* @returns the expected transaction (a transfer also carries the `btype` it leaves, `1xfer` or `2xfer`), or
|
|
86
|
+
* `undefined` for a method this module does not map, a call without a stamp
|
|
87
|
+
* (nothing makes its block specific) or an unreadable caller
|
|
88
|
+
*/
|
|
89
|
+
export function expectedTransaction(method, arg, caller, { minting = null } = {}) {
|
|
90
|
+
if (arg === null || typeof arg !== "object") return undefined;
|
|
91
|
+
const ts = arg.created_at_time;
|
|
92
|
+
if (typeof ts !== "bigint" || typeof arg.amount !== "bigint") return undefined;
|
|
93
|
+
if (arg.memo !== null && arg.memo !== undefined && !isBytes(arg.memo)) return undefined;
|
|
94
|
+
const callerKey = (sub) => keyOf(caller, sub);
|
|
95
|
+
if (callerKey(null) === undefined) return undefined;
|
|
96
|
+
for (const key of ["from_subaccount", "spender_subaccount"]) if (arg[key] !== null && arg[key] !== undefined && !isBytes(arg[key])) return undefined;
|
|
97
|
+
const common = { ts, amt: arg.amount, memo: isBytes(arg.memo) ? hex(arg.memo) : null, fee: natOrNull(arg.fee) };
|
|
98
|
+
const mint = accountKey(minting);
|
|
99
|
+
switch (method) {
|
|
100
|
+
case "icrc1_transfer": {
|
|
101
|
+
const from = callerKey(arg.from_subaccount);
|
|
102
|
+
const to = accountKey(arg.to);
|
|
103
|
+
if (from === undefined || to === undefined) return undefined;
|
|
104
|
+
if (sameKey(from, mint)) return { ...common, op: "mint", to };
|
|
105
|
+
if (sameKey(to, mint)) return { ...common, op: "burn", from };
|
|
106
|
+
return { ...common, op: "xfer", btype: "1xfer", from, to };
|
|
107
|
+
}
|
|
108
|
+
case "icrc2_approve": {
|
|
109
|
+
const spender = accountKey(arg.spender);
|
|
110
|
+
const from = callerKey(arg.from_subaccount);
|
|
111
|
+
if (spender === undefined || from === undefined) return undefined;
|
|
112
|
+
return {
|
|
113
|
+
...common,
|
|
114
|
+
op: "approve",
|
|
115
|
+
from,
|
|
116
|
+
spender,
|
|
117
|
+
expires_at: natOrNull(arg.expires_at),
|
|
118
|
+
expected_allowance: natOrNull(arg.expected_allowance),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
case "icrc2_transfer_from": {
|
|
122
|
+
const from = accountKey(arg.from);
|
|
123
|
+
const to = accountKey(arg.to);
|
|
124
|
+
if (from === undefined || to === undefined) return undefined;
|
|
125
|
+
const spender = callerKey(arg.spender_subaccount);
|
|
126
|
+
if (spender === undefined) return undefined;
|
|
127
|
+
// From the minting account it is a mint (no `from`), as the reference ledger classes it; to it, a burn (no `to`).
|
|
128
|
+
// A mint block may leave `spender` out; then it cannot tell which spender made the call, so that is optional
|
|
129
|
+
// only when the spender is the minting account itself.
|
|
130
|
+
if (sameKey(from, mint)) return { ...common, op: "mint", to, spender, ...(sameKey(spender, from) ? { spenderOptional: true } : {}) };
|
|
131
|
+
const burning = sameKey(to, mint);
|
|
132
|
+
return {
|
|
133
|
+
...common,
|
|
134
|
+
op: burning ? "burn" : "xfer",
|
|
135
|
+
...(burning ? {} : { btype: "2xfer" }),
|
|
136
|
+
from,
|
|
137
|
+
...present("to", burning ? undefined : to),
|
|
138
|
+
spender,
|
|
139
|
+
// A spender spending its own account: a ledger may leave `spender` out of the block.
|
|
140
|
+
...(sameKey(spender, from) ? { spenderOptional: true } : {}),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
default:
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ---- ICRC-3 values -------------------------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
const get = (value, key) => (value?.tag === "Map" && Array.isArray(value.value) ? value.value.find((e) => Array.isArray(e) && e[0] === key)?.[1] : undefined);
|
|
151
|
+
const natOf = (v) => (v?.tag === "Nat" && typeof v.value === "bigint" ? v.value : undefined);
|
|
152
|
+
/** An optional Nat field: null when absent, its value when a Nat, undefined when present but not a Nat (equal to nothing). */
|
|
153
|
+
const optNat = (map, key) => {
|
|
154
|
+
const v = get(map, key);
|
|
155
|
+
return v === undefined ? null : natOf(v);
|
|
156
|
+
};
|
|
157
|
+
const textOf = (v) => (v?.tag === "Text" && typeof v.value === "string" ? v.value : undefined);
|
|
158
|
+
const blobOf = (v) => (v?.tag === "Blob" && isBytes(v.value) ? v.value : undefined);
|
|
159
|
+
/** ICRC-3 block types (the ICRC-1/2 block schema) as the legacy `tx.op` names. */
|
|
160
|
+
const BTYPES = { "1xfer": "xfer", "2xfer": "xfer", "1mint": "mint", "1burn": "burn", "2approve": "approve" };
|
|
161
|
+
/**
|
|
162
|
+
* A block's operation: its `btype` when it has one (authoritative), else `tx.op`. An unknown btype matches nothing; a
|
|
163
|
+
* `btype` that is present but not Text is unreadable (undefined), never a reason to fall back to `tx.op`.
|
|
164
|
+
*/
|
|
165
|
+
function opOf(block) {
|
|
166
|
+
const raw = get(block, "btype");
|
|
167
|
+
if (raw !== undefined) {
|
|
168
|
+
const btype = textOf(raw);
|
|
169
|
+
if (btype === undefined) return undefined;
|
|
170
|
+
return Object.hasOwn(BTYPES, btype) ? BTYPES[btype] : `btype:${btype}`;
|
|
171
|
+
}
|
|
172
|
+
return textOf(get(get(block, "tx"), "op"));
|
|
173
|
+
}
|
|
174
|
+
/** Whether a block's operation and amount can be read, and its stamp when it has one (a call without one leaves none). */
|
|
175
|
+
function readable(block) {
|
|
176
|
+
const tx = get(block, "tx");
|
|
177
|
+
const ts = get(tx, "ts");
|
|
178
|
+
return opOf(block) !== undefined && natOf(get(tx, "amt")) !== undefined && (ts === undefined || natOf(ts) !== undefined);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** An ICRC-3 account: `Array [Blob owner]` or `Array [Blob owner, Blob subaccount]`. */
|
|
182
|
+
function keyOfValue(v) {
|
|
183
|
+
if (v?.tag !== "Array" || !Array.isArray(v.value) || v.value.length < 1 || v.value.length > 2) return undefined;
|
|
184
|
+
const owner = blobOf(v.value[0]);
|
|
185
|
+
const sub = v.value.length === 2 ? blobOf(v.value[1]) : undefined;
|
|
186
|
+
if (owner === undefined || (v.value.length === 2 && sub === undefined)) return undefined;
|
|
187
|
+
return { owner: hex(owner), subaccount: sub === undefined ? ZERO : hex(sub) };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Whether an ICRC-3 block carries exactly this transaction. */
|
|
191
|
+
export function blockMatches(block, expected) {
|
|
192
|
+
const tx = get(block, "tx");
|
|
193
|
+
if (tx === undefined || expected === undefined) return false;
|
|
194
|
+
if (opOf(block) !== expected.op) return false;
|
|
195
|
+
// `1xfer` and `2xfer` both read as `xfer`, but the btype tells an icrc1_transfer from an icrc2_transfer_from.
|
|
196
|
+
const btype = textOf(get(block, "btype"));
|
|
197
|
+
if (btype !== undefined && expected.btype !== undefined && btype !== expected.btype) return false;
|
|
198
|
+
// A spender's own transfer_from moves the same funds as an icrc1_transfer from that account, and ICRC-3 lets either
|
|
199
|
+
// block carry `tx.spender` ("it CAN contain"), so only a `2xfer` btype tells them apart; a legacy block is a lookalike.
|
|
200
|
+
if (expected.op === "xfer" && expected.spenderOptional === true && btype !== "2xfer") return false;
|
|
201
|
+
if (natOf(get(tx, "ts")) !== expected.ts) return false;
|
|
202
|
+
if (natOf(get(tx, "amt")) !== expected.amt) return false;
|
|
203
|
+
if (optNat(tx, "fee") !== expected.fee) return false;
|
|
204
|
+
const memo = get(tx, "memo");
|
|
205
|
+
if (memo !== undefined && blobOf(memo) === undefined) return false;
|
|
206
|
+
if ((memo === undefined ? null : hex(blobOf(memo))) !== expected.memo) return false;
|
|
207
|
+
for (const side of ["from", "to", "spender"]) {
|
|
208
|
+
const want = expected[side];
|
|
209
|
+
const have = get(tx, side);
|
|
210
|
+
// Without `spender`, only a `2xfer` btype tells a spender's own transfer_from from an icrc1_transfer (or a mint or
|
|
211
|
+
// burn) with the same fields; a mint or burn stays a lookalike.
|
|
212
|
+
if (side === "spender" && expected.spenderOptional === true && have === undefined && btype === "2xfer") continue;
|
|
213
|
+
if (want === undefined) {
|
|
214
|
+
if (have !== undefined) return false;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (!sameKey(keyOfValue(have), want)) return false;
|
|
218
|
+
}
|
|
219
|
+
if (expected.op === "approve") {
|
|
220
|
+
if (optNat(tx, "expires_at") !== (expected.expires_at ?? null)) return false;
|
|
221
|
+
if (optNat(tx, "expected_allowance") !== (expected.expected_allowance ?? null)) return false;
|
|
222
|
+
}
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* A block with the call's stamp and amount from the call's account (or from none), whatever else it says: it may
|
|
228
|
+
* be the original in a shape the mapping does not know. An amount above u64::MAX counts as u64::MAX too.
|
|
229
|
+
*/
|
|
230
|
+
function looksLikeIt(block, expected) {
|
|
231
|
+
const tx = get(block, "tx");
|
|
232
|
+
const amt = natOf(get(tx, "amt"));
|
|
233
|
+
const sameAmount = amt === expected.amt || (expected.amt > U64_MAX && amt === U64_MAX);
|
|
234
|
+
if (natOf(get(tx, "ts")) !== expected.ts || !sameAmount) return false;
|
|
235
|
+
// only a source that reads as another account rules the block out; one in a shape this cannot read may be the call's
|
|
236
|
+
const from = keyOfValue(get(tx, "from"));
|
|
237
|
+
if (from !== undefined && expected.from !== undefined && !sameKey(from, expected.from)) return false;
|
|
238
|
+
return !namesAnother(block, tx, expected);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** A block of the call's own operation that names another recipient or spender than the call: another call. */
|
|
242
|
+
function namesAnother(block, tx, expected) {
|
|
243
|
+
if (opOf(block) !== expected.op) return false;
|
|
244
|
+
// `1xfer` and `2xfer` both read as `xfer`, but the btype tells an icrc1_transfer from an icrc2_transfer_from.
|
|
245
|
+
const btype = textOf(get(block, "btype"));
|
|
246
|
+
if (btype !== undefined && expected.btype !== undefined && btype !== expected.btype) return false;
|
|
247
|
+
// A spender's own transfer_from moves the same funds as an icrc1_transfer from that account, and ICRC-3 lets either
|
|
248
|
+
// block carry `tx.spender` ("it CAN contain"), so only a `2xfer` btype tells them apart; a legacy block is a lookalike.
|
|
249
|
+
if (expected.op === "xfer" && expected.spenderOptional === true && btype !== "2xfer") return false;
|
|
250
|
+
return ["to", "spender"].some((side) => {
|
|
251
|
+
const want = expected[side];
|
|
252
|
+
const have = keyOfValue(get(tx, side));
|
|
253
|
+
return want !== undefined && have !== undefined && !sameKey(have, want);
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Judge the blocks a caller read since the call's first send.
|
|
259
|
+
*
|
|
260
|
+
* @param {{ id: bigint, block: object }[]} blocks ICRC-3 blocks with their indices, in any order; together they
|
|
261
|
+
* must hold every index from `floor` to `logLength - 1`
|
|
262
|
+
* @param expected from {@link expectedTransaction}
|
|
263
|
+
* @param {object} o
|
|
264
|
+
* @param {bigint} o.logLength the log length when the blocks were read (`icrc3_get_blocks` `log_length`)
|
|
265
|
+
* @param {bigint} [o.floor] the log length before the first send: the original is at this index or later (default 0)
|
|
266
|
+
* @param {boolean} o.inFlight a send of the call had an unknown outcome, so it may still execute until refused
|
|
267
|
+
* @param {boolean} [o.stampExpired] a send was answered TooOld: the ledger refuses the stamp from then on. Sound
|
|
268
|
+
* only when `blocks` were read after that answer arrived: a block written before it is in them then.
|
|
269
|
+
* @param {bigint} [o.ledgerTime] the ledger's clock (ns), where the caller has it; otherwise the later of
|
|
270
|
+
* `ledgerTimeAtLeast` and the tip block's time stands in (both lower bounds on a clock that only moves forward)
|
|
271
|
+
* @param {bigint} [o.ledgerTimeAtLeast] a time the ledger's clock is at least (this machine's clock less the
|
|
272
|
+
* permitted drift, for a ledger that took this machine's stamps)
|
|
273
|
+
* @param {bigint} [o.windowNs] how long after its stamp a call can still execute: the ledger's TX_WINDOW plus
|
|
274
|
+
* PERMITTED_DRIFT ({@link DEDUP_WINDOW_NS} for the DFINITY ledger's defaults). Without it an in-flight call
|
|
275
|
+
* stays `not_yet`: nothing closes by the clock.
|
|
276
|
+
* @param {bigint[]} [o.notOriginal] blocks the person said are not the original: never a lookalike again
|
|
277
|
+
* @returns {{ status: "found", block: bigint }
|
|
278
|
+
* | { status: "absent", closedBy: "answered" | "too_old" | "window_passed", clock?: { at: bigint, by: string } }
|
|
279
|
+
* | { status: "not_yet", openUntil?: bigint, reason?: string, clock?: { at: bigint, by: string } }
|
|
280
|
+
* | { status: "unreadable", reason: string, lookalike?: { block: bigint, op: string, capped: boolean } }}
|
|
281
|
+
*/
|
|
282
|
+
export function matchBlocks(blocks, expected, o) {
|
|
283
|
+
if (expected === undefined) return { status: "unreadable", reason: "no rule maps this call to a block (no stamp, or an unknown method)" };
|
|
284
|
+
if (typeof o?.logLength !== "bigint") throw new TypeError("matchBlocks: logLength (bigint) is required");
|
|
285
|
+
if (typeof o.inFlight !== "boolean") throw new TypeError("matchBlocks: inFlight (boolean) is required");
|
|
286
|
+
const floor = o.floor ?? 0n;
|
|
287
|
+
if (floor > o.logLength) return { status: "unreadable", reason: `the log has ${o.logLength} blocks, fewer than the ${floor} it had before the first send` };
|
|
288
|
+
|
|
289
|
+
const byId = new Map();
|
|
290
|
+
for (const b of blocks) if (typeof b?.id === "bigint") byId.set(b.id, b.block);
|
|
291
|
+
for (let id = floor; id < o.logLength; id++) {
|
|
292
|
+
if (!byId.has(id)) return { status: "unreadable", reason: `block ${id} since the first send was not read (an archive, or a short page)` };
|
|
293
|
+
}
|
|
294
|
+
// An exact original wins over blocks this module cannot read: another standard's blocks share the log (ICRC-3).
|
|
295
|
+
for (let id = o.logLength - 1n; id >= floor; id--) if (blockMatches(byId.get(id), expected)) return { status: "found", block: id };
|
|
296
|
+
for (let id = floor; id < o.logLength; id++) {
|
|
297
|
+
if (!readable(byId.get(id))) return { status: "unreadable", reason: `block ${id} has no operation or amount this module can read, or a stamp that is not a Nat` };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
let lookalike;
|
|
301
|
+
for (let id = o.logLength - 1n; id >= floor; id--) {
|
|
302
|
+
const block = byId.get(id);
|
|
303
|
+
if (lookalike === undefined && !(o.notOriginal ?? []).includes(id) && looksLikeIt(block, expected)) {
|
|
304
|
+
const tx = get(block, "tx");
|
|
305
|
+
lookalike = { block: id, op: opOf(block) ?? "?", capped: natOf(get(tx, "amt")) !== expected.amt };
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
if (lookalike !== undefined) {
|
|
309
|
+
return {
|
|
310
|
+
status: "unreadable",
|
|
311
|
+
reason: lookalike.capped
|
|
312
|
+
? `block ${lookalike.block} (op ${lookalike.op}) carries this call's stamp from its account with the amount capped at u64::MAX: it may be the original`
|
|
313
|
+
: `block ${lookalike.block} (op ${lookalike.op}) carries this call's stamp and amount from its account in another shape: it may be the original`,
|
|
314
|
+
lookalike,
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (!o.inFlight) return { status: "absent", closedBy: "answered" };
|
|
319
|
+
if (o.stampExpired === true) return { status: "absent", closedBy: "too_old" };
|
|
320
|
+
let clock;
|
|
321
|
+
if (typeof o.ledgerTime === "bigint") clock = { at: o.ledgerTime, by: "ledger" };
|
|
322
|
+
else {
|
|
323
|
+
const tipTime = o.logLength > 0n ? natOf(get(byId.get(o.logLength - 1n), "ts")) : undefined;
|
|
324
|
+
const host = typeof o.ledgerTimeAtLeast === "bigint" ? o.ledgerTimeAtLeast : undefined;
|
|
325
|
+
if (host !== undefined && (tipTime === undefined || host >= tipTime)) clock = { at: host, by: "host" };
|
|
326
|
+
else if (tipTime !== undefined) clock = { at: tipTime, by: "block" };
|
|
327
|
+
}
|
|
328
|
+
// The window is the ledger's (TX_WINDOW plus PERMITTED_DRIFT, spec 4.3): without it nothing closes by the clock.
|
|
329
|
+
if (typeof o.windowNs !== "bigint") return { status: "not_yet", reason: "no windowNs: the ledger's deduplication window is not known, so a send may still land", ...present("clock", clock) };
|
|
330
|
+
const openUntil = expected.ts + o.windowNs;
|
|
331
|
+
if (clock !== undefined && clock.at > openUntil) return { status: "absent", closedBy: "window_passed", clock };
|
|
332
|
+
return { status: "not_yet", openUntil, ...present("clock", clock) };
|
|
333
|
+
}
|