@useopentab/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,371 @@
1
+ import {
2
+ assertTestnet
3
+ } from "./chunk-4R3NAR3C.js";
4
+ import {
5
+ isKeyBoundTo,
6
+ parseOwnerOfKeyResponse,
7
+ readExternalKeyId,
8
+ serializeExternalKeyId,
9
+ writeExternalKeyId
10
+ } from "./chunk-IRXOU25X.js";
11
+ import {
12
+ ByteReader,
13
+ ByteWriter,
14
+ accountFromBase58,
15
+ accountToBase58,
16
+ formatContractAddress,
17
+ isAccountAlias,
18
+ toHex,
19
+ toU64
20
+ } from "./chunk-HZHOKJIM.js";
21
+ import {
22
+ CIS8,
23
+ CIS8004,
24
+ RegistryChangedError,
25
+ RegistryInvokeError,
26
+ RegistryParseError
27
+ } from "./chunk-S5IAH7CT.js";
28
+
29
+ // packages/registry/src/chain.ts
30
+ import {
31
+ AccountAddress as AccountAddress2,
32
+ BlockHash as BlockHash2,
33
+ ContractAddress as ContractAddress2,
34
+ Energy,
35
+ isKnown,
36
+ Parameter,
37
+ ReceiveName,
38
+ RejectReasonTag,
39
+ ReturnValue
40
+ } from "@concordium/web-sdk";
41
+
42
+ // packages/registry/src/accountEvidence.ts
43
+ import { AccountAddress } from "@concordium/web-sdk";
44
+ var YM_RE = /^([0-9]{4})(0[1-9]|1[0-2])$/;
45
+ var CRED_ID_RE = /^[0-9a-f]{96}$/;
46
+ var HEX_RE = /^(?:[0-9a-f]{2})+$/;
47
+ function fail(msg) {
48
+ throw new RegistryParseError(`getAccountInfo: ${msg}`);
49
+ }
50
+ function checkYm(v, what) {
51
+ if (typeof v !== "string" || !YM_RE.test(v)) fail(`${what} is not YYYYMM: ${String(v)}`);
52
+ return v;
53
+ }
54
+ function checkNat(v, what) {
55
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 0) fail(`${what} is not a natural number`);
56
+ return v;
57
+ }
58
+ function accountEvidenceFromInfo(info) {
59
+ const credentials = [];
60
+ for (const [key, versioned] of Object.entries(info.accountCredentials)) {
61
+ if (!/^(?:0|[1-9][0-9]*)$/.test(key)) fail(`bad credential index ${key}`);
62
+ const index = Number(key);
63
+ const cred = versioned.value;
64
+ const c = cred.contents;
65
+ const policy = {
66
+ createdAt: checkYm(c.policy.createdAt, `credential ${index} createdAt`),
67
+ validTo: checkYm(c.policy.validTo, `credential ${index} validTo`)
68
+ };
69
+ const ipIdentity = checkNat(c.ipIdentity, `credential ${index} ipIdentity`);
70
+ if (cred.type === "initial") {
71
+ const credId = String(cred.contents.regId).toLowerCase();
72
+ if (!CRED_ID_RE.test(credId)) fail(`credential ${index} regId is not 48 bytes of hex`);
73
+ credentials.push({ index, type: "initial", credId, ipIdentity, policy, revocationThreshold: null, arData: [] });
74
+ } else if (cred.type === "normal") {
75
+ const n = cred.contents;
76
+ const credId = String(n.credId).toLowerCase();
77
+ if (!CRED_ID_RE.test(credId)) fail(`credential ${index} credId is not 48 bytes of hex`);
78
+ const revocationThreshold = checkNat(n.revocationThreshold, `credential ${index} revocationThreshold`);
79
+ const arData = [];
80
+ for (const [ar, share] of Object.entries(n.arData)) {
81
+ if (!/^[1-9][0-9]*$/.test(ar)) fail(`credential ${index} has a bad AR identity ${ar}`);
82
+ const enc = String(share.encIdCredPubShare).toLowerCase();
83
+ if (!HEX_RE.test(enc)) fail(`credential ${index} AR ${ar} share is not hex`);
84
+ arData.push({ arIdentity: Number(ar), encIdCredPubShare: enc });
85
+ }
86
+ arData.sort((a, b) => a.arIdentity - b.arIdentity);
87
+ if (revocationThreshold < 1 || revocationThreshold > arData.length) {
88
+ fail(`credential ${index} revocation threshold ${revocationThreshold} does not fit ${arData.length} ARs`);
89
+ }
90
+ credentials.push({ index, type: "normal", credId, ipIdentity, policy, revocationThreshold, arData });
91
+ } else {
92
+ fail(`credential ${index} has unknown type`);
93
+ }
94
+ }
95
+ credentials.sort((a, b) => a.index - b.index);
96
+ const first = credentials[0];
97
+ if (!first || first.index !== 0) fail("account has no credential 0");
98
+ return {
99
+ address: AccountAddress.toBase58(info.accountAddress),
100
+ accountIndex: info.accountIndex,
101
+ accountThreshold: info.accountThreshold,
102
+ isInitialAccount: first.type === "initial",
103
+ credentials
104
+ };
105
+ }
106
+
107
+ // packages/registry/src/cis8004.ts
108
+ function serializeAgentTokenId(tokenId) {
109
+ return new ByteWriter().u8(8).u64(toU64(tokenId, "token id")).finish();
110
+ }
111
+ function serializeGetMetadataParam(tokenId, key) {
112
+ return new ByteWriter().raw(serializeAgentTokenId(tokenId)).string(key).finish();
113
+ }
114
+ function serializeExternalReference(ref) {
115
+ const w = new ByteWriter().u64(ref.contract.index).u64(ref.contract.subindex).u8(0);
116
+ return writeExternalKeyId(w, ref.key).finish();
117
+ }
118
+ function readAgentTokenId(r, field) {
119
+ const at = r.offset;
120
+ const len = r.u8(`${field} length`);
121
+ if (len !== 8) r.fail(`${field}: token id must be 8 bytes, got ${len}`, at);
122
+ return r.u64(field);
123
+ }
124
+ function readStatus(r) {
125
+ const at = r.offset;
126
+ const tag = r.u8("status");
127
+ if (tag === 0) return "Active";
128
+ if (tag === 1) return "Revoked";
129
+ return r.fail(`status: unknown tag ${tag}`, at);
130
+ }
131
+ function readExternalReference(r) {
132
+ const contract = { index: r.u64("external_reference.contract.index"), subindex: r.u64("external_reference.contract.subindex") };
133
+ const at = r.offset;
134
+ const kind = r.u8("external_reference.kind");
135
+ if (kind !== 0) r.fail(`external_reference.kind: unknown tag ${kind}`, at);
136
+ return { contract, kind: "Cis8", key: readExternalKeyId(r, "external_reference.key") };
137
+ }
138
+ function readAgentView(r) {
139
+ const tokenId = readAgentTokenId(r, "token_id");
140
+ const ownerAccount = accountToBase58(r.bytes(32, "owner_account"));
141
+ const agentUri = r.option("agent_uri", () => r.string("agent_uri"));
142
+ const metadataHash = r.option("metadata_hash", () => toHex(r.bytes(32, "metadata_hash")));
143
+ const externalReference = r.option("external_reference", () => readExternalReference(r));
144
+ const agentWallet = r.option("agent_wallet", () => accountToBase58(r.bytes(32, "agent_wallet")));
145
+ const status = readStatus(r);
146
+ const registeredAt = r.u64("registered_at");
147
+ const revokedAt = r.option("revoked_at", () => r.u64("revoked_at"));
148
+ const revocationReason = r.option("revocation_reason", () => r.string("revocation_reason"));
149
+ const count = r.u32("on_chain_metadata count");
150
+ const onChainMetadata = [];
151
+ for (let i = 0; i < count; i++) {
152
+ if (r.remaining < 8) r.fail(`on_chain_metadata[${i}]: truncated`);
153
+ const key = r.string(`on_chain_metadata[${i}].key`);
154
+ const value = toHex(r.bytestring(`on_chain_metadata[${i}].value`));
155
+ onChainMetadata.push({ key, value });
156
+ }
157
+ return {
158
+ tokenId,
159
+ ownerAccount,
160
+ agentUri,
161
+ metadataHash,
162
+ externalReference,
163
+ agentWallet,
164
+ status,
165
+ registeredAt,
166
+ revokedAt,
167
+ revocationReason,
168
+ onChainMetadata
169
+ };
170
+ }
171
+ function parseAgentOfResponse(bytes, expectedTokenId) {
172
+ const r = new ByteReader(bytes, "CIS-8004.agentOf");
173
+ const view = r.option("agent", () => readAgentView(r));
174
+ r.end();
175
+ if (view && expectedTokenId !== void 0 && view.tokenId !== toU64(expectedTokenId, "token id")) {
176
+ throw new RegistryParseError(`CIS-8004.agentOf: returned token ${view.tokenId}, asked for ${expectedTokenId}`);
177
+ }
178
+ return view;
179
+ }
180
+ function parseGetAgentWalletResponse(bytes) {
181
+ const r = new ByteReader(bytes, "CIS-8004.getAgentWallet");
182
+ const wallet = r.option("wallet", () => accountToBase58(r.bytes(32, "wallet")));
183
+ r.end();
184
+ return wallet;
185
+ }
186
+ function parseGetAgentWalletNonceResponse(bytes) {
187
+ const r = new ByteReader(bytes, "CIS-8004.getAgentWalletNonce");
188
+ const nonce = r.option("nonce", () => r.u64("nonce"));
189
+ r.end();
190
+ return nonce;
191
+ }
192
+ function parseGetMetadataResponse(bytes) {
193
+ const r = new ByteReader(bytes, "CIS-8004.getMetadata");
194
+ const value = r.option("value", () => toHex(r.bytestring("value")));
195
+ r.end();
196
+ return value;
197
+ }
198
+
199
+ // packages/registry/src/moduleRefs.ts
200
+ import { BlockHash, ContractAddress, InitName, ModuleReference } from "@concordium/web-sdk";
201
+ var PINNED_REGISTRIES = Object.freeze({ cis8004: CIS8004, cis8: CIS8 });
202
+ async function checkRegistryModules(client, pinned = PINNED_REGISTRIES, blockHash) {
203
+ const block = blockHash === void 0 ? void 0 : BlockHash.fromHexString(blockHash);
204
+ const contracts = await Promise.all(
205
+ [pinned.cis8004, pinned.cis8].map(async (c) => {
206
+ const info = await client.getInstanceInfo(ContractAddress.create(c.address.index, c.address.subindex), block);
207
+ const actualModule = ModuleReference.toHexString(info.sourceModule);
208
+ const actualName = InitName.toString(info.name);
209
+ const expectedName = `init_${c.contractName}`;
210
+ return {
211
+ label: c.label,
212
+ address: formatContractAddress(c.address),
213
+ expectedModule: c.moduleRef,
214
+ actualModule,
215
+ expectedName,
216
+ actualName,
217
+ ok: actualModule === c.moduleRef && actualName === expectedName
218
+ };
219
+ })
220
+ );
221
+ return { ok: contracts.every((c) => c.ok), contracts };
222
+ }
223
+ async function assertRegistryModules(client, pinned = PINNED_REGISTRIES, blockHash) {
224
+ const report = await checkRegistryModules(client, pinned, blockHash);
225
+ if (!report.ok) {
226
+ throw new RegistryChangedError(
227
+ report.contracts.filter((c) => !c.ok).map((c) => ({
228
+ contract: `${c.label} ${c.address}`,
229
+ expected: `${c.expectedName} ${c.expectedModule}`,
230
+ actual: `${c.actualName} ${c.actualModule}`
231
+ }))
232
+ );
233
+ }
234
+ return report;
235
+ }
236
+ var REGISTRY_MANIFEST_URL = new URL("../../../contracts/tab_bureau/tests/fixtures/registry-modules.json", import.meta.url);
237
+
238
+ // packages/registry/src/chain.ts
239
+ var AGENT_NOT_FOUND = -7200;
240
+ var RegistryReader = class {
241
+ client;
242
+ cis8004;
243
+ cis8;
244
+ #moduleCheck;
245
+ #ttl;
246
+ #energy;
247
+ #now;
248
+ /** blockHash (or 'latest') -> time the module check last passed. */
249
+ #checked = /* @__PURE__ */ new Map();
250
+ constructor(client, opts = {}) {
251
+ this.client = client;
252
+ this.cis8004 = opts.cis8004 ?? CIS8004;
253
+ this.cis8 = opts.cis8 ?? CIS8;
254
+ this.#moduleCheck = opts.moduleCheck ?? "cached";
255
+ this.#ttl = opts.moduleCheckTtlMs ?? 6e4;
256
+ this.#energy = opts.energy ?? 100000n;
257
+ this.#now = opts.now ?? Date.now;
258
+ }
259
+ /** Fail unless the node is on testnet. */
260
+ async assertTestnet() {
261
+ await assertTestnet(this.client);
262
+ }
263
+ /** Check both registries against the pinned module refs; throws `RegistryChangedError`. */
264
+ async assertModules(opts = {}) {
265
+ const report = await assertRegistryModules(this.client, { cis8004: this.cis8004, cis8: this.cis8 }, opts.blockHash);
266
+ this.#markChecked(opts.blockHash);
267
+ return report;
268
+ }
269
+ #markChecked(blockHash) {
270
+ const key = blockHash ?? "latest";
271
+ this.#checked.delete(key);
272
+ this.#checked.set(key, this.#now());
273
+ while (this.#checked.size > 64) {
274
+ const oldest = this.#checked.keys().next().value;
275
+ if (oldest === void 0) break;
276
+ this.#checked.delete(oldest);
277
+ }
278
+ }
279
+ async #ensureModules(blockHash) {
280
+ if (this.#moduleCheck === "off") return;
281
+ if (this.#moduleCheck === "cached") {
282
+ const at = this.#checked.get(blockHash ?? "latest");
283
+ if (at !== void 0 && this.#now() - at < this.#ttl) return;
284
+ }
285
+ await this.assertModules(blockHash === void 0 ? {} : { blockHash });
286
+ }
287
+ /** Invoke a registry entrypoint and return the raw return value bytes. */
288
+ async invokeRaw(contract, entrypoint, parameter, opts = {}) {
289
+ await this.#ensureModules(opts.blockHash);
290
+ const method = `${contract.contractName}.${entrypoint}`;
291
+ const res = await this.client.invokeContract(
292
+ {
293
+ contract: ContractAddress2.create(contract.address.index, contract.address.subindex),
294
+ method: ReceiveName.fromString(method),
295
+ parameter: Parameter.fromHexString(toHex(parameter)),
296
+ energy: Energy.create(this.#energy)
297
+ },
298
+ opts.blockHash === void 0 ? void 0 : BlockHash2.fromHexString(opts.blockHash)
299
+ );
300
+ if (res.tag === "failure") {
301
+ const reason = res.reason;
302
+ if (isKnown(reason) && reason.tag === RejectReasonTag.RejectedReceive) {
303
+ throw new RegistryInvokeError(method, `rejected with code ${reason.rejectReason}`, reason.rejectReason);
304
+ }
305
+ throw new RegistryInvokeError(method, `invocation failed (${isKnown(reason) ? reason.tag : "unknown reason"})`);
306
+ }
307
+ if (res.returnValue === void 0) throw new RegistryParseError(`${method}: no return value`);
308
+ return Uint8Array.from(ReturnValue.toBuffer(res.returnValue));
309
+ }
310
+ async #agentRead(entrypoint, parameter, opts, parse) {
311
+ let bytes;
312
+ try {
313
+ bytes = await this.invokeRaw(this.cis8004, entrypoint, parameter, opts);
314
+ } catch (e) {
315
+ if (e instanceof RegistryInvokeError && e.rejectCode === AGENT_NOT_FOUND) return null;
316
+ throw e;
317
+ }
318
+ return parse(bytes);
319
+ }
320
+ /** `agentOf(token_id)`; `null` when no agent has that id. */
321
+ agentOf(tokenId, opts = {}) {
322
+ return this.#agentRead("agentOf", serializeAgentTokenId(tokenId), opts, (b) => parseAgentOfResponse(b, tokenId));
323
+ }
324
+ /** `agentByExternalReference(ref)`; `null` when no active agent holds it. */
325
+ agentByExternalReference(ref, opts = {}) {
326
+ return this.#agentRead("agentByExternalReference", serializeExternalReference(ref), opts, (b) => parseAgentOfResponse(b));
327
+ }
328
+ /** `getAgentWallet(token_id)`: the payment account, or `null` (unset, or no such agent). */
329
+ getAgentWallet(tokenId, opts = {}) {
330
+ return this.#agentRead("getAgentWallet", serializeAgentTokenId(tokenId), opts, parseGetAgentWalletResponse);
331
+ }
332
+ /** `getAgentWalletNonce(token_id)`; `null` when there is no such agent. */
333
+ getAgentWalletNonce(tokenId, opts = {}) {
334
+ return this.#agentRead("getAgentWalletNonce", serializeAgentTokenId(tokenId), opts, parseGetAgentWalletNonceResponse);
335
+ }
336
+ /** `getMetadata(token_id, key)`: the value as lowercase hex, or `null`. */
337
+ getMetadata(tokenId, key, opts = {}) {
338
+ return this.#agentRead("getMetadata", serializeGetMetadataParam(tokenId, key), opts, parseGetMetadataResponse);
339
+ }
340
+ /**
341
+ * CIS-8 `ownerOfKey(key)`, as stored. The registration may be Revoked, and its key may be a
342
+ * canonical form of `key` (secp256k1); use {@link RegistryReader.isKeyBoundTo} for decisions.
343
+ */
344
+ async ownerOfKey(key, opts = {}) {
345
+ const bytes = await this.invokeRaw(this.cis8, "ownerOfKey", serializeExternalKeyId(key), opts);
346
+ return parseOwnerOfKeyResponse(bytes);
347
+ }
348
+ /** Spec §3.4 displacement check, read live. */
349
+ async isKeyBoundTo(owner, pinned, opts = {}) {
350
+ return isKeyBoundTo(await this.ownerOfKey(pinned, opts), owner, pinned);
351
+ }
352
+ /** Credential evidence for an account (see accountEvidence.ts). */
353
+ async accountEvidence(address, opts = {}) {
354
+ accountFromBase58(address);
355
+ const info = await this.client.getAccountInfo(
356
+ AccountAddress2.fromBase58(address),
357
+ opts.blockHash === void 0 ? void 0 : BlockHash2.fromHexString(opts.blockHash)
358
+ );
359
+ const evidence = accountEvidenceFromInfo(info);
360
+ if (evidence.address !== address) {
361
+ if (!isAccountAlias(evidence.address, address)) {
362
+ throw new RegistryParseError(`getAccountInfo returned ${evidence.address} for ${address}`);
363
+ }
364
+ }
365
+ return evidence;
366
+ }
367
+ };
368
+
369
+ export {
370
+ RegistryReader
371
+ };
@@ -0,0 +1,53 @@
1
+ // packages/cli/src/report.ts
2
+ var ReportBuilder = class {
3
+ #subject;
4
+ #checks = [];
5
+ #facts = {};
6
+ #children = [];
7
+ constructor(subject) {
8
+ this.#subject = subject;
9
+ }
10
+ /** Records a check; returns `ok` so callers can stop early. */
11
+ check(name, ok, detail = "") {
12
+ this.#checks.push({ name, ok, detail });
13
+ return ok;
14
+ }
15
+ fact(name, value) {
16
+ this.#facts[name] = value === null ? "none" : String(value);
17
+ }
18
+ child(report) {
19
+ this.#children.push(report);
20
+ }
21
+ get failed() {
22
+ return this.#checks.some((c) => !c.ok) || this.#children.some((c) => !c.ok);
23
+ }
24
+ build() {
25
+ return {
26
+ subject: this.#subject,
27
+ ok: this.#checks.length + this.#children.length > 0 && !this.failed,
28
+ checks: [...this.#checks],
29
+ facts: { ...this.#facts },
30
+ children: [...this.#children]
31
+ };
32
+ }
33
+ };
34
+ function errorReport(subject, error) {
35
+ return { subject, ok: false, checks: [{ name: "verifiable", ok: false, detail: error }], facts: {}, children: [] };
36
+ }
37
+ function renderReport(r, indent = "") {
38
+ const lines = [`${indent}${r.ok ? "PASS" : "FAIL"} ${r.subject}`];
39
+ for (const c of r.checks) lines.push(`${indent} ${c.ok ? "ok " : "FAIL"} ${c.name}${c.detail === "" ? "" : `: ${c.detail}`}`);
40
+ for (const [k, v] of Object.entries(r.facts)) lines.push(`${indent} \xB7 ${k}: ${v}`);
41
+ for (const child of r.children) lines.push(renderReport(child, `${indent} `));
42
+ return lines.join("\n");
43
+ }
44
+ function reportJson(r) {
45
+ return JSON.stringify(r, null, 2);
46
+ }
47
+
48
+ export {
49
+ ReportBuilder,
50
+ errorReport,
51
+ renderReport,
52
+ reportJson
53
+ };
@@ -0,0 +1,223 @@
1
+ import {
2
+ HASH_RE,
3
+ attempt,
4
+ bureauCall,
5
+ bureauEvents,
6
+ ccd,
7
+ finalizedTx,
8
+ lineOf,
9
+ standingOf,
10
+ tabOf
11
+ } from "./chunk-QTI2WM44.js";
12
+ import {
13
+ ReportBuilder
14
+ } from "./chunk-GOEFQ62Z.js";
15
+ import {
16
+ TESTNET_CIS8,
17
+ TESTNET_CIS8004,
18
+ accountAddressToBase58,
19
+ ascii,
20
+ bureauErrorName,
21
+ bytesEqual,
22
+ contractAddressEqual,
23
+ decodeBureauEvent,
24
+ decodeCis8004Event,
25
+ decodeCis8Event,
26
+ decodeOpenLineParams,
27
+ decodeSettleTabParams,
28
+ isFlagged,
29
+ toHex
30
+ } from "./chunk-D3C7KAMJ.js";
31
+
32
+ // packages/cli/src/verify/expectRules.ts
33
+ var REGISTRY_ENTRYPOINTS = {
34
+ registerAgent: "CIS-8004.register",
35
+ setAgentWallet: "CIS-8004.setAgentWallet",
36
+ setAgentURI: "CIS-8004.setAgentURI",
37
+ registerExternalKey: "CIS-8.registerExternalKey"
38
+ };
39
+ var BUREAU_KINDS = ["registerSeller", "openLine", "openTab", "settleTab", "reportDefault", "closeTab", "closeLine"];
40
+ var DRP_ANCHOR_PREFIX = ascii("OTDRP1");
41
+ function drpAnchorRoot(data) {
42
+ if (data === null || data.length !== DRP_ANCHOR_PREFIX.length + 32) return null;
43
+ if (!bytesEqual(data.subarray(0, DRP_ANCHOR_PREFIX.length), DRP_ANCHOR_PREFIX)) return null;
44
+ return toHex(data.subarray(DRP_ANCHOR_PREFIX.length));
45
+ }
46
+ function registryCall(tx, kind) {
47
+ const name = REGISTRY_ENTRYPOINTS[kind];
48
+ if (name === void 0) return void 0;
49
+ const contract = kind === "registerExternalKey" ? TESTNET_CIS8 : TESTNET_CIS8004;
50
+ return tx.calls.findLast((c) => c.receiveName === name && contractAddressEqual(c.contract, contract));
51
+ }
52
+ function movedAmount(ctx, tx, kind) {
53
+ if (BUREAU_KINDS.includes(kind)) return bureauCall(ctx, tx, kind)?.amount ?? null;
54
+ if (REGISTRY_ENTRYPOINTS[kind] !== void 0) return registryCall(tx, kind)?.amount ?? null;
55
+ if (kind === "exactPayment") return tx.accountTransfer?.amount ?? null;
56
+ return tx.accountTransfer?.amount ?? tx.calls.at(-1)?.amount ?? 0n;
57
+ }
58
+ function describeEvent(ctx, contract, e) {
59
+ try {
60
+ if (contractAddressEqual(contract, ctx.bureau)) return `tab_bureau ${JSON.stringify(eventJson(decodeBureauEvent(e)))}`;
61
+ if (contractAddressEqual(contract, TESTNET_CIS8004)) return `CIS-8004 ${JSON.stringify(eventJson(decodeCis8004Event(e)))}`;
62
+ if (contractAddressEqual(contract, TESTNET_CIS8)) return `CIS-8 ${JSON.stringify(eventJson(decodeCis8Event(e)))}`;
63
+ } catch {
64
+ return `undecodable event ${toHex(e).slice(0, 64)}`;
65
+ }
66
+ return `<${contract.index},${contract.subindex}> event ${toHex(e).slice(0, 64)}`;
67
+ }
68
+ var ACCOUNT_FIELDS = /* @__PURE__ */ new Set(["ownerAccount", "newWallet", "owner", "previous", "next"]);
69
+ function eventJson(e, key = "") {
70
+ if (e instanceof Uint8Array) return ACCOUNT_FIELDS.has(key) && e.length === 32 ? accountAddressToBase58(e) : toHex(e);
71
+ if (typeof e === "bigint") return e.toString();
72
+ if (Array.isArray(e)) return e.map((x) => eventJson(x));
73
+ if (e !== null && typeof e === "object") return Object.fromEntries(Object.entries(e).map(([k, v]) => [k, eventJson(v, k)]));
74
+ return e;
75
+ }
76
+ function entrypointOf(ctx, kind) {
77
+ if (BUREAU_KINDS.includes(kind)) return { contract: ctx.bureau, receiveName: `tab_bureau.${kind}` };
78
+ const name = REGISTRY_ENTRYPOINTS[kind];
79
+ if (name === void 0) return null;
80
+ return { contract: kind === "registerExternalKey" ? TESTNET_CIS8 : TESTNET_CIS8004, receiveName: name };
81
+ }
82
+ var codeText = (code) => {
83
+ const name = bureauErrorName(code);
84
+ return `${code}${name === null ? "" : ` (${name})`}`;
85
+ };
86
+ async function verifyRejected(ctx, hash, kind, code, rb) {
87
+ if (!rb.check("transaction hash is well formed", HASH_RE.test(hash), hash)) return null;
88
+ const found = await ctx.chain.transaction(hash);
89
+ if (!rb.check("transaction is finalized", found.status === "finalized", found.status) || found.status !== "finalized") return null;
90
+ const tx = found.tx;
91
+ const want = codeText(code);
92
+ if (!rb.check("transaction was rejected", !tx.ok, tx.ok ? `succeeded in block ${tx.blockHeight}` : tx.rejectReason ?? "rejected")) {
93
+ rb.check(`rejected with code ${want}`, false, "not rejected");
94
+ return tx;
95
+ }
96
+ const ep = entrypointOf(ctx, kind);
97
+ const call = tx.rejectedCall ?? null;
98
+ let ours = true;
99
+ if (ep !== null) {
100
+ ours = call !== null && contractAddressEqual(call.contract, ep.contract) && call.receiveName === ep.receiveName;
101
+ const where = contractAddressEqual(ep.contract, ctx.bureau) ? "this bureau" : `<${ep.contract.index},${ep.contract.subindex}>`;
102
+ rb.check(
103
+ `rejected by ${ep.receiveName} on ${where}`,
104
+ ours,
105
+ call === null ? tx.rejectReason ?? "no contract rejection" : `${call.receiveName} on <${call.contract.index},${call.contract.subindex}>`
106
+ );
107
+ }
108
+ rb.check(`rejected with code ${want}`, tx.rejectCode === code, tx.rejectCode === null ? tx.rejectReason ?? "no code" : codeText(tx.rejectCode));
109
+ if (tx.rejectCode !== null) rb.fact("reject code", codeText(tx.rejectCode));
110
+ if (kind === "openLine" && ours && call !== null) {
111
+ const p = attempt(rb, "openLine parameter decodes", () => decodeOpenLineParams(call.parameter));
112
+ if (p !== null) {
113
+ const owner = accountAddressToBase58(p.terms.owner);
114
+ rb.fact("buyer token", p.terms.buyerToken);
115
+ rb.fact("line owner", owner);
116
+ rb.fact("line limit", ccd(p.terms.lineLimit));
117
+ rb.fact("tier", p.attestation.tier);
118
+ if (bureauErrorName(code) === "Flagged") {
119
+ const keys = [{ kind: "account", account: p.terms.owner }];
120
+ if (p.attestation.tier > 0) keys.unshift({ kind: "subject", subjectKey: p.attestation.subjectKey });
121
+ const standings = await Promise.all(keys.map((k) => standingOf(ctx, k, tx.parentBlock)));
122
+ const flagged = standings.some((s) => isFlagged(s, tx.blockTime));
123
+ rb.check(
124
+ "the line owner\u2019s standing key was flagged at the block before",
125
+ flagged,
126
+ standings.map((s) => `open defaults ${s.openDefaults}, flagged until ${new Date(Number(s.flagUntil)).toISOString()}`).join("; ")
127
+ );
128
+ }
129
+ }
130
+ }
131
+ return tx;
132
+ }
133
+ async function verifyCapStep(ctx, tx, expected, rb) {
134
+ const events = attempt(rb, "bureau events decode", () => bureauEvents(ctx, tx)) ?? [];
135
+ const steps = events.filter((e) => e.type === "CapStepped");
136
+ if (!expected) {
137
+ rb.check("logged no CapStepped", steps.length === 0, steps.length === 0 ? void 0 : `${steps.length} CapStepped`);
138
+ return;
139
+ }
140
+ const call = bureauCall(ctx, tx, "settleTab");
141
+ const params = call === void 0 ? null : attempt(rb, "settleTab parameter decodes", () => decodeSettleTabParams(call.parameter));
142
+ const tab = params === null ? null : await tabOf(ctx, params.close.tabId, tx.blockHash);
143
+ const step = tab === null ? void 0 : steps.find((e) => e.type === "CapStepped" && e.lineId === tab.lineId);
144
+ if (!rb.check("logged CapStepped for the tab\u2019s line", step?.type === "CapStepped", steps.length === 0 ? "none" : `${steps.length} CapStepped`) || step?.type !== "CapStepped" || tab === null) return;
145
+ rb.fact("cap step", `line ${step.lineId} to k = ${step.k}`);
146
+ const line = await lineOf(ctx, tab.lineId, tx.blockHash);
147
+ if (!rb.check("the tab\u2019s line exists", line !== null) || line === null) return;
148
+ const after = await standingOf(ctx, line.standingKey, tx.blockHash);
149
+ rb.check("CapStepped.k = the standing key\u2019s k after the block", after.k === step.k, `k = ${after.k}`);
150
+ }
151
+ var TESTNET_DRP_ANCHOR_ACCOUNTS = [
152
+ "3mJWFAQpYYMSQLoTwWmGwNhBGSdL5XAaJYVwv7NnMuZmRgjE49",
153
+ "4HT2tWdvyiZ4TcZ6WnCWJhs8Vid8PTREVvTh597b9aTaYXMGeo"
154
+ ];
155
+ function verifyDrpAnchor(ctx, tx, rb) {
156
+ const data = tx.registeredData;
157
+ rb.check("is a RegisterData", tx.type === "registerData" && data !== null, tx.type);
158
+ const accepted = ctx.drpAnchorAccounts ?? [ctx.anchorAccount];
159
+ rb.check("sent by a DRP-1 anchor account", accepted.includes(tx.sender), tx.sender);
160
+ const root = drpAnchorRoot(data);
161
+ rb.check('payload is "OTDRP1" \u2016 a 32-byte root', root !== null, data === null ? "no data" : `${data.length} bytes`);
162
+ if (root !== null) rb.fact("DRP-1 root", root);
163
+ }
164
+ function verifyDrpRoot(tx, expected, rb) {
165
+ const root = drpAnchorRoot(tx.registeredData);
166
+ rb.check("anchors the expected DRP-1 root", root === expected, root ?? "no DRP-1 root");
167
+ }
168
+ async function verifyTxWith(ctx, hash, entry, kindChecks, inferKind) {
169
+ const rb = new ReportBuilder(`tx ${hash}${entry?.label === void 0 ? "" : ` (${entry.label})`}`);
170
+ const rejectCode = entry?.expect?.rejectCode;
171
+ if (entry !== void 0 && rejectCode !== void 0) {
172
+ const tx2 = await verifyRejected(ctx, hash, entry.kind, rejectCode, rb);
173
+ if (tx2 === null) return rb.build();
174
+ describeTx(ctx, tx2, entry.kind, rb);
175
+ expectations(ctx, tx2, entry.kind, entry.expect, rb);
176
+ return rb.build();
177
+ }
178
+ const tx = await finalizedTx(ctx, hash, rb);
179
+ if (tx === null) return rb.build();
180
+ const kind = entry?.kind ?? inferKind(tx);
181
+ describeTx(ctx, tx, kind, rb);
182
+ await kindChecks(ctx, tx, kind, rb);
183
+ const expect = entry?.expect;
184
+ if (expect?.capStepped !== void 0) await verifyCapStep(ctx, tx, expect.capStepped, rb);
185
+ if (expect?.drpRoot !== void 0) verifyDrpRoot(tx, expect.drpRoot, rb);
186
+ expectations(ctx, tx, kind, expect, rb);
187
+ return rb.build();
188
+ }
189
+ function describeTx(ctx, tx, kind, rb) {
190
+ rb.fact("kind", kind);
191
+ rb.fact("type", tx.type);
192
+ rb.fact("block", `${tx.blockHeight} (${tx.blockHash})`);
193
+ rb.fact("time", new Date(Number(tx.blockTime)).toISOString());
194
+ rb.fact("sender", tx.sender);
195
+ rb.fact("sponsor", tx.sponsor);
196
+ rb.fact("fee", ccd(tx.costMicroCcd));
197
+ tx.calls.forEach((c, i) => rb.fact(`call ${i + 1}`, `${c.receiveName} on <${c.contract.index},${c.contract.subindex}>${c.amount > 0n ? ` with ${ccd(c.amount)}` : ""}`));
198
+ tx.transfers.forEach((t, i) => rb.fact(`transfer ${i + 1}`, `${ccd(t.amount)} from <${t.from.index},${t.from.subindex}> to ${t.to}`));
199
+ [...tx.calls, ...tx.interruptedEvents].flatMap((c) => c.events.map((e) => describeEvent(ctx, c.contract, e))).forEach((e, i) => rb.fact(`event ${i + 1}`, e));
200
+ }
201
+ function expectations(ctx, tx, kind, expect, rb) {
202
+ if (expect?.sender !== void 0) rb.check("sent by the expected account", tx.sender === expect.sender, tx.sender);
203
+ if (expect?.amountMicroCcd !== void 0) {
204
+ const amount = movedAmount(ctx, tx, kind);
205
+ rb.check("moved the expected amount", amount !== null && amount.toString() === expect.amountMicroCcd, amount === null ? `no ${kind} call` : ccd(amount));
206
+ }
207
+ if (expect?.tabId !== void 0 || expect?.lineId !== void 0) {
208
+ const events = attempt(rb, "bureau events decode", () => bureauEvents(ctx, tx)) ?? [];
209
+ const ids = events.flatMap((e) => ("tabId" in e ? [`tab:${e.tabId}`] : []).concat("lineId" in e ? [`line:${e.lineId}`] : []));
210
+ if (expect.tabId !== void 0) rb.check("names the expected tab", ids.includes(`tab:${expect.tabId}`));
211
+ if (expect.lineId !== void 0) rb.check("names the expected line", ids.includes(`line:${expect.lineId}`));
212
+ }
213
+ }
214
+
215
+ export {
216
+ REGISTRY_ENTRYPOINTS,
217
+ BUREAU_KINDS,
218
+ drpAnchorRoot,
219
+ registryCall,
220
+ TESTNET_DRP_ANCHOR_ACCOUNTS,
221
+ verifyDrpAnchor,
222
+ verifyTxWith
223
+ };