@integraledger/lcp-binding-canton-x402 0.9.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/src/adapter.ts ADDED
@@ -0,0 +1,265 @@
1
+ /**
2
+ * The Canton adapter — thin I/O over an injected participant-reader port. It is a **Canton-native
3
+ * surface**, NOT binding-core's `WeldAdapter`: that port is EVM-shaped (`SettlementRef` is a `0x`-hex tx
4
+ * hash, `ChainReader` speaks `eth_getLogs`), whereas a Canton settlement is a ledger update read via the
5
+ * Daml JSON Ledger API over HTTP.
6
+ *
7
+ * **THE CARRIER.** x402's `exact` scheme for Canton: the seller advertises `PaymentRequirements.extra.memo`,
8
+ * the payer MUST echo it into the transfer's metadata under `x402.memo`, and the facilitator MUST reject
9
+ * `invalid_exact_canton_memo_mismatch` if the two disagree. One transaction settles each payment (scheme
10
+ * §Protocol Flow): the payer signs a `TransferFactory_Transfer` naming the merchant as receiver and does
11
+ * NOT submit it; the facilitator relays the signed submission and pays the traffic fee; the merchant's
12
+ * standing `TransferPreapproval` resolves it `direct`.
13
+ *
14
+ * So the weld, the value and the settlement are one on-ledger event, and `recover` reads all three off a
15
+ * single update. The `LcpAnchor` overlay this replaced pointed at a SEPARATE contract — which is exactly
16
+ * why it could bind no asset: the thing it referenced was not the thing that moved the money.
17
+ *
18
+ * `recover` refuses rather than throwing: an update under audit may be any transaction on the party's
19
+ * stream, and "this is not an LCP settlement" is an answer, not an error. `propose` throws, because a
20
+ * seller advertising a malformed memo is a wiring defect and the facilitator would reject the payment.
21
+ */
22
+ import type { BindingManifest, Outcome } from "@integraledger/lcp-binding-core";
23
+ import { atrHashEquals, isAtrHash } from "@integraledger/lcp-kernel";
24
+ import { readTransferMemoAtrHash, x402MemoRequirement } from "./memo.js";
25
+
26
+ /**
27
+ * A Canton settlement reference — the ledger update id of the transfer the facilitator relayed.
28
+ *
29
+ * One id, because one transaction settles each payment.
30
+ */
31
+ export interface CantonX402SettlementRef {
32
+ updateId: string;
33
+ }
34
+
35
+ /**
36
+ * A settled `TransferFactory_Transfer` as one participant sees it.
37
+ *
38
+ * The asset fields are carried rather than decoded and discarded, and that is what lets the manifest
39
+ * declare `assetBinding: "carried"` honestly: the axis asks whether a CONSUMER can reach the asset the
40
+ * weld is attached to, not merely whether the chain recorded it.
41
+ */
42
+ export interface CantonX402TransferView {
43
+ /** The transfer's on-ledger metadata map. The memo rides `x402.memo` (scheme safety check 12). */
44
+ meta: Readonly<Record<string, string>>;
45
+ /** Receiving party id — the merchant's `payTo` in the scheme's `PaymentRequirements`. */
46
+ receiver: string;
47
+ /** Atomic units as an integer string (1 CC = 1e10 units), exactly as the ledger records it. */
48
+ amount: string;
49
+ /** The Canton Coin instrument identifier `{ admin, id }`. */
50
+ instrumentId: { admin: string; id: string };
51
+ }
52
+
53
+ /** What a settled LCP transfer yields: the weld, and the asset it is welded to. */
54
+ export interface CantonX402Settlement {
55
+ state: "settled";
56
+ atrHash: `0x${string}`;
57
+ receiver: string;
58
+ amount: string;
59
+ instrumentId: { admin: string; id: string };
60
+ }
61
+
62
+ /**
63
+ * Reads the participant's update stream over the Daml JSON Ledger API. Injected so the adapter is pure
64
+ * and testable; a live implementation wraps a participant URL and a party bearer JWT.
65
+ */
66
+ export interface CantonX402Reader {
67
+ /** One settled transfer by ledger update id, or `null` if the participant has no such update. */
68
+ transferView(updateId: string): Promise<CantonX402TransferView | null>;
69
+ /** Update ids of transfers visible to `party`, most recent first. A participant view, not an index. */
70
+ transfersFor(party: string, limit?: number): Promise<string[]>;
71
+ }
72
+
73
+ /** The Canton x402 rail's surface. `propose` returns an `extra` fragment for the SELLER to merge into its
74
+ * `PaymentRequirements` — this rail's weld is committed by the seller and echoed by the payer, unlike the
75
+ * memo rails where the payer chooses the value. Its reach is exactly x402's `exact` Canton scheme, which
76
+ * settles Canton Coin only; anything else on Canton needs `@integraledger/lcp-binding-canton`'s overlay. */
77
+ export interface CantonX402Adapter {
78
+ manifest: BindingManifest;
79
+ /**
80
+ * The `extra` fragment the seller merges into its x402 `PaymentRequirements`, committing it to the memo
81
+ * the payer must echo. Throws on a malformed atrHash.
82
+ */
83
+ propose(atrHash: string): { readonly memo: string };
84
+ /** Recover the atrHash from a settled transfer, or a `verification-failure` Refusal if none binds. */
85
+ recover(
86
+ ref: CantonX402SettlementRef,
87
+ reader: CantonX402Reader,
88
+ ): Promise<Outcome<`0x${string}`>>;
89
+ /** Report the `settled` transition, with the asset the weld is attached to. */
90
+ observe(
91
+ ref: CantonX402SettlementRef,
92
+ reader: CantonX402Reader,
93
+ ): Promise<Outcome<CantonX402Settlement>>;
94
+ /** Scan one party's visible transfers for `atrHash` — a participant view, never a global index. */
95
+ enumerate(
96
+ atrHash: string,
97
+ party: string,
98
+ reader: CantonX402Reader,
99
+ limit?: number,
100
+ ): Promise<CantonX402SettlementRef[]>;
101
+ }
102
+
103
+ /** Config for a live Daml JSON Ledger API participant reader. */
104
+ export interface CantonX402ReaderConfig {
105
+ /** JSON Ledger API base URL — e.g. `https://164.92.95.184.nip.io`. */
106
+ jsonLedgerUrl: string;
107
+ /** Bearer JWT authenticating the reading party on the participant. */
108
+ bearerJwt: string;
109
+ }
110
+
111
+ /**
112
+ * A live `CantonX402Reader` over the Daml JSON Ledger API, PURE `fetch` — no Daml SDK.
113
+ *
114
+ * Fails LOUD on a non-2xx response or a Daml `errors[]` envelope; an absent update surfaces as `null`,
115
+ * because a reference the participant cannot see is a value the caller must classify, not a transport
116
+ * failure. No package id is required — the memo rides the CIP-56 token-standard transfer, so unlike the
117
+ * overlay this replaced there is no deployment-specific DAR to deploy or configure.
118
+ */
119
+ export function makeCantonX402Reader(
120
+ cfg: CantonX402ReaderConfig,
121
+ ): CantonX402Reader {
122
+ if (cfg.jsonLedgerUrl.length === 0)
123
+ throw new Error("makeCantonX402Reader: jsonLedgerUrl is empty");
124
+ if (cfg.bearerJwt.length === 0)
125
+ throw new Error("makeCantonX402Reader: bearerJwt is empty");
126
+
127
+ async function ledgerCall<T>(path: string, body: unknown): Promise<T> {
128
+ const res = await fetch(`${cfg.jsonLedgerUrl}${path}`, {
129
+ method: "POST",
130
+ headers: {
131
+ "content-type": "application/json",
132
+ authorization: `Bearer ${cfg.bearerJwt}`,
133
+ },
134
+ body: JSON.stringify(body),
135
+ });
136
+ if (!res.ok) {
137
+ const text = await res.text().catch(() => "");
138
+ throw new Error(`Daml ${path} HTTP ${res.status}: ${text}`);
139
+ }
140
+ const envelope = (await res.json()) as { result?: T; errors?: string[] };
141
+ if (envelope.errors !== undefined && envelope.errors.length > 0)
142
+ throw new Error(`Daml ${path} errors: ${envelope.errors.join("; ")}`);
143
+ if (envelope.result === undefined)
144
+ throw new Error(`Daml ${path} returned no result`);
145
+ return envelope.result;
146
+ }
147
+
148
+ return {
149
+ async transferView(
150
+ updateId: string,
151
+ ): Promise<CantonX402TransferView | null> {
152
+ const result = await ledgerCall<CantonX402TransferView | null>(
153
+ "/v1/updates/transfer",
154
+ { updateId },
155
+ );
156
+ return result ?? null;
157
+ },
158
+ async transfersFor(party: string, limit?: number): Promise<string[]> {
159
+ return ledgerCall<string[]>("/v1/updates/transfers", {
160
+ party,
161
+ ...(limit !== undefined ? { limit } : {}),
162
+ });
163
+ },
164
+ };
165
+ }
166
+
167
+ /** Construct the Canton x402 adapter. **The manifest is injected, not baked in** — pass this package's own
168
+ * `CANTON_X402_MANIFEST`; a manifest whose `rail` is not `"canton:x402"` throws, because an adapter over
169
+ * another rail's manifest would publish that rail's claims as its own. Nothing has to be deployed first:
170
+ * the memo rides the token-standard transfer, so there is no DAR here. This is the package's entry point. */
171
+ export function createCantonX402Adapter(
172
+ manifest: BindingManifest,
173
+ ): CantonX402Adapter {
174
+ // Fail-fast: an adapter constructed over another rail's manifest would report that rail's claims as
175
+ // this one's. The EVM adapters bake their module const in; the injectable factories refuse instead.
176
+ // Stryker disable next-line all: the guard runs during test-module load (the repository's
177
+ // test suite constructs the adapter at describe scope), so its mutants are 'static' — outside the vitest
178
+ // runner's per-test attribution and unkillable by any test that in fact kills them behaviorally
179
+ // (each rail pins both arms: valid manifest constructs, wrong rail throws by message).
180
+ if (manifest.rail !== "canton:x402")
181
+ throw new Error(
182
+ `createCantonX402Adapter: manifest.rail "${manifest.rail}" is not "canton:x402"`,
183
+ );
184
+
185
+ // Closure helper (not `this`) so the returned methods stay destructure-safe.
186
+ async function readSettlement(
187
+ ref: CantonX402SettlementRef,
188
+ reader: CantonX402Reader,
189
+ ): Promise<Outcome<CantonX402Settlement>> {
190
+ const view = await reader.transferView(ref.updateId);
191
+ if (view === null)
192
+ return {
193
+ refused: true,
194
+ haltClass: "verification-failure",
195
+ code: "canton/no-such-update",
196
+ detail: `the participant has no transfer at updateId ${ref.updateId}`,
197
+ };
198
+ const atrHash = readTransferMemoAtrHash(view.meta);
199
+ if (atrHash === null)
200
+ return {
201
+ refused: true,
202
+ haltClass: "verification-failure",
203
+ code: "canton/no-lcp-memo",
204
+ detail: `the transfer at updateId ${ref.updateId} carries no well-formed atrHash under x402.memo`,
205
+ };
206
+ return {
207
+ ok: true,
208
+ value: {
209
+ state: "settled",
210
+ atrHash,
211
+ receiver: view.receiver,
212
+ amount: view.amount,
213
+ instrumentId: view.instrumentId,
214
+ },
215
+ };
216
+ }
217
+
218
+ return {
219
+ manifest,
220
+
221
+ propose(atrHash: string): { readonly memo: string } {
222
+ return x402MemoRequirement(atrHash);
223
+ },
224
+
225
+ async recover(
226
+ ref: CantonX402SettlementRef,
227
+ reader: CantonX402Reader,
228
+ ): Promise<Outcome<`0x${string}`>> {
229
+ const settlement = await readSettlement(ref, reader);
230
+ return "refused" in settlement
231
+ ? settlement
232
+ : { ok: true, value: settlement.value.atrHash };
233
+ },
234
+
235
+ observe(
236
+ ref: CantonX402SettlementRef,
237
+ reader: CantonX402Reader,
238
+ ): Promise<Outcome<CantonX402Settlement>> {
239
+ return readSettlement(ref, reader);
240
+ },
241
+
242
+ async enumerate(
243
+ atrHash: string,
244
+ party: string,
245
+ reader: CantonX402Reader,
246
+ limit?: number,
247
+ ): Promise<CantonX402SettlementRef[]> {
248
+ // Fail-fast, like propose: a malformed atrHash can never match a decoded memo, and the silent []
249
+ // it would produce is indistinguishable from "this party has no settlements".
250
+ if (!isAtrHash(atrHash))
251
+ throw new Error(
252
+ `enumerate: atrHash must be a 0x-prefixed 32-byte value, got "${atrHash}"`,
253
+ );
254
+ const updateIds = await reader.transfersFor(party, limit);
255
+ const out: CantonX402SettlementRef[] = [];
256
+ for (const updateId of updateIds) {
257
+ const view = await reader.transferView(updateId);
258
+ const found = view === null ? null : readTransferMemoAtrHash(view.meta);
259
+ if (found !== null && atrHashEquals(found, atrHash))
260
+ out.push({ updateId });
261
+ }
262
+ return out;
263
+ },
264
+ };
265
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Canton / Daml constants for the LCP transfer-memo binding.
3
+ *
4
+ * **Canton has a native arbitrary-bytes carrier, and this binding uses it.** x402's `exact` scheme for
5
+ * Canton defines `PaymentRequirements.extra.memo` — "Seller-defined UTF-8 string, max 256 bytes. When
6
+ * present, the client MUST include it in the transfer's metadata" — and its facilitator rule 12 rejects
7
+ * `invalid_exact_canton_memo_mismatch` when the transfer metadata does not carry the identical value under
8
+ * `x402.memo`. Seller-committed, payer-echoed, facilitator-verified, and riding the same transaction as
9
+ * the value.
10
+ *
11
+ * Daml is often said to have no native arbitrary-bytes carrier — no memo, no metadata label, no nonce. That
12
+ * is true of the LEDGER's own primitives and false of a payment settled through x402, which is why this
13
+ * rail exists beside `@integraledger/lcp-binding-canton`'s overlay contract rather than instead of it.
14
+ */
15
+
16
+ /**
17
+ * The transfer-metadata key the facilitator compares against `extra.memo`. The host's, read exactly: a
18
+ * metadata map carrying our value under a different key is a transfer no facilitator checked.
19
+ */
20
+ export const CANTON_X402_MEMO_KEY = "x402.memo";
21
+
22
+ /** The scheme's stated ceiling for `extra.memo`. A canonical atrHash is 66 UTF-8 bytes. */
23
+ export const CANTON_X402_MEMO_MAX_BYTES = 256;
24
+
25
+ /** The three Canton environments this binding ships constants for. */
26
+ export type CantonX402Network = "sandbox" | "devnet" | "mainnet";
27
+
28
+ /** Per-network constants. Same shape as the overlay rail's and for the same reason: a Canton participant
29
+ * node is a deployment's own, so there is no endpoint to pin here. */
30
+ export interface CantonX402NetworkConfig {
31
+ network: CantonX402Network;
32
+ /** Explorer base for a contract link (Daml Sandbox has no public explorer — Navigator stand-in). */
33
+ explorerBase: string;
34
+ /** CAIP-2-style identifier — Canton has no canonical namespace yet (informal, like Cardano's). */
35
+ caip2: string;
36
+ }
37
+
38
+ const SANDBOX: CantonX402NetworkConfig = {
39
+ network: "sandbox",
40
+ explorerBase: "http://localhost:7500",
41
+ caip2: "canton:sandbox",
42
+ };
43
+
44
+ const DEVNET: CantonX402NetworkConfig = {
45
+ network: "devnet",
46
+ explorerBase: "https://scan.global.dev.sync.global",
47
+ caip2: "canton:devnet",
48
+ };
49
+
50
+ const MAINNET: CantonX402NetworkConfig = {
51
+ network: "mainnet",
52
+ explorerBase: "https://scan.sync.global",
53
+ caip2: "canton:mainnet",
54
+ };
55
+
56
+ /** The constants for one environment. Which Canton rail you want is the real choice: this one only reaches
57
+ * payments settled through x402's Canton-Coin scheme, and `@integraledger/lcp-binding-canton`'s overlay
58
+ * covers everything else. */
59
+ export function getCantonX402Config(
60
+ network: CantonX402Network,
61
+ ): CantonX402NetworkConfig {
62
+ if (network === "sandbox") return SANDBOX;
63
+ if (network === "devnet") return DEVNET;
64
+ return MAINNET;
65
+ }
package/src/index.ts ADDED
@@ -0,0 +1,24 @@
1
+ export {
2
+ type CantonX402Adapter,
3
+ type CantonX402Reader,
4
+ type CantonX402ReaderConfig,
5
+ type CantonX402Settlement,
6
+ type CantonX402SettlementRef,
7
+ type CantonX402TransferView,
8
+ createCantonX402Adapter,
9
+ makeCantonX402Reader,
10
+ } from "./adapter.js";
11
+ export {
12
+ CANTON_X402_MEMO_KEY,
13
+ CANTON_X402_MEMO_MAX_BYTES,
14
+ type CantonX402Network,
15
+ type CantonX402NetworkConfig,
16
+ getCantonX402Config,
17
+ } from "./constants.js";
18
+ export { CANTON_X402_MANIFEST } from "./manifest.js";
19
+ export {
20
+ decodeTransferMemo,
21
+ encodeTransferMemo,
22
+ readTransferMemoAtrHash,
23
+ x402MemoRequirement,
24
+ } from "./memo.js";
@@ -0,0 +1,82 @@
1
+ import type { BindingManifest } from "@integraledger/lcp-binding-core";
2
+ import { CANTON_X402_MEMO_KEY } from "./constants.js";
3
+
4
+ /**
5
+ * The Canton transfer-memo binding manifest.
6
+ *
7
+ * **pattern = "native-field"** (canonical LCP §8.3.1). x402's `exact` scheme for Canton defines
8
+ * `PaymentRequirements.extra.memo` — "Seller-defined UTF-8 string, max 256 bytes. When present, the
9
+ * client MUST include it in the transfer's metadata" — and its facilitator safety check 12 rejects
10
+ * `invalid_exact_canton_memo_mismatch` unless the transfer metadata carries the identical value under
11
+ * `x402.memo`. The atrHash therefore rides a field the host defined, on the transaction that moves the
12
+ * money.
13
+ *
14
+ * **THIS IS A SECOND CANTON RAIL, NOT A REPLACEMENT.** `@integraledger/lcp-binding-canton` binds the same
15
+ * chain through an `LcpAnchor` overlay contract, and it is not obsolete: x402's exact-Canton scheme
16
+ * settles **Canton Coin only** ("`asset`: `\"CC\"`. Settles Canton Coin only", instrument fixed to
17
+ * `Amulet`, via `transfer-factory`, relayed by a facilitator). Every other Canton deployment — any
18
+ * instrument, any synchronizer, DvP and fund and bond workflows, no facilitator — still has no native
19
+ * field to ride, and the overlay is the only carrier there.
20
+ *
21
+ * Where BOTH apply, this one wins on every axis: the weld rides the SAME transaction as the payment
22
+ * rather than a separate contract create; it is enforced by the facilitator rather than by nobody; and it
23
+ * binds the asset rather than declaring `assetBinding: "none"`. That is LCP §8.3's own ordering, and it is
24
+ * why the overlay's docblock now says it is an overlay by CHOICE rather than by necessity — the claim that
25
+ * Daml has no native arbitrary-bytes carrier was simply false.
26
+ *
27
+ * One chain, two carriers, two bindings, for the same reason EVM has three (`evm:x402`, `evm:escrow`,
28
+ * `evm:mpp`): a manifest can honestly describe exactly one carrier.
29
+ *
30
+ * **protocol = "x402"**, and the declaration is substantive. `extra.memo` is x402's field, its 256-byte
31
+ * ceiling is x402's ceiling, and the enforcement is an x402 facilitator's. A deployment settling Canton
32
+ * Coin outside x402 does not get this carrier, and saying so is the point of the axis: an absent
33
+ * `protocol` is a positive claim of protocol-neutrality, which this binding cannot make.
34
+ *
35
+ * **assetBinding = "carried"** — the memo rides a `TransferFactory_Transfer` whose own fields name the
36
+ * receiver, the amount and the instrument, and `CantonX402TransferView` carries all three to the caller. That
37
+ * is the axis's actual test: not that the value exists on-chain, but that a consumer can reach it. The
38
+ * overlay could not, which is why it honestly said `"none"`.
39
+ *
40
+ * **recovery.zeroPartyRecoverable = false** — unchanged, and for the unchanged reason. Daml contract and
41
+ * transaction visibility is limited to stakeholders, so a neutral verifier holding only a settlement
42
+ * reference sees nothing until the payer, the merchant or the DSO grants access. §8.3 asks whether an
43
+ * auditor can reconstruct the atrHash from the settlement reference alone WITHOUT trusting either party to
44
+ * produce records; on Canton they cannot, whichever carrier is used. WLD-3 makes the direction of the
45
+ * error normative — understating costs nothing, overstating is non-conformance.
46
+ *
47
+ * **recovery.forwardIndexable = false** — a participant's update stream is one participant's view, not a
48
+ * chain-global forward index, and the memo is a metadata value rather than an indexed key. Honest for the
49
+ * same reason the overlay's participant query was.
50
+ *
51
+ * **successGate = "structural"** — a Canton transfer that did not commit produces no update, so there is
52
+ * no failed view whose memo could be misread as a settlement. The transfer either executed and its
53
+ * metadata exists, or it did not and nothing does.
54
+ *
55
+ * **weldGrades["x402-memo"] = "tx"** — the memo is committed by the payer's signed
56
+ * `TransferFactory_Transfer`, not by a detached signature over the atrHash bytes. The payer signs the
57
+ * prepared transaction (which contains the memo), so the commitment rides the transaction. Per LCP §8.3 /
58
+ * WLD-3 that is tx-grade.
59
+ *
60
+ * **finality.reversible = false** — once the transfer executes, its input holdings are consumed and Canton
61
+ * has no reversal; recourse is the record's elected forum (PAY-3/RCS-5), never dispute resolution.
62
+ */
63
+ export const CANTON_X402_MANIFEST: BindingManifest = {
64
+ rail: "canton:x402",
65
+ pattern: "native-field",
66
+ protocol: "x402",
67
+ nativeField: CANTON_X402_MEMO_KEY,
68
+ recovery: {
69
+ onChain: true,
70
+ zeroPartyRecoverable: false,
71
+ forwardIndexable: false,
72
+ },
73
+ assetBinding: "carried",
74
+ successGate: "structural",
75
+ indexing: `participant-updates:transfer.meta.${CANTON_X402_MEMO_KEY}`,
76
+ finality: {
77
+ reversible: false,
78
+ note: "a Canton transfer consumes the input holdings it names and Canton has no reversal, so an executed transfer's memo is permanent; recourse is the record's elected forum (PAY-3/RCS-5), never dispute resolution",
79
+ },
80
+ weldGrades: { "x402-memo": "tx" },
81
+ lifecycleStates: ["proposed", "settled"],
82
+ };
package/src/memo.ts ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The Canton transfer-memo atrHash codec — PURE, no Daml SDK, no HTTP.
3
+ *
4
+ * **THE CARRIER.** x402's `exact` scheme for Canton defines `PaymentRequirements.extra.memo`:
5
+ *
6
+ * > `extra.memo` (optional): Seller-defined UTF-8 string, max 256 bytes. When present, the client MUST
7
+ * > include it in the transfer's metadata.
8
+ *
9
+ * and makes it facilitator-enforced (scheme §Safety Checks, rule 12):
10
+ *
11
+ * > **Memo.** If `paymentRequirements.extra.memo` is set, the transfer metadata MUST carry the identical
12
+ * > value under `x402.memo`. Reject with `invalid_exact_canton_memo_mismatch`.
13
+ *
14
+ * So the SELLER names the value, the PAYER must echo it into the transfer that moves the money, and a
15
+ * THIRD PARTY refuses to relay the payment if they disagree. That is a §8.3.1 Native Field with an
16
+ * unusually strong commitment story, and it rides the same transaction as the value — which is what the
17
+ * overlay it replaces could never do.
18
+ *
19
+ * **WHY THIS CARRIER AND NOT AN OVERLAY CONTRACT.** Canton's other binding,
20
+ * `@integraledger/lcp-binding-canton`, welds through a custom `LcpAnchor` Daml template. Where this scheme
21
+ * applies, the memo is stronger on every axis: it rides the SAME transaction as the payment rather than a
22
+ * separate contract create, the facilitator checks it before relaying, and the transfer's own fields name
23
+ * the asset. LCP §8.3's ordering puts Overlay Contract below Native Field for exactly these reasons. The
24
+ * overlay covers what this scheme cannot reach — it settles Canton Coin only.
25
+ *
26
+ * **THE 256-BYTE CEILING NEEDS NO RUNTIME CHECK.** A canonical atrHash is exactly 66 UTF-8 bytes and the
27
+ * host allows 256, so a length guard here could never fire — it would be an unreachable branch asserting
28
+ * a fact the type of the input already settles. `CANTON_X402_MEMO_MAX_BYTES` records the host's limit and
29
+ * `constants.test.ts` proves an atrHash fits inside it; that is where a fact about the host belongs.
30
+ *
31
+ * `encodeTransferMemo` fails LOUD on a malformed atrHash (never advertise a memo we could not later
32
+ * verify); `decodeTransferMemo` returns `null` for anything that is not one, so a scan over a party's
33
+ * transfers can skip foreign memos without treating them as errors.
34
+ */
35
+ import { canonicalAtrHash, isAtrHash } from "@integraledger/lcp-kernel";
36
+ import { CANTON_X402_MEMO_KEY } from "./constants.js";
37
+
38
+ /**
39
+ * The `extra` fragment a Canton seller merges into its x402 `PaymentRequirements`.
40
+ *
41
+ * Returned as an object rather than a bare string so the call site reads as what it is — the seller
42
+ * ADVERTISING a value it is committing to — and so a future scheme field can join it without changing
43
+ * every caller. Mirrors `binding-tempo-mpp`'s `mppMethodDetailsMemo`.
44
+ */
45
+ export function x402MemoRequirement(atrHash: string): {
46
+ readonly memo: string;
47
+ } {
48
+ return { memo: encodeTransferMemo(atrHash) };
49
+ }
50
+
51
+ /**
52
+ * The memo string carrying `atrHash`: the canonical `0x`-prefixed lowercase form, verbatim.
53
+ *
54
+ * No bare-hex variant is emitted or accepted. The host calls this a "seller-defined UTF-8 string" and
55
+ * compares it byte-for-byte against the transfer metadata, so any second spelling would be a second wire
56
+ * value that a facilitator would reject against the first.
57
+ */
58
+ export function encodeTransferMemo(atrHash: string): string {
59
+ return canonicalAtrHash(atrHash, "encodeTransferMemo");
60
+ }
61
+
62
+ /** Decode a memo string back to an atrHash, or `null` if it is not a well-formed one. */
63
+ export function decodeTransferMemo(memo: string): `0x${string}` | null {
64
+ return isAtrHash(memo) ? canonicalAtrHash(memo, "decodeTransferMemo") : null;
65
+ }
66
+
67
+ /**
68
+ * Read the atrHash out of a transfer's on-ledger metadata map, or `null` if it carries none.
69
+ *
70
+ * The key is the host's — `x402.memo`, quoted in rule 12 above — and it is read EXACTLY. A metadata map
71
+ * carrying our value under some other key is a transfer that no facilitator checked, so treating it as a
72
+ * weld would assert a commitment nobody made.
73
+ */
74
+ export function readTransferMemoAtrHash(
75
+ meta: Readonly<Record<string, string>> | undefined,
76
+ ): `0x${string}` | null {
77
+ // `?? ""` rather than an `undefined` branch: an absent key and a foreign memo are the same answer, and
78
+ // "" is not a well-formed atrHash, so the decoder already gives it.
79
+ return decodeTransferMemo(meta?.[CANTON_X402_MEMO_KEY] ?? "");
80
+ }