@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,95 @@
1
+ import {
2
+ ccd,
3
+ lineOf
4
+ } from "./chunk-QTI2WM44.js";
5
+ import {
6
+ KeyFileOwnerSigner,
7
+ consentUrl,
8
+ explorerTx,
9
+ submitUpdate
10
+ } from "./chunk-Q776JIO3.js";
11
+ import "./chunk-IRXOU25X.js";
12
+ import "./chunk-HZHOKJIM.js";
13
+ import "./chunk-S5IAH7CT.js";
14
+ import {
15
+ ReportBuilder
16
+ } from "./chunk-GOEFQ62Z.js";
17
+ import {
18
+ CliError
19
+ } from "./chunk-MOZ4BFSB.js";
20
+ import {
21
+ BUREAU_ENTRYPOINTS,
22
+ TESTNET_GENESIS_HEX,
23
+ accountAddressToBase58,
24
+ decodeStandingOfResult,
25
+ encodeCloseLineParams,
26
+ encodeStandingOfParams,
27
+ fromHex,
28
+ isFlagged,
29
+ toHex
30
+ } from "./chunk-D3C7KAMJ.js";
31
+
32
+ // packages/cli/src/commands/line.ts
33
+ function lineOpen(env, a) {
34
+ const web = env.config.publicBaseUrl;
35
+ if (web === null) throw new CliError("usage", "set PUBLIC_BASE_URL (the web app that serves the consent page)");
36
+ const rb = new ReportBuilder(`open a line for agent ${a.tokenId}`);
37
+ const url = consentUrl(web, { tokenId: a.tokenId, owner: a.owner, sessionKeyHex: a.sessionKeyHex, bureau: env.config.bureau });
38
+ rb.check("consent URL built", true, "the owner opens it, approves the terms and signs openLine in Browser Wallet");
39
+ rb.fact("consent URL", url);
40
+ return rb.build();
41
+ }
42
+ async function lineStatus(env, lineId) {
43
+ const chain = await env.verifyChain();
44
+ const ctx = { chain, bureau: env.config.bureau, anchorAccount: env.config.anchorAccount, drpAnchorAccounts: env.config.drpAnchorAccounts, genesis: fromHex(TESTNET_GENESIS_HEX, 32) };
45
+ const rb = new ReportBuilder(`line ${lineId}`);
46
+ const line = await lineOf(ctx, lineId);
47
+ if (!rb.check("line exists", line !== null) || line === null) return rb.build();
48
+ const standing = decodeStandingOfResult(await chain.bureauView(BUREAU_ENTRYPOINTS.standingOf, encodeStandingOfParams(line.standingKey)));
49
+ rb.fact("status", line.status);
50
+ rb.fact("owner", accountAddressToBase58(line.owner));
51
+ rb.fact("buyer token", line.buyerToken);
52
+ rb.fact("buyer wallet", line.buyerWallet === null ? null : accountAddressToBase58(line.buyerWallet));
53
+ rb.fact("session key", toHex(line.sessionKey.publicKey));
54
+ rb.fact("tier", `T${line.tier}${line.ci ? " (CI line)" : ""}`);
55
+ rb.fact("line limit", ccd(line.lineLimit));
56
+ rb.fact("per-seller max", ccd(line.perSellerMax));
57
+ rb.fact("open total", ccd(line.openTotal));
58
+ rb.fact("open tabs", line.openTabs.join(", ") || "none");
59
+ rb.fact("valid until", new Date(Number(line.validUntil)).toISOString());
60
+ rb.fact("standing", `k=${standing.k}, on-time cycles ${standing.onTimeCycles}, open defaults ${standing.openDefaults}`);
61
+ rb.fact("flagged now", isFlagged(standing, BigInt(env.io.now())));
62
+ return rb.build();
63
+ }
64
+ async function lineClose(env, a) {
65
+ const chain = await env.onboardChain();
66
+ const signer = a.ownerKeyFile === null ? null : await KeyFileOwnerSigner.fromFile(a.ownerKeyFile);
67
+ const rb = new ReportBuilder(`close line ${a.lineId}`);
68
+ try {
69
+ const r = await submitUpdate(
70
+ {
71
+ sender: signer?.address ?? a.owner,
72
+ contract: env.config.bureau,
73
+ receiveName: `tab_bureau.${BUREAU_ENTRYPOINTS.closeLine}`,
74
+ parameter: encodeCloseLineParams(a.lineId),
75
+ amount: 0n
76
+ },
77
+ { chain, signer, now: () => env.io.now() }
78
+ );
79
+ if (r.kind === "unsigned") {
80
+ rb.check("dry run passed", true, "sign and send this payload from the owner in Browser Wallet");
81
+ rb.fact("payload", JSON.stringify(r.payload));
82
+ } else {
83
+ rb.check("closeLine finalized", true, r.outcome.txHash);
84
+ rb.fact("explorer", explorerTx(r.outcome.txHash));
85
+ }
86
+ } finally {
87
+ signer?.destroy();
88
+ }
89
+ return rb.build();
90
+ }
91
+ export {
92
+ lineClose,
93
+ lineOpen,
94
+ lineStatus
95
+ };
@@ -0,0 +1,299 @@
1
+ import {
2
+ createTestnetGrpcClient
3
+ } from "./chunk-4R3NAR3C.js";
4
+ import "./chunk-S5IAH7CT.js";
5
+ import {
6
+ CliError
7
+ } from "./chunk-MOZ4BFSB.js";
8
+ import {
9
+ BUREAU_CONTRACT_NAME,
10
+ contractAddress,
11
+ fromHex
12
+ } from "./chunk-D3C7KAMJ.js";
13
+
14
+ // packages/registry/src/retry.ts
15
+ var TRANSIENT_CODES = /* @__PURE__ */ new Set(["UNAVAILABLE", "DEADLINE_EXCEEDED", "RESOURCE_EXHAUSTED", 14, 4, 8]);
16
+ var VAGUE_CODES = /* @__PURE__ */ new Set([void 0, null, "UNKNOWN", "INTERNAL", 2, 13]);
17
+ var NETWORK_CODES = /* @__PURE__ */ new Set(["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EAI_AGAIN", "EPIPE", "ENETUNREACH", "EHOSTUNREACH"]);
18
+ var TRANSIENT_MESSAGE = /Received HTTP status code (429|502|503|504)\b|\bUNAVAILABLE\b|DEADLINE_EXCEEDED|RESOURCE_EXHAUSTED|Deadline exceeded|RST_STREAM|No connection established|Connection dropped|socket hang up|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN/i;
19
+ function isTransientReadError(e) {
20
+ if (e instanceof ReadRetryExhaustedError) return false;
21
+ if (typeof e !== "object" || e === null) return false;
22
+ const code = e.code;
23
+ if (TRANSIENT_CODES.has(code) || NETWORK_CODES.has(code)) return true;
24
+ if (!VAGUE_CODES.has(code)) return false;
25
+ return TRANSIENT_MESSAGE.test(e instanceof Error ? e.message : String(e));
26
+ }
27
+ function describe(e) {
28
+ const message = e instanceof Error ? e.message : String(e);
29
+ const code = e?.code;
30
+ return typeof code === "string" && code !== "" && !message.includes(code) ? `${message} (${code})` : message;
31
+ }
32
+ var seconds = (ms) => (ms / 1e3).toFixed(1);
33
+ var ReadRetryExhaustedError = class extends Error {
34
+ name = "ReadRetryExhaustedError";
35
+ label;
36
+ /** Attempts made (0 when the time was already up). */
37
+ attempts;
38
+ elapsedMs;
39
+ /** True when the time budget (not the attempt limit) ended it. */
40
+ outOfTime;
41
+ constructor(r) {
42
+ const tries = `${r.attempts} attempt${r.attempts === 1 ? "" : "s"} in ${seconds(r.elapsedMs)} s`;
43
+ const why = `${r.cutInFlight === true ? "; the last attempt got no answer" : ""}${r.last === void 0 ? "" : `; last error: ${describe(r.last)}`}`;
44
+ super(
45
+ r.attempts === 0 ? `${r.label}: not attempted, no time left` : r.outOfTime ? `${r.label}: out of time after ${tries} (${+(r.budgetMs / 1e3).toFixed(1)} s allowed)${why}` : `${r.label}: gave up after ${tries}${why}`,
46
+ r.last === void 0 ? void 0 : { cause: r.last }
47
+ );
48
+ this.label = r.label;
49
+ this.attempts = r.attempts;
50
+ this.elapsedMs = r.elapsedMs;
51
+ this.outOfTime = r.outOfTime;
52
+ }
53
+ };
54
+ var OUT_OF_TIME = /* @__PURE__ */ Symbol("out of time");
55
+ function within(read, ms) {
56
+ let p;
57
+ try {
58
+ p = Promise.resolve(read());
59
+ } catch (e) {
60
+ p = Promise.reject(e);
61
+ }
62
+ if (!Number.isFinite(ms)) return p;
63
+ return new Promise((resolve, reject) => {
64
+ const timer = setTimeout(() => reject(OUT_OF_TIME), ms);
65
+ p.then(
66
+ (v) => {
67
+ clearTimeout(timer);
68
+ resolve(v);
69
+ },
70
+ (e) => {
71
+ clearTimeout(timer);
72
+ reject(e);
73
+ }
74
+ );
75
+ });
76
+ }
77
+ async function retryRead(read, opts = {}) {
78
+ const label = opts.label ?? "node read";
79
+ const attempts = Math.max(1, opts.attempts ?? 6);
80
+ const base = opts.baseDelayMs ?? 500;
81
+ const max = opts.maxDelayMs ?? 8e3;
82
+ const transient = opts.isTransient ?? isTransientReadError;
83
+ const now = opts.now ?? Date.now;
84
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
85
+ const random = opts.random ?? Math.random;
86
+ const started = now();
87
+ const end = Math.min(started + (opts.budgetMs ?? 3e4), opts.deadlineAt ?? Number.POSITIVE_INFINITY);
88
+ let last;
89
+ const exhausted = (made, outOfTime, cutInFlight = false) => new ReadRetryExhaustedError({ label, attempts: made, elapsedMs: now() - started, budgetMs: end - started, outOfTime, last, cutInFlight });
90
+ for (let attempt = 1; ; attempt++) {
91
+ const left = end - now();
92
+ if (left <= 0) throw exhausted(attempt - 1, true);
93
+ try {
94
+ return await within(read, left);
95
+ } catch (e) {
96
+ if (e === OUT_OF_TIME) throw exhausted(attempt, true, true);
97
+ if (!transient(e)) throw e;
98
+ last = e;
99
+ if (attempt >= attempts) throw exhausted(attempt, false);
100
+ const ceiling = Math.min(max, base * 2 ** (attempt - 1));
101
+ const delayMs = Math.floor(ceiling / 2 + random() * ceiling / 2);
102
+ if (now() + delayMs >= end) throw exhausted(attempt, true);
103
+ opts.onRetry?.({ label, attempt, delayMs, error: e });
104
+ await sleep(delayMs);
105
+ }
106
+ }
107
+ }
108
+
109
+ // packages/cli/src/verify/nodeReads.ts
110
+ import {
111
+ BlockHash,
112
+ ContractAddress as SdkContractAddress,
113
+ ContractEvent,
114
+ Energy,
115
+ isKnown,
116
+ Parameter,
117
+ ReceiveName,
118
+ RejectReasonTag,
119
+ ReturnValue,
120
+ TransactionEventTag,
121
+ TransactionHash,
122
+ TransactionKindString,
123
+ TransactionStatusEnum,
124
+ TransactionSummaryType
125
+ } from "@concordium/web-sdk";
126
+ function buffer(bytes) {
127
+ const copy = new Uint8Array(bytes.length);
128
+ copy.set(bytes);
129
+ return copy.buffer;
130
+ }
131
+ var bytesOf = (e) => Uint8Array.from(ContractEvent.toBuffer(e));
132
+ var addr = (a) => contractAddress(a.index, a.subindex);
133
+ function txRecordOf(summary, block) {
134
+ const base = {
135
+ ...block,
136
+ calls: [],
137
+ interruptedEvents: [],
138
+ transfers: [],
139
+ accountTransfer: null,
140
+ registeredData: null,
141
+ rejectReason: null,
142
+ rejectCode: null
143
+ };
144
+ if (summary.type !== TransactionSummaryType.AccountTransaction) {
145
+ return { ...base, type: summary.type, sender: "", sponsor: null, costMicroCcd: 0n, ok: true };
146
+ }
147
+ const head = {
148
+ ...base,
149
+ type: summary.transactionType,
150
+ sender: summary.sender.address,
151
+ sponsor: summary.sponsor === void 0 ? null : summary.sponsor.sponsor.address,
152
+ costMicroCcd: summary.sponsor === void 0 ? summary.cost : summary.sponsor.cost.microCcdAmount,
153
+ ok: summary.transactionType !== TransactionKindString.Failed
154
+ };
155
+ switch (summary.transactionType) {
156
+ case TransactionKindString.Failed: {
157
+ const reason = summary.rejectReason;
158
+ const receive = isKnown(reason) && reason.tag === RejectReasonTag.RejectedReceive ? reason : null;
159
+ return {
160
+ ...head,
161
+ rejectReason: isKnown(reason) ? reason.tag : "Unknown",
162
+ rejectCode: receive === null ? null : receive.rejectReason,
163
+ rejectedCall: receive === null || receive.contractAddress === void 0 ? null : { contract: addr(receive.contractAddress), receiveName: ReceiveName.toString(receive.receiveName), parameter: Uint8Array.from(Parameter.toBuffer(receive.parameter)) }
164
+ };
165
+ }
166
+ case TransactionKindString.Update:
167
+ for (const ev of summary.events) {
168
+ if (!isKnown(ev)) continue;
169
+ if (ev.tag === TransactionEventTag.Updated) {
170
+ head.calls.push({
171
+ contract: addr(ev.address),
172
+ receiveName: ReceiveName.toString(ev.receiveName),
173
+ amount: ev.amount.microCcdAmount,
174
+ parameter: Uint8Array.from(Parameter.toBuffer(ev.message)),
175
+ events: ev.events.map(bytesOf)
176
+ });
177
+ } else if (ev.tag === TransactionEventTag.Interrupted) {
178
+ head.interruptedEvents.push({ contract: addr(ev.address), events: ev.events.map(bytesOf) });
179
+ } else if (ev.tag === TransactionEventTag.Transferred) {
180
+ head.transfers.push({ from: addr(ev.from), to: ev.to.address, amount: ev.amount.microCcdAmount });
181
+ }
182
+ }
183
+ return head;
184
+ case TransactionKindString.RegisterData:
185
+ return { ...head, registeredData: fromHex(summary.dataRegistered.data) };
186
+ case TransactionKindString.Transfer:
187
+ case TransactionKindString.TransferWithMemo:
188
+ return { ...head, accountTransfer: { to: summary.transfer.to.address, amount: summary.transfer.amount.microCcdAmount } };
189
+ default:
190
+ return head;
191
+ }
192
+ }
193
+ var NodeVerifyChain = class {
194
+ #client;
195
+ #bureau;
196
+ #readFn;
197
+ constructor(client, bureau, read = (_label, f) => f()) {
198
+ this.#client = client;
199
+ this.#bureau = bureau;
200
+ this.#readFn = read;
201
+ }
202
+ async genesis() {
203
+ return BlockHash.toHexString((await this.#readFn("getConsensusStatus", () => this.#client.getConsensusStatus())).genesisBlock);
204
+ }
205
+ async transaction(hash) {
206
+ let status;
207
+ try {
208
+ status = await this.#readFn(`getBlockItemStatus ${hash.slice(0, 12)}\u2026`, () => this.#client.getBlockItemStatus(TransactionHash.fromHexString(hash)));
209
+ } catch (err) {
210
+ if (err?.code === "NOT_FOUND") return { status: "absent" };
211
+ throw err;
212
+ }
213
+ if (status.status !== TransactionStatusEnum.Finalized) return { status: status.status === TransactionStatusEnum.Committed ? "committed" : "received" };
214
+ const { summary, blockHash } = status.outcome;
215
+ if (!isKnown(summary)) throw new CliError("chain_unreadable", `transaction ${hash}: unknown summary type`);
216
+ const info = await this.#readFn(`getBlockInfo ${BlockHash.toHexString(blockHash).slice(0, 12)}\u2026`, () => this.#client.getBlockInfo(blockHash));
217
+ return {
218
+ status: "finalized",
219
+ tx: txRecordOf(summary, {
220
+ hash,
221
+ blockHash: BlockHash.toHexString(blockHash),
222
+ blockHeight: info.blockHeight,
223
+ parentBlock: BlockHash.toHexString(info.blockParent),
224
+ blockTime: BigInt(info.blockSlotTime.getTime())
225
+ })
226
+ };
227
+ }
228
+ async instanceBalance(contract, blockHash) {
229
+ const info = await this.#readFn(
230
+ `getInstanceInfo <${contract.index},${contract.subindex}>`,
231
+ () => this.#client.getInstanceInfo(SdkContractAddress.create(contract.index, contract.subindex), BlockHash.fromHexString(blockHash))
232
+ );
233
+ return info.amount.microCcdAmount;
234
+ }
235
+ async bureauView(entrypoint, parameter, blockHash) {
236
+ const res = await this.#readFn(
237
+ `${BUREAU_CONTRACT_NAME}.${entrypoint}`,
238
+ () => this.#client.invokeContract(
239
+ {
240
+ contract: SdkContractAddress.create(this.#bureau.index, this.#bureau.subindex),
241
+ method: ReceiveName.fromString(`${BUREAU_CONTRACT_NAME}.${entrypoint}`),
242
+ parameter: Parameter.fromBuffer(buffer(parameter)),
243
+ energy: Energy.create(500000n)
244
+ },
245
+ blockHash === void 0 ? void 0 : BlockHash.fromHexString(blockHash)
246
+ )
247
+ );
248
+ if (res.tag === "failure" || res.returnValue === void 0) throw new CliError("chain_unreadable", `tab_bureau.${entrypoint} view failed`);
249
+ return Uint8Array.from(ReturnValue.toBuffer(res.returnValue));
250
+ }
251
+ };
252
+
253
+ // packages/cli/src/verify/grpc.ts
254
+ var VERIFY_READ_RETRY = { attempts: 12, baseDelayMs: 500, maxDelayMs: 8e3, budgetMs: 6e4 };
255
+ var GrpcVerifyChain = class {
256
+ #node;
257
+ #retry;
258
+ #retries = 0;
259
+ constructor(client, bureau, opts = {}) {
260
+ this.#retry = { ...VERIFY_READ_RETRY, ...opts.retry };
261
+ this.#node = new NodeVerifyChain(client, bureau, (label, read) => this.#read(label, read));
262
+ }
263
+ /** Node reads asked again so far. */
264
+ retries() {
265
+ return this.#retries;
266
+ }
267
+ async #read(label, read) {
268
+ const onRetry = this.#retry.onRetry;
269
+ try {
270
+ return await retryRead(read, {
271
+ ...this.#retry,
272
+ label,
273
+ onRetry: (info) => {
274
+ this.#retries++;
275
+ onRetry?.(info);
276
+ }
277
+ });
278
+ } catch (err) {
279
+ if (err instanceof ReadRetryExhaustedError) throw new CliError("node_unavailable", err.message, { cause: err });
280
+ throw err;
281
+ }
282
+ }
283
+ genesis() {
284
+ return this.#node.genesis();
285
+ }
286
+ transaction(hash) {
287
+ return this.#node.transaction(hash);
288
+ }
289
+ instanceBalance(contract, blockHash) {
290
+ return this.#node.instanceBalance(contract, blockHash);
291
+ }
292
+ bureauView(entrypoint, parameter, blockHash) {
293
+ return this.#node.bureauView(entrypoint, parameter, blockHash);
294
+ }
295
+ };
296
+ export {
297
+ GrpcVerifyChain,
298
+ createTestnetGrpcClient
299
+ };