@pacspace-io/sdk 0.15.1 → 0.15.3
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/dist/index.js +625 -48
- package/dist/index.js.map +4 -4
- package/dist/inputs.txt +2 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -457,7 +457,7 @@ var HttpClient = class {
|
|
|
457
457
|
const headers = {
|
|
458
458
|
"X-Api-Key": this.apiKey,
|
|
459
459
|
"Content-Type": "application/json",
|
|
460
|
-
"User-Agent": "@pacspace-io/sdk/0.15.
|
|
460
|
+
"User-Agent": "@pacspace-io/sdk/0.15.3"
|
|
461
461
|
};
|
|
462
462
|
if (options?.dashboardToken) {
|
|
463
463
|
headers.Authorization = `Bearer ${options.dashboardToken}`;
|
|
@@ -3228,10 +3228,178 @@ function admitRecordEntryV1(layout, entry) {
|
|
|
3228
3228
|
}
|
|
3229
3229
|
|
|
3230
3230
|
// ../shared/src/records/record-seal-history-v1.ts
|
|
3231
|
-
var
|
|
3231
|
+
var import_ethers14 = require("ethers");
|
|
3232
3232
|
|
|
3233
3233
|
// ../shared/src/demo/mirror-node-record-chain-reader.ts
|
|
3234
|
-
var
|
|
3234
|
+
var import_ethers13 = require("ethers");
|
|
3235
|
+
|
|
3236
|
+
// ../shared/src/records/ledger-write-search-v1.ts
|
|
3237
|
+
var LEDGER_WRITE_SEARCH_WINDOW_LIMIT_SECONDS = 7 * 24 * 60 * 60;
|
|
3238
|
+
var LEDGER_WRITE_SEARCH_PAGE_LIMIT = 100;
|
|
3239
|
+
var MIRROR_ANSWER_MAX_BYTES = 1048576;
|
|
3240
|
+
var HEX40 = /^0x[0-9a-f]{40}$/;
|
|
3241
|
+
var HEX642 = /^0x[0-9a-f]{64}$/;
|
|
3242
|
+
var HEX_DATA = /^0x[0-9a-f]*$/;
|
|
3243
|
+
var TIMESTAMP = /^\d+(\.\d+)?$/;
|
|
3244
|
+
var REFUSAL_CODES = {
|
|
3245
|
+
redirect: true,
|
|
3246
|
+
"too-large": true,
|
|
3247
|
+
"too-many-logs": true,
|
|
3248
|
+
"next-page": true,
|
|
3249
|
+
"too-slow": true,
|
|
3250
|
+
"too-long": true
|
|
3251
|
+
};
|
|
3252
|
+
var MIRROR_REFUSAL_CODES = Object.keys(REFUSAL_CODES);
|
|
3253
|
+
var MirrorAnswerRefused = class extends Error {
|
|
3254
|
+
constructor(code, message) {
|
|
3255
|
+
super(message);
|
|
3256
|
+
this.name = "MirrorAnswerRefused";
|
|
3257
|
+
this.code = code;
|
|
3258
|
+
}
|
|
3259
|
+
};
|
|
3260
|
+
function mirrorRefusalOf(error) {
|
|
3261
|
+
if (!error || typeof error !== "object") return null;
|
|
3262
|
+
const { name, code } = error;
|
|
3263
|
+
return name === "MirrorAnswerRefused" && typeof code === "string" && Object.prototype.hasOwnProperty.call(REFUSAL_CODES, code) ? code : null;
|
|
3264
|
+
}
|
|
3265
|
+
function pathLabel(path) {
|
|
3266
|
+
return path ? ` (${path.split("?")[0]})` : "";
|
|
3267
|
+
}
|
|
3268
|
+
var mirrorRefusal = {
|
|
3269
|
+
redirect: (path) => new MirrorAnswerRefused("redirect", `mirror node answered with a redirect, which is not followed${pathLabel(path)}`),
|
|
3270
|
+
tooLarge: (maxBytes, path) => new MirrorAnswerRefused("too-large", `mirror node answer is larger than ${maxBytes} bytes${pathLabel(path)}`),
|
|
3271
|
+
tooManyLogs: (asked, path) => new MirrorAnswerRefused("too-many-logs", `mirror node returned more logs than the ${asked} asked for${pathLabel(path)}`),
|
|
3272
|
+
nextPage: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that is not this contract's log"),
|
|
3273
|
+
/** A page whose logs do not come after the last log read. */
|
|
3274
|
+
notForward: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that does not follow the last"),
|
|
3275
|
+
scanTooSlow: (budgetMs) => new MirrorAnswerRefused("too-slow", `mirror node log scan did not finish in ${budgetMs}ms`),
|
|
3276
|
+
scanTooManyRequests: (requests) => new MirrorAnswerRefused("too-long", `mirror node log scan passed ${requests} requests`),
|
|
3277
|
+
scanTooManyLogs: (logs) => new MirrorAnswerRefused("too-long", `mirror node log scan kept more than ${logs} logs`)
|
|
3278
|
+
};
|
|
3279
|
+
var rpcRefusal = {
|
|
3280
|
+
redirect: () => new MirrorAnswerRefused("redirect", "RPC endpoint answered with a redirect, which is not followed"),
|
|
3281
|
+
tooLarge: (maxBytes) => new MirrorAnswerRefused("too-large", `RPC endpoint answer is larger than ${maxBytes} bytes`),
|
|
3282
|
+
scanTooSlow: (budgetMs) => new MirrorAnswerRefused("too-slow", `RPC log scan did not finish in ${budgetMs}ms`),
|
|
3283
|
+
scanTooManyLogs: (logs) => new MirrorAnswerRefused("too-long", `RPC log scan kept more than ${logs} logs`)
|
|
3284
|
+
};
|
|
3285
|
+
var LOG_SCAN_BUDGET_TIMEOUTS = 60;
|
|
3286
|
+
var LOG_SCAN_MAX_REQUESTS = 1e4;
|
|
3287
|
+
var LOG_SCAN_MAX_KEPT_LOGS = 1e6;
|
|
3288
|
+
var KEPT_LOG_DATA_MAX_CHARS = 2 + 64 * 3;
|
|
3289
|
+
var KEPT_LOG_MAX_TOPICS = 3;
|
|
3290
|
+
function isMirrorRedirect(response) {
|
|
3291
|
+
return response.redirected === true || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400;
|
|
3292
|
+
}
|
|
3293
|
+
async function readMirrorText(response, maxBytes = MIRROR_ANSWER_MAX_BYTES, path) {
|
|
3294
|
+
const declared = Number(response.headers?.get?.("content-length") ?? Number.NaN);
|
|
3295
|
+
const body = response.body;
|
|
3296
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
3297
|
+
await body?.cancel?.().catch(() => void 0);
|
|
3298
|
+
throw mirrorRefusal.tooLarge(maxBytes, path);
|
|
3299
|
+
}
|
|
3300
|
+
if (body && typeof body.getReader === "function") {
|
|
3301
|
+
const reader = body.getReader();
|
|
3302
|
+
const decoder = new TextDecoder();
|
|
3303
|
+
let text2 = "";
|
|
3304
|
+
let read = 0;
|
|
3305
|
+
for (; ; ) {
|
|
3306
|
+
const { done, value } = await reader.read();
|
|
3307
|
+
if (done) break;
|
|
3308
|
+
read += value.byteLength;
|
|
3309
|
+
if (read > maxBytes) {
|
|
3310
|
+
await reader.cancel().catch(() => void 0);
|
|
3311
|
+
throw mirrorRefusal.tooLarge(maxBytes, path);
|
|
3312
|
+
}
|
|
3313
|
+
text2 += decoder.decode(value, { stream: true });
|
|
3314
|
+
}
|
|
3315
|
+
return text2 + decoder.decode();
|
|
3316
|
+
}
|
|
3317
|
+
const text = await response.text();
|
|
3318
|
+
if (new TextEncoder().encode(text).byteLength > maxBytes) throw mirrorRefusal.tooLarge(maxBytes, path);
|
|
3319
|
+
return text;
|
|
3320
|
+
}
|
|
3321
|
+
async function readMirrorJson(response, maxBytes = MIRROR_ANSWER_MAX_BYTES, path) {
|
|
3322
|
+
return JSON.parse(await readMirrorText(response, maxBytes, path));
|
|
3323
|
+
}
|
|
3324
|
+
function contractLogPath(contractAddress) {
|
|
3325
|
+
return `/api/v1/contracts/${contractAddress}/results/logs`;
|
|
3326
|
+
}
|
|
3327
|
+
function ledgerWriteSearchPath(input) {
|
|
3328
|
+
const query = `topic0=${input.topic0}&topic1=${input.recordKey}×tamp=gte:${input.lower}×tamp=lt:${input.upper}&order=desc&limit=${LEDGER_WRITE_SEARCH_PAGE_LIMIT}`;
|
|
3329
|
+
return `${contractLogPath(input.contractAddress)}?${query}`;
|
|
3330
|
+
}
|
|
3331
|
+
function nextLogPath(next, source) {
|
|
3332
|
+
if (typeof next !== "string" || next === "") return null;
|
|
3333
|
+
const contract = source.contract.toLowerCase();
|
|
3334
|
+
if (!HEX40.test(contract)) return null;
|
|
3335
|
+
if (!/^[\x21-\x5b\x5d-\x7e]+$/.test(next)) return null;
|
|
3336
|
+
if (next.startsWith("//")) return null;
|
|
3337
|
+
let base;
|
|
3338
|
+
let url;
|
|
3339
|
+
try {
|
|
3340
|
+
base = new URL(source.base);
|
|
3341
|
+
url = new URL(next, `${base.origin}/`);
|
|
3342
|
+
} catch {
|
|
3343
|
+
return null;
|
|
3344
|
+
}
|
|
3345
|
+
if (base.protocol !== "https:" && base.protocol !== "http:") return null;
|
|
3346
|
+
if (url.origin !== base.origin || url.username !== "" || url.password !== "" || url.hash !== "" || next.includes("#")) return null;
|
|
3347
|
+
const written = (next.startsWith("/") ? next : next.slice(next.indexOf("/", next.indexOf("//") + 2))).split("?")[0];
|
|
3348
|
+
if (/(^|\/)\.{1,2}(\/|$)/.test(written) || /%2e/i.test(written) || written !== url.pathname) return null;
|
|
3349
|
+
if (url.search.length < 2) return null;
|
|
3350
|
+
const logs = contractLogPath(contract);
|
|
3351
|
+
const prefix = base.pathname.replace(/\/+$/, "");
|
|
3352
|
+
const path = url.pathname.toLowerCase();
|
|
3353
|
+
if (path !== logs && !(prefix !== "" && url.pathname.startsWith(`${prefix}/`) && url.pathname.slice(prefix.length).toLowerCase() === logs)) return null;
|
|
3354
|
+
return `${logs}${url.search}`;
|
|
3355
|
+
}
|
|
3356
|
+
function withLogPageLimit(path, limit) {
|
|
3357
|
+
const at = path.indexOf("?");
|
|
3358
|
+
const before = at === -1 ? path : path.slice(0, at);
|
|
3359
|
+
const parts = at === -1 ? [] : path.slice(at + 1).split("&").filter((part) => part !== "");
|
|
3360
|
+
let placed = false;
|
|
3361
|
+
const out = [];
|
|
3362
|
+
for (const part of parts) {
|
|
3363
|
+
if (!part.startsWith("limit=")) out.push(part);
|
|
3364
|
+
else if (!placed) {
|
|
3365
|
+
out.push(`limit=${limit}`);
|
|
3366
|
+
placed = true;
|
|
3367
|
+
}
|
|
3368
|
+
}
|
|
3369
|
+
if (!placed) out.push(`limit=${limit}`);
|
|
3370
|
+
return `${before}?${out.join("&")}`;
|
|
3371
|
+
}
|
|
3372
|
+
function parseLedgerWriteLog(log, expected) {
|
|
3373
|
+
if (!log || typeof log !== "object") return null;
|
|
3374
|
+
const raw = log;
|
|
3375
|
+
const address = typeof raw.address === "string" ? raw.address.toLowerCase() : "";
|
|
3376
|
+
if (!HEX40.test(address) || address !== String(expected.contractAddress).toLowerCase()) return null;
|
|
3377
|
+
const topics = Array.isArray(raw.topics) ? raw.topics.map((topic) => String(topic).toLowerCase()) : [];
|
|
3378
|
+
if (topics[0] !== expected.topic0 || topics[1] !== expected.recordKey) return null;
|
|
3379
|
+
const data = typeof raw.data === "string" ? raw.data.toLowerCase() : "";
|
|
3380
|
+
const transactionHash = typeof raw.transaction_hash === "string" ? raw.transaction_hash.toLowerCase() : "";
|
|
3381
|
+
const timestamp = typeof raw.timestamp === "string" ? raw.timestamp : "";
|
|
3382
|
+
if (!HEX_DATA.test(data) || data.length < 2 + 64 * 3) return null;
|
|
3383
|
+
if (!HEX642.test(transactionHash) || !TIMESTAMP.test(timestamp)) return null;
|
|
3384
|
+
const encodingVersion = Number.parseInt(data.slice(2, 2 + 64).slice(-8), 16);
|
|
3385
|
+
const previousWord = data.slice(2 + 64, 2 + 64 * 2);
|
|
3386
|
+
const newWord = data.slice(2 + 64 * 2, 2 + 64 * 3);
|
|
3387
|
+
const [seconds, fraction = ""] = timestamp.split(".");
|
|
3388
|
+
const ms = Number(seconds) * 1e3 + Number(fraction.slice(0, 3).padEnd(3, "0"));
|
|
3389
|
+
if (!Number.isFinite(ms) || Math.abs(ms) > 864e13) return null;
|
|
3390
|
+
return {
|
|
3391
|
+
transactionHash,
|
|
3392
|
+
timestamp,
|
|
3393
|
+
committedAt: new Date(ms).toISOString(),
|
|
3394
|
+
previousWord: `0x${previousWord}`,
|
|
3395
|
+
newWord: `0x${newWord}`,
|
|
3396
|
+
operator: HEX642.test(topics[2] ?? "") ? `0x${topics[2].slice(26)}` : "",
|
|
3397
|
+
encodingVersion,
|
|
3398
|
+
address,
|
|
3399
|
+
blockNumber: Number.isSafeInteger(raw.block_number) ? raw.block_number : null,
|
|
3400
|
+
logIndex: Number.isSafeInteger(raw.index) ? raw.index : null
|
|
3401
|
+
};
|
|
3402
|
+
}
|
|
3235
3403
|
|
|
3236
3404
|
// ../shared/src/records/inspect-record-calldata-v1.ts
|
|
3237
3405
|
var MIRROR_NODE_BY_CHAIN = Object.freeze({
|
|
@@ -3240,6 +3408,9 @@ var MIRROR_NODE_BY_CHAIN = Object.freeze({
|
|
|
3240
3408
|
});
|
|
3241
3409
|
|
|
3242
3410
|
// ../shared/src/demo/independent-verify-records.ts
|
|
3411
|
+
var import_ethers12 = require("ethers");
|
|
3412
|
+
|
|
3413
|
+
// ../shared/src/chain/rpc-guarded-send.ts
|
|
3243
3414
|
var import_ethers11 = require("ethers");
|
|
3244
3415
|
|
|
3245
3416
|
// ../shared/src/chain/rpc-provider.ts
|
|
@@ -3440,14 +3611,35 @@ async function guardSubscriptionSend(method, send, provider, retry, secrets) {
|
|
|
3440
3611
|
}
|
|
3441
3612
|
}
|
|
3442
3613
|
}
|
|
3614
|
+
function requestFor(url, options) {
|
|
3615
|
+
const request = new import_ethers10.FetchRequest(url);
|
|
3616
|
+
if (options.timeoutMs !== void 0) request.timeout = options.timeoutMs;
|
|
3617
|
+
options.prepareRequest?.(request);
|
|
3618
|
+
return request;
|
|
3619
|
+
}
|
|
3620
|
+
var CHAIN_ID_RESULT = /^0x[0-9a-f]{1,13}$/i;
|
|
3621
|
+
async function readRpcChainId(url, options = {}) {
|
|
3622
|
+
const secrets = rpcUrlSecrets(url);
|
|
3623
|
+
try {
|
|
3624
|
+
const request = requestFor(url, options);
|
|
3625
|
+
request.body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_chainId", params: [] });
|
|
3626
|
+
request.setHeader("content-type", "application/json");
|
|
3627
|
+
const response = await request.send();
|
|
3628
|
+
response.assertOk();
|
|
3629
|
+
const answer = response.bodyJson;
|
|
3630
|
+
const result = answer !== null && typeof answer === "object" ? answer.result : void 0;
|
|
3631
|
+
if (typeof result !== "string" || !CHAIN_ID_RESULT.test(result)) throw new RpcResultUnavailableError("eth_chainId", "not a chain id");
|
|
3632
|
+
return Number.parseInt(result, 16);
|
|
3633
|
+
} catch (error) {
|
|
3634
|
+
throw redactRpcError(error, secrets);
|
|
3635
|
+
}
|
|
3636
|
+
}
|
|
3443
3637
|
var RedactingJsonRpcProvider = class extends import_ethers10.JsonRpcProvider {
|
|
3444
3638
|
#secrets;
|
|
3445
3639
|
#subscriptionRetry;
|
|
3446
3640
|
constructor(url, network, options) {
|
|
3447
|
-
const { timeoutMs, subscriptionRetry, ...providerOptions } = options;
|
|
3448
|
-
|
|
3449
|
-
if (timeoutMs !== void 0) request.timeout = timeoutMs;
|
|
3450
|
-
super(request, network, providerOptions);
|
|
3641
|
+
const { timeoutMs, subscriptionRetry, prepareRequest, ...providerOptions } = options;
|
|
3642
|
+
super(requestFor(url, { timeoutMs, prepareRequest }), network, providerOptions);
|
|
3451
3643
|
this.#secrets = rpcUrlSecrets(url);
|
|
3452
3644
|
this.#subscriptionRetry = subscriptionRetry ?? {};
|
|
3453
3645
|
}
|
|
@@ -3484,6 +3676,100 @@ function createRpcProvider(url, network, options = {}) {
|
|
|
3484
3676
|
return new RedactingJsonRpcProvider(url, network, options);
|
|
3485
3677
|
}
|
|
3486
3678
|
|
|
3679
|
+
// ../shared/src/chain/rpc-guarded-send.ts
|
|
3680
|
+
var RPC_READER_MAX_TRIES = 3;
|
|
3681
|
+
function basicAuthorization(username, password) {
|
|
3682
|
+
const decoded = (value) => {
|
|
3683
|
+
try {
|
|
3684
|
+
return decodeURIComponent(value);
|
|
3685
|
+
} catch {
|
|
3686
|
+
return value;
|
|
3687
|
+
}
|
|
3688
|
+
};
|
|
3689
|
+
const bytes2 = new TextEncoder().encode(`${decoded(username)}:${decoded(password)}`);
|
|
3690
|
+
let binary = "";
|
|
3691
|
+
for (const byte of bytes2) binary += String.fromCharCode(byte);
|
|
3692
|
+
return `Basic ${btoa(binary)}`;
|
|
3693
|
+
}
|
|
3694
|
+
function createGuardedRpcSend(options = {}) {
|
|
3695
|
+
const maxBytes = options.maxBytes ?? MIRROR_ANSWER_MAX_BYTES;
|
|
3696
|
+
return async (req, signal) => {
|
|
3697
|
+
if (signal?.cancelled) throw (0, import_ethers11.makeError)("request cancelled before sending", "CANCELLED");
|
|
3698
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
3699
|
+
const secrets = rpcUrlSecrets(req.url);
|
|
3700
|
+
const url = new URL(req.url);
|
|
3701
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
3702
|
+
throw (0, import_ethers11.makeError)(`unsupported protocol ${url.protocol.replace(/:$/, "")}`, "UNSUPPORTED_OPERATION", { operation: "request" });
|
|
3703
|
+
}
|
|
3704
|
+
const headers = {};
|
|
3705
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
3706
|
+
const lower = name.toLowerCase();
|
|
3707
|
+
if (lower === "content-length" || lower === "accept-encoding") continue;
|
|
3708
|
+
headers[lower] = value;
|
|
3709
|
+
}
|
|
3710
|
+
if (url.username !== "" || url.password !== "") {
|
|
3711
|
+
if (headers.authorization === void 0) headers.authorization = basicAuthorization(url.username, url.password);
|
|
3712
|
+
url.username = "";
|
|
3713
|
+
url.password = "";
|
|
3714
|
+
}
|
|
3715
|
+
const controller = new AbortController();
|
|
3716
|
+
let timedOut = false;
|
|
3717
|
+
const timer = setTimeout(() => {
|
|
3718
|
+
timedOut = true;
|
|
3719
|
+
controller.abort();
|
|
3720
|
+
}, req.timeout);
|
|
3721
|
+
let cancelled = false;
|
|
3722
|
+
signal?.addListener(() => {
|
|
3723
|
+
cancelled = true;
|
|
3724
|
+
controller.abort();
|
|
3725
|
+
});
|
|
3726
|
+
try {
|
|
3727
|
+
const body = req.body;
|
|
3728
|
+
const response = await fetchImpl(url.toString(), {
|
|
3729
|
+
method: req.method,
|
|
3730
|
+
headers,
|
|
3731
|
+
...body ? { body } : {},
|
|
3732
|
+
redirect: "manual",
|
|
3733
|
+
signal: controller.signal
|
|
3734
|
+
});
|
|
3735
|
+
if (isMirrorRedirect(response)) {
|
|
3736
|
+
await response.body?.cancel?.().catch(() => void 0);
|
|
3737
|
+
throw rpcRefusal.redirect();
|
|
3738
|
+
}
|
|
3739
|
+
let text;
|
|
3740
|
+
try {
|
|
3741
|
+
text = await readMirrorText(response, maxBytes);
|
|
3742
|
+
} catch (error) {
|
|
3743
|
+
if (mirrorRefusalOf(error) === "too-large") throw rpcRefusal.tooLarge(maxBytes);
|
|
3744
|
+
throw error;
|
|
3745
|
+
}
|
|
3746
|
+
const answered = {};
|
|
3747
|
+
response.headers.forEach((value, name) => {
|
|
3748
|
+
answered[name.toLowerCase()] = value;
|
|
3749
|
+
});
|
|
3750
|
+
return { statusCode: response.status, statusMessage: response.statusText, headers: answered, body: new TextEncoder().encode(replaceRpcSecrets(text, secrets)) };
|
|
3751
|
+
} catch (error) {
|
|
3752
|
+
if (mirrorRefusalOf(error)) throw error;
|
|
3753
|
+
if (cancelled) throw (0, import_ethers11.makeError)("request cancelled", "CANCELLED");
|
|
3754
|
+
if (timedOut) throw (0, import_ethers11.makeError)("request timeout", "TIMEOUT", { operation: "request.send", reason: "timeout" });
|
|
3755
|
+
throw error;
|
|
3756
|
+
} finally {
|
|
3757
|
+
clearTimeout(timer);
|
|
3758
|
+
}
|
|
3759
|
+
};
|
|
3760
|
+
}
|
|
3761
|
+
function retryAfterMs(value) {
|
|
3762
|
+
return typeof value === "string" && /^[1-9][0-9]*$/.test(value) ? Number.parseInt(value, 10) : null;
|
|
3763
|
+
}
|
|
3764
|
+
function holdRpcRequest(request, options = {}) {
|
|
3765
|
+
request.getUrlFunc = createGuardedRpcSend(options);
|
|
3766
|
+
request.retryFunc = async (req, response, attempt) => {
|
|
3767
|
+
if (attempt >= RPC_READER_MAX_TRIES - 1) return false;
|
|
3768
|
+
const wait = retryAfterMs(response.headers["retry-after"]);
|
|
3769
|
+
return wait === null || wait <= req.timeout;
|
|
3770
|
+
};
|
|
3771
|
+
}
|
|
3772
|
+
|
|
3487
3773
|
// ../shared/src/demo/independent-verify-records.ts
|
|
3488
3774
|
var RECORD_LANE_ABI_V38 = [
|
|
3489
3775
|
"function getRecord(bytes32 recordKey) view returns (uint256)",
|
|
@@ -3495,18 +3781,20 @@ var RECORD_LANE_ABI_V38 = [
|
|
|
3495
3781
|
"event RecordWritten(bytes32 indexed recordKey, address indexed operator, uint8 encodingVersion, uint256 previousWord, uint256 newWord)",
|
|
3496
3782
|
"event LedgerHeadAdvanced(uint256 indexed batchId, bytes32 merkleRoot, bytes32 previousHead, bytes32 newHead)"
|
|
3497
3783
|
];
|
|
3498
|
-
var LEDGER_HEAD_ADVANCED_TOPIC =
|
|
3499
|
-
var RECORD_WRITTEN_TOPIC =
|
|
3784
|
+
var LEDGER_HEAD_ADVANCED_TOPIC = import_ethers12.ethers.id("LedgerHeadAdvanced(uint256,bytes32,bytes32,bytes32)");
|
|
3785
|
+
var RECORD_WRITTEN_TOPIC = import_ethers12.ethers.id("RecordWritten(bytes32,address,uint8,uint256,uint256)");
|
|
3500
3786
|
function normalizeRpcUrl(url) {
|
|
3501
3787
|
const trimmed = String(url || "").trim();
|
|
3502
3788
|
if (trimmed.startsWith("wss://")) return trimmed.replace(/^wss:\/\//, "https://");
|
|
3503
3789
|
if (trimmed.startsWith("ws://")) return trimmed.replace(/^ws:\/\//, "http://");
|
|
3504
3790
|
return trimmed;
|
|
3505
3791
|
}
|
|
3792
|
+
var ReadTimedOut = class extends Error {
|
|
3793
|
+
};
|
|
3506
3794
|
async function withTimeout(p, ms, label) {
|
|
3507
3795
|
let timer;
|
|
3508
3796
|
const timeout = new Promise((_, reject) => {
|
|
3509
|
-
timer = setTimeout(() => reject(new
|
|
3797
|
+
timer = setTimeout(() => reject(new ReadTimedOut(`${label} timed out after ${ms}ms`)), ms);
|
|
3510
3798
|
});
|
|
3511
3799
|
try {
|
|
3512
3800
|
return await Promise.race([p, timeout]);
|
|
@@ -3517,24 +3805,71 @@ async function withTimeout(p, ms, label) {
|
|
|
3517
3805
|
function createRpcRecordChainReader(options) {
|
|
3518
3806
|
const rpcUrl = normalizeRpcUrl(options.rpcUrl);
|
|
3519
3807
|
if (!rpcUrl) throw new Error("rpcUrl is required.");
|
|
3520
|
-
const contractAddress =
|
|
3808
|
+
const contractAddress = import_ethers12.ethers.getAddress(options.contractAddress).toLowerCase();
|
|
3521
3809
|
const timeoutMs = Number(options.timeoutMs || 1e4);
|
|
3522
3810
|
const chunk = Math.max(1, Number(options.logsChunkSize || 2e3));
|
|
3523
|
-
const
|
|
3524
|
-
const
|
|
3525
|
-
const
|
|
3526
|
-
const
|
|
3811
|
+
const now = options.scan?.now ?? Date.now;
|
|
3812
|
+
const maxKeptLogs = options.scan?.maxKeptLogs ?? LOG_SCAN_MAX_KEPT_LOGS;
|
|
3813
|
+
const iface = new import_ethers12.ethers.Interface(RECORD_LANE_ABI_V38);
|
|
3814
|
+
const prepareRequest = (request) => holdRpcRequest(request);
|
|
3815
|
+
const endpointFor = (chainId) => {
|
|
3816
|
+
const network = new import_ethers12.ethers.Network(`chain-${chainId}`, chainId);
|
|
3817
|
+
const provider = createRpcProvider(rpcUrl, network, { staticNetwork: network, timeoutMs, prepareRequest });
|
|
3818
|
+
return { provider, contract: new import_ethers12.ethers.Contract(contractAddress, RECORD_LANE_ABI_V38, provider) };
|
|
3819
|
+
};
|
|
3820
|
+
let ready = options.chainId != null ? Promise.resolve(endpointFor(options.chainId)) : null;
|
|
3821
|
+
function endpoint() {
|
|
3822
|
+
if (!ready) {
|
|
3823
|
+
const pending = readRpcChainId(rpcUrl, { timeoutMs, prepareRequest }).then(endpointFor);
|
|
3824
|
+
ready = pending;
|
|
3825
|
+
pending.catch(() => {
|
|
3826
|
+
if (ready === pending) ready = null;
|
|
3827
|
+
});
|
|
3828
|
+
}
|
|
3829
|
+
return ready;
|
|
3830
|
+
}
|
|
3831
|
+
function keptLog(log, topic0) {
|
|
3832
|
+
return String(log.address).toLowerCase() === contractAddress && log.topics.length <= KEPT_LOG_MAX_TOPICS && String(log.topics[0] ?? "").toLowerCase() === topic0 && typeof log.data === "string" && log.data.length <= KEPT_LOG_DATA_MAX_CHARS;
|
|
3833
|
+
}
|
|
3527
3834
|
async function scanLogs(topics, fromBlock, toBlock, label) {
|
|
3528
|
-
const
|
|
3835
|
+
const { provider } = await endpoint();
|
|
3836
|
+
const budgetMs = LOG_SCAN_BUDGET_TIMEOUTS * timeoutMs;
|
|
3837
|
+
const deadline = now() + budgetMs;
|
|
3838
|
+
const topic0 = String(topics[0] ?? "").toLowerCase();
|
|
3839
|
+
const ask = async (send, what) => {
|
|
3840
|
+
const left = deadline - now();
|
|
3841
|
+
if (left <= 0) throw rpcRefusal.scanTooSlow(budgetMs);
|
|
3842
|
+
const allowed = Math.min(timeoutMs, left);
|
|
3843
|
+
try {
|
|
3844
|
+
return await withTimeout(send(), allowed, what);
|
|
3845
|
+
} catch (error) {
|
|
3846
|
+
if (error instanceof ReadTimedOut && allowed < timeoutMs) throw rpcRefusal.scanTooSlow(budgetMs);
|
|
3847
|
+
if (!mirrorRefusalOf(error) && now() >= deadline) throw rpcRefusal.scanTooSlow(budgetMs);
|
|
3848
|
+
throw error;
|
|
3849
|
+
}
|
|
3850
|
+
};
|
|
3851
|
+
const latest = toBlock === "latest" ? await ask(() => provider.getBlockNumber(), "getBlockNumber") : toBlock;
|
|
3529
3852
|
const out = [];
|
|
3853
|
+
const pending = [];
|
|
3530
3854
|
for (let start = fromBlock; start <= latest; start += chunk) {
|
|
3531
|
-
|
|
3532
|
-
|
|
3533
|
-
|
|
3534
|
-
|
|
3535
|
-
|
|
3536
|
-
|
|
3537
|
-
|
|
3855
|
+
pending.push([start, Math.min(latest, start + chunk - 1)]);
|
|
3856
|
+
while (pending.length > 0) {
|
|
3857
|
+
const [from, to] = pending.pop();
|
|
3858
|
+
let logs;
|
|
3859
|
+
try {
|
|
3860
|
+
logs = await ask(() => provider.getLogs({ address: contractAddress, topics, fromBlock: from, toBlock: to }), `getLogs ${label} (${from}-${to})`);
|
|
3861
|
+
} catch (error) {
|
|
3862
|
+
if (mirrorRefusalOf(error) !== "too-large" || from >= to) throw error;
|
|
3863
|
+
const middle = from + Math.floor((to - from) / 2);
|
|
3864
|
+
pending.push([middle + 1, to], [from, middle]);
|
|
3865
|
+
continue;
|
|
3866
|
+
}
|
|
3867
|
+
for (const log of logs) {
|
|
3868
|
+
if (!keptLog(log, topic0)) continue;
|
|
3869
|
+
if (out.length >= maxKeptLogs) throw rpcRefusal.scanTooManyLogs(maxKeptLogs);
|
|
3870
|
+
out.push(log);
|
|
3871
|
+
}
|
|
3872
|
+
}
|
|
3538
3873
|
}
|
|
3539
3874
|
return out;
|
|
3540
3875
|
}
|
|
@@ -3542,10 +3877,12 @@ function createRpcRecordChainReader(options) {
|
|
|
3542
3877
|
contractAddress,
|
|
3543
3878
|
async getRecord(recordKey) {
|
|
3544
3879
|
const key = normalizeProofHash(recordKey, "recordKey");
|
|
3880
|
+
const { contract } = await endpoint();
|
|
3545
3881
|
const word = await withTimeout(contract.getRecord(key), timeoutMs, "getRecord");
|
|
3546
3882
|
return hex256(BigInt(word));
|
|
3547
3883
|
},
|
|
3548
3884
|
async getLayout(layoutId) {
|
|
3885
|
+
const { contract } = await endpoint();
|
|
3549
3886
|
const l = await withTimeout(contract.getLayout(layoutId), timeoutMs, "getLayout");
|
|
3550
3887
|
return {
|
|
3551
3888
|
layoutDigest: String(l[0]).toLowerCase(),
|
|
@@ -3555,10 +3892,12 @@ function createRpcRecordChainReader(options) {
|
|
|
3555
3892
|
};
|
|
3556
3893
|
},
|
|
3557
3894
|
async getBatchRoot(batchId) {
|
|
3895
|
+
const { contract } = await endpoint();
|
|
3558
3896
|
const root = await withTimeout(contract.getBatchRoot(BigInt(batchId)), timeoutMs, "getBatchRoot");
|
|
3559
3897
|
return normalizeProofHash(String(root), "observedProofRoot");
|
|
3560
3898
|
},
|
|
3561
3899
|
async getLedgerHead() {
|
|
3900
|
+
const { contract } = await endpoint();
|
|
3562
3901
|
const head = await withTimeout(contract.getLedgerHead(), timeoutMs, "getLedgerHead");
|
|
3563
3902
|
return normalizeProofHash(String(head), "ledgerHead");
|
|
3564
3903
|
},
|
|
@@ -3598,46 +3937,171 @@ function createRpcRecordChainReader(options) {
|
|
|
3598
3937
|
});
|
|
3599
3938
|
}
|
|
3600
3939
|
return out;
|
|
3940
|
+
},
|
|
3941
|
+
async findRecordWrites(recordKey, search) {
|
|
3942
|
+
const key = normalizeProofHash(recordKey, "recordKey");
|
|
3943
|
+
const now2 = search.now ?? Date.now;
|
|
3944
|
+
const deadline = now2() + search.budgetMs;
|
|
3945
|
+
const writes = [];
|
|
3946
|
+
const blockTimes = /* @__PURE__ */ new Map();
|
|
3947
|
+
let requests = 0;
|
|
3948
|
+
const CUT = Symbol("cut");
|
|
3949
|
+
const within = async (p) => {
|
|
3950
|
+
const left = deadline - now2();
|
|
3951
|
+
if (left <= 0) return CUT;
|
|
3952
|
+
let timer;
|
|
3953
|
+
const cut = new Promise((resolve) => {
|
|
3954
|
+
timer = setTimeout(() => resolve(CUT), left);
|
|
3955
|
+
});
|
|
3956
|
+
p.catch(() => void 0);
|
|
3957
|
+
try {
|
|
3958
|
+
return await Promise.race([p, cut]);
|
|
3959
|
+
} finally {
|
|
3960
|
+
if (timer) clearTimeout(timer);
|
|
3961
|
+
}
|
|
3962
|
+
};
|
|
3963
|
+
const end = (ended) => ({ writes, ended, requests });
|
|
3964
|
+
if (search.maxRequests < 1) return end("limit");
|
|
3965
|
+
const found = await within(endpoint());
|
|
3966
|
+
if (found === CUT) return end("timeout");
|
|
3967
|
+
const { provider } = found;
|
|
3968
|
+
requests += 1;
|
|
3969
|
+
const latest = await within(provider.getBlockNumber());
|
|
3970
|
+
if (latest === CUT) return end("timeout");
|
|
3971
|
+
for (let to = latest; to >= 0; to -= chunk) {
|
|
3972
|
+
if (search.done(writes)) return end("done");
|
|
3973
|
+
if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
|
|
3974
|
+
requests += 1;
|
|
3975
|
+
const logs = await within(provider.getLogs({ address: contractAddress, topics: [RECORD_WRITTEN_TOPIC, key], fromBlock: Math.max(0, to - chunk + 1), toBlock: to }));
|
|
3976
|
+
if (logs === CUT) return end("timeout");
|
|
3977
|
+
for (const log of [...logs].reverse()) {
|
|
3978
|
+
const parsed = iface.parseLog({ topics: [...log.topics], data: log.data });
|
|
3979
|
+
if (!parsed) continue;
|
|
3980
|
+
let committedAt = blockTimes.get(log.blockNumber);
|
|
3981
|
+
if (committedAt === void 0) {
|
|
3982
|
+
if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
|
|
3983
|
+
requests += 1;
|
|
3984
|
+
const block = await within(provider.getBlock(log.blockNumber));
|
|
3985
|
+
if (block === CUT) return end("timeout");
|
|
3986
|
+
if (!block || !Number.isSafeInteger(block.timestamp)) throw new Error(`getBlock ${log.blockNumber} returned no time`);
|
|
3987
|
+
committedAt = new Date(block.timestamp * 1e3).toISOString();
|
|
3988
|
+
blockTimes.set(log.blockNumber, committedAt);
|
|
3989
|
+
}
|
|
3990
|
+
writes.push({
|
|
3991
|
+
previousWord: hex256(BigInt(parsed.args.previousWord)),
|
|
3992
|
+
newWord: hex256(BigInt(parsed.args.newWord)),
|
|
3993
|
+
operator: String(parsed.args.operator).toLowerCase(),
|
|
3994
|
+
encodingVersion: Number(parsed.args.encodingVersion),
|
|
3995
|
+
blockNumber: log.blockNumber,
|
|
3996
|
+
transactionHash: String(log.transactionHash).toLowerCase(),
|
|
3997
|
+
logIndex: log.index,
|
|
3998
|
+
committedAt,
|
|
3999
|
+
contractAddress: String(log.address).toLowerCase()
|
|
4000
|
+
});
|
|
4001
|
+
}
|
|
4002
|
+
}
|
|
4003
|
+
return end(search.done(writes) ? "done" : "limit");
|
|
3601
4004
|
}
|
|
3602
4005
|
};
|
|
3603
4006
|
}
|
|
3604
4007
|
|
|
3605
4008
|
// ../shared/src/demo/mirror-node-record-chain-reader.ts
|
|
4009
|
+
var RECORD_WRITE_SEARCH_WINDOW_SECONDS = 6 * 24 * 60 * 60;
|
|
4010
|
+
var DAY_SECONDS = 24 * 60 * 60;
|
|
4011
|
+
var CONSENSUS_TIMESTAMP = /^\d{1,12}\.\d{9}$/;
|
|
4012
|
+
function committedAtOf(timestamp) {
|
|
4013
|
+
if (typeof timestamp !== "string" || !CONSENSUS_TIMESTAMP.test(timestamp)) return void 0;
|
|
4014
|
+
const [seconds, fraction] = timestamp.split(".");
|
|
4015
|
+
return new Date(Number(seconds) * 1e3 + Number(fraction.slice(0, 3))).toISOString();
|
|
4016
|
+
}
|
|
4017
|
+
var KEPT_TOPICS = [RECORD_WRITTEN_TOPIC.toLowerCase(), LEDGER_HEAD_ADVANCED_TOPIC.toLowerCase()];
|
|
4018
|
+
var HEX_DATA2 = /^0x[0-9a-fA-F]*$/;
|
|
4019
|
+
function mirrorLogPosition(raw) {
|
|
4020
|
+
if (!raw || typeof raw !== "object") return null;
|
|
4021
|
+
const { timestamp, index } = raw;
|
|
4022
|
+
if (typeof timestamp !== "string" || !CONSENSUS_TIMESTAMP.test(timestamp)) return null;
|
|
4023
|
+
if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return null;
|
|
4024
|
+
const [seconds, fraction] = timestamp.split(".");
|
|
4025
|
+
return { nanos: BigInt(seconds) * 1000000000n + BigInt(fraction), index };
|
|
4026
|
+
}
|
|
4027
|
+
function mirrorLogFollows(last, next) {
|
|
4028
|
+
return last === null || next.nanos > last.nanos || next.nanos === last.nanos && next.index > last.index;
|
|
4029
|
+
}
|
|
4030
|
+
function keptMirrorLog(raw, contract) {
|
|
4031
|
+
if (!raw || typeof raw !== "object") return null;
|
|
4032
|
+
const log = raw;
|
|
4033
|
+
if (!Array.isArray(log.topics) || typeof log.data !== "string") return null;
|
|
4034
|
+
if (log.topics.length > KEPT_LOG_MAX_TOPICS || log.data.length > KEPT_LOG_DATA_MAX_CHARS || !HEX_DATA2.test(log.data)) return null;
|
|
4035
|
+
const topics = log.topics.map((topic) => String(topic));
|
|
4036
|
+
if (!KEPT_TOPICS.includes((topics[0] ?? "").toLowerCase())) return null;
|
|
4037
|
+
if (topics.some((topic) => topic.length > 66)) return null;
|
|
4038
|
+
if (contract !== void 0) {
|
|
4039
|
+
if (typeof log.address !== "string" || log.address.toLowerCase() !== contract) return null;
|
|
4040
|
+
if (!mirrorLogPosition(raw)) return null;
|
|
4041
|
+
if (typeof log.block_number !== "number" || !Number.isSafeInteger(log.block_number)) return null;
|
|
4042
|
+
if (typeof log.transaction_hash !== "string" || log.transaction_hash.length > 98) return null;
|
|
4043
|
+
}
|
|
4044
|
+
return {
|
|
4045
|
+
address: log.address,
|
|
4046
|
+
data: log.data,
|
|
4047
|
+
index: log.index,
|
|
4048
|
+
topics,
|
|
4049
|
+
block_number: log.block_number,
|
|
4050
|
+
transaction_hash: log.transaction_hash,
|
|
4051
|
+
timestamp: log.timestamp
|
|
4052
|
+
};
|
|
4053
|
+
}
|
|
3606
4054
|
function createMirrorNodeRecordChainReader(options) {
|
|
3607
4055
|
const chainId = options.chainId ?? 296;
|
|
3608
4056
|
const base = (options.mirrorBaseUrl ?? MIRROR_NODE_BY_CHAIN[chainId] ?? "").replace(/\/+$/, "");
|
|
3609
4057
|
if (!base) throw new Error(`No mirror node known for chain ${chainId}; pass mirrorBaseUrl.`);
|
|
3610
|
-
const contractAddress =
|
|
4058
|
+
const contractAddress = import_ethers13.ethers.getAddress(options.contractAddress).toLowerCase();
|
|
3611
4059
|
const timeoutMs = Number(options.timeoutMs || 1e4);
|
|
3612
4060
|
const pageSize = Math.min(100, Math.max(1, Number(options.pageSize || 100)));
|
|
3613
4061
|
const attempts = Math.max(1, options.attempts ?? 3);
|
|
3614
4062
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
3615
|
-
const iface = new
|
|
3616
|
-
|
|
3617
|
-
|
|
4063
|
+
const iface = new import_ethers13.ethers.Interface(RECORD_LANE_ABI_V38);
|
|
4064
|
+
const now = options.scan?.now ?? Date.now;
|
|
4065
|
+
const maxScanRequests = options.scan?.maxRequests ?? LOG_SCAN_MAX_REQUESTS;
|
|
4066
|
+
const maxKeptLogs = options.scan?.maxKeptLogs ?? LOG_SCAN_MAX_KEPT_LOGS;
|
|
4067
|
+
const scanBudgetMs = LOG_SCAN_BUDGET_TIMEOUTS * timeoutMs;
|
|
4068
|
+
async function request(path, init, deadline) {
|
|
4069
|
+
const url = `${base}${path}`;
|
|
3618
4070
|
let lastError = null;
|
|
3619
4071
|
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
4072
|
+
const left = deadline === void 0 ? timeoutMs : deadline - now();
|
|
4073
|
+
if (left <= 0) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
|
|
4074
|
+
const allowed = Math.min(timeoutMs, left);
|
|
3620
4075
|
const controller = new AbortController();
|
|
3621
|
-
const timer = setTimeout(() => controller.abort(),
|
|
4076
|
+
const timer = setTimeout(() => controller.abort(), allowed);
|
|
3622
4077
|
try {
|
|
3623
|
-
const response = await fetchImpl(url, { ...init, signal: controller.signal });
|
|
4078
|
+
const response = await fetchImpl(url, { ...init, redirect: "manual", signal: controller.signal });
|
|
4079
|
+
if (isMirrorRedirect(response)) {
|
|
4080
|
+
await response.body?.cancel?.().catch(() => void 0);
|
|
4081
|
+
throw mirrorRefusal.redirect(path);
|
|
4082
|
+
}
|
|
3624
4083
|
if (response.status === 429 || response.status >= 500) {
|
|
4084
|
+
await response.body?.cancel?.().catch(() => void 0);
|
|
3625
4085
|
lastError = new Error(`mirror node ${response.status} for ${path}`);
|
|
3626
4086
|
} else if (!response.ok) {
|
|
3627
|
-
const body = await response
|
|
4087
|
+
const body = await readMirrorText(response, MIRROR_ANSWER_MAX_BYTES, path).catch(() => "");
|
|
3628
4088
|
throw new Error(`mirror node ${response.status} for ${path}${body ? `: ${body.slice(0, 200)}` : ""}`);
|
|
3629
4089
|
} else {
|
|
3630
|
-
return await response
|
|
4090
|
+
return await readMirrorJson(response, MIRROR_ANSWER_MAX_BYTES, path);
|
|
3631
4091
|
}
|
|
3632
4092
|
} catch (error) {
|
|
3633
|
-
if (error
|
|
3634
|
-
|
|
4093
|
+
if (mirrorRefusalOf(error)) throw error;
|
|
4094
|
+
if (error.name === "AbortError") {
|
|
4095
|
+
if (deadline !== void 0 && allowed < timeoutMs) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
|
|
4096
|
+
lastError = new Error(`mirror node request timed out after ${timeoutMs}ms (${path})`);
|
|
4097
|
+
} else if (/^mirror node \d{3} for/.test(error.message) && !/^mirror node (429|5\d\d)/.test(error.message)) throw error;
|
|
3635
4098
|
else lastError = error;
|
|
3636
4099
|
} finally {
|
|
3637
4100
|
clearTimeout(timer);
|
|
3638
4101
|
}
|
|
3639
4102
|
if (attempt < attempts) await new Promise((resolve) => setTimeout(resolve, 250 * attempt));
|
|
3640
4103
|
}
|
|
4104
|
+
if (deadline !== void 0 && now() >= deadline) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
|
|
3641
4105
|
throw lastError ?? new Error(`mirror node request failed (${path})`);
|
|
3642
4106
|
}
|
|
3643
4107
|
async function call(fn, args = []) {
|
|
@@ -3656,28 +4120,93 @@ function createMirrorNodeRecordChainReader(options) {
|
|
|
3656
4120
|
function matchesTopics(log, topics) {
|
|
3657
4121
|
return topics.every((topic, index) => !topic || (log.topics[index] ?? "").toLowerCase() === topic.toLowerCase());
|
|
3658
4122
|
}
|
|
3659
|
-
|
|
4123
|
+
let keptLogs = null;
|
|
4124
|
+
function readAllLogs() {
|
|
4125
|
+
if (!options.keepLogPages) return readAllLogPages();
|
|
4126
|
+
if (!keptLogs) {
|
|
4127
|
+
keptLogs = readAllLogPages();
|
|
4128
|
+
keptLogs.catch(() => {
|
|
4129
|
+
keptLogs = null;
|
|
4130
|
+
});
|
|
4131
|
+
}
|
|
4132
|
+
return keptLogs;
|
|
4133
|
+
}
|
|
4134
|
+
async function readAllLogPages() {
|
|
3660
4135
|
const params = new URLSearchParams();
|
|
3661
4136
|
params.set("order", "asc");
|
|
3662
4137
|
params.set("limit", String(pageSize));
|
|
3663
|
-
let next =
|
|
4138
|
+
let next = `${contractLogPath(contractAddress)}?${params.toString()}`;
|
|
3664
4139
|
const out = [];
|
|
3665
|
-
|
|
4140
|
+
const scan = { deadline: now() + scanBudgetMs, requests: 0 };
|
|
4141
|
+
let last = null;
|
|
4142
|
+
let size = pageSize;
|
|
3666
4143
|
while (next) {
|
|
3667
|
-
const page = await
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
4144
|
+
const { page, asked } = await readLogPage(next, size, scan);
|
|
4145
|
+
size = Math.min(pageSize, asked * 2);
|
|
4146
|
+
const logs = Array.isArray(page.logs) ? page.logs : [...page.logs ?? []];
|
|
4147
|
+
if (logs.length > asked) throw mirrorRefusal.tooManyLogs(asked, next);
|
|
4148
|
+
for (const raw of logs) {
|
|
4149
|
+
const position = mirrorLogPosition(raw);
|
|
4150
|
+
if (!position) continue;
|
|
4151
|
+
if (!mirrorLogFollows(last, position)) throw mirrorRefusal.notForward();
|
|
4152
|
+
last = position;
|
|
4153
|
+
const log = keptMirrorLog(raw, contractAddress);
|
|
4154
|
+
if (!log) continue;
|
|
4155
|
+
if (out.length >= maxKeptLogs) throw mirrorRefusal.scanTooManyLogs(maxKeptLogs);
|
|
3672
4156
|
out.push(log);
|
|
3673
4157
|
}
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
4158
|
+
const link = page.links?.next;
|
|
4159
|
+
if (link === null || link === void 0 || link === "") {
|
|
4160
|
+
next = null;
|
|
4161
|
+
} else {
|
|
4162
|
+
const path = nextLogPath(link, { base, contract: contractAddress });
|
|
4163
|
+
if (!path) throw mirrorRefusal.nextPage();
|
|
4164
|
+
next = withLogPageLimit(path, size);
|
|
4165
|
+
}
|
|
4166
|
+
}
|
|
4167
|
+
return out;
|
|
4168
|
+
}
|
|
4169
|
+
async function readLogPage(path, start, scan) {
|
|
4170
|
+
let asked = start;
|
|
4171
|
+
for (; ; ) {
|
|
4172
|
+
if (scan.requests >= maxScanRequests) throw mirrorRefusal.scanTooManyRequests(maxScanRequests);
|
|
4173
|
+
scan.requests += 1;
|
|
4174
|
+
try {
|
|
4175
|
+
return { page: await request(withLogPageLimit(path, asked), void 0, scan.deadline), asked };
|
|
4176
|
+
} catch (error) {
|
|
4177
|
+
if (mirrorRefusalOf(error) !== "too-large" || asked <= 1) throw error;
|
|
4178
|
+
asked = Math.max(1, Math.floor(asked / 2));
|
|
4179
|
+
}
|
|
4180
|
+
}
|
|
4181
|
+
}
|
|
4182
|
+
async function scanLogs(topics, fromBlock, toBlock) {
|
|
4183
|
+
const out = [];
|
|
4184
|
+
for (const log of await readAllLogs()) {
|
|
4185
|
+
if (!matchesTopics(log, topics)) continue;
|
|
4186
|
+
if (log.block_number < fromBlock) continue;
|
|
4187
|
+
if (toBlock !== "latest" && log.block_number > toBlock) continue;
|
|
4188
|
+
out.push(log);
|
|
3677
4189
|
}
|
|
3678
4190
|
out.sort((a, b) => a.block_number - b.block_number || a.index - b.index);
|
|
3679
4191
|
return out;
|
|
3680
4192
|
}
|
|
4193
|
+
async function searchPage(path, ms) {
|
|
4194
|
+
const controller = new AbortController();
|
|
4195
|
+
const timer = setTimeout(() => controller.abort(), ms);
|
|
4196
|
+
try {
|
|
4197
|
+
const response = await fetchImpl(`${base}${path}`, { headers: { accept: "application/json" }, redirect: "error", signal: controller.signal });
|
|
4198
|
+
if (isMirrorRedirect(response)) throw mirrorRefusal.redirect(path);
|
|
4199
|
+
if (!response.ok) throw new Error(`mirror node ${response.status} for a record's writes`);
|
|
4200
|
+
const page = await readMirrorJson(response, MIRROR_ANSWER_MAX_BYTES, path);
|
|
4201
|
+
if (Array.isArray(page.logs) && page.logs.length > LEDGER_WRITE_SEARCH_PAGE_LIMIT) throw mirrorRefusal.tooManyLogs(LEDGER_WRITE_SEARCH_PAGE_LIMIT, path);
|
|
4202
|
+
return page;
|
|
4203
|
+
} catch (error) {
|
|
4204
|
+
if (controller.signal.aborted) return "timeout";
|
|
4205
|
+
throw error;
|
|
4206
|
+
} finally {
|
|
4207
|
+
clearTimeout(timer);
|
|
4208
|
+
}
|
|
4209
|
+
}
|
|
3681
4210
|
return {
|
|
3682
4211
|
contractAddress,
|
|
3683
4212
|
async getRecord(recordKey) {
|
|
@@ -3735,10 +4264,58 @@ function createMirrorNodeRecordChainReader(options) {
|
|
|
3735
4264
|
encodingVersion: Number(parsed.args.encodingVersion),
|
|
3736
4265
|
blockNumber: log.block_number,
|
|
3737
4266
|
transactionHash: log.transaction_hash,
|
|
3738
|
-
logIndex: log.index
|
|
4267
|
+
logIndex: log.index,
|
|
4268
|
+
committedAt: committedAtOf(log.timestamp),
|
|
4269
|
+
contractAddress: typeof log.address === "string" ? log.address.toLowerCase() : void 0
|
|
3739
4270
|
});
|
|
3740
4271
|
}
|
|
3741
4272
|
return out;
|
|
4273
|
+
},
|
|
4274
|
+
async findRecordWrites(recordKey, search) {
|
|
4275
|
+
const key = normalizeProofHash(recordKey, "recordKey").toLowerCase();
|
|
4276
|
+
const topic0 = RECORD_WRITTEN_TOPIC.toLowerCase();
|
|
4277
|
+
const now2 = search.now ?? Date.now;
|
|
4278
|
+
const deadline = now2() + search.budgetMs;
|
|
4279
|
+
const windowSeconds = Math.max(1, Math.floor(search.windowSeconds ?? RECORD_WRITE_SEARCH_WINDOW_SECONDS));
|
|
4280
|
+
const nowSeconds = Math.floor(now2() / 1e3);
|
|
4281
|
+
const hint = search.startAt ? Date.parse(search.startAt) : Number.NaN;
|
|
4282
|
+
let upper = Math.min(Number.isFinite(hint) ? Math.floor(hint / 1e3) : nowSeconds, nowSeconds) + DAY_SECONDS;
|
|
4283
|
+
const writes = [];
|
|
4284
|
+
let requests = 0;
|
|
4285
|
+
const end = (ended) => ({ writes, ended, requests });
|
|
4286
|
+
while (!search.done(writes)) {
|
|
4287
|
+
if (upper <= 0) return end("limit");
|
|
4288
|
+
const lower = Math.max(0, upper - windowSeconds);
|
|
4289
|
+
let path = ledgerWriteSearchPath({ contractAddress, topic0, recordKey: key, lower, upper });
|
|
4290
|
+
while (path) {
|
|
4291
|
+
const left = deadline - now2();
|
|
4292
|
+
if (requests >= search.maxRequests || left <= 0) return end("limit");
|
|
4293
|
+
requests += 1;
|
|
4294
|
+
const page = await searchPage(path, left);
|
|
4295
|
+
if (page === "timeout") return end("timeout");
|
|
4296
|
+
for (const log of Array.isArray(page?.logs) ? page.logs : []) {
|
|
4297
|
+
const write = parseLedgerWriteLog(log, { topic0, recordKey: key, contractAddress });
|
|
4298
|
+
if (!write || !CONSENSUS_TIMESTAMP.test(write.timestamp)) continue;
|
|
4299
|
+
writes.push({
|
|
4300
|
+
previousWord: write.previousWord,
|
|
4301
|
+
newWord: write.newWord,
|
|
4302
|
+
operator: write.operator,
|
|
4303
|
+
encodingVersion: write.encodingVersion,
|
|
4304
|
+
blockNumber: write.blockNumber ?? void 0,
|
|
4305
|
+
transactionHash: write.transactionHash,
|
|
4306
|
+
logIndex: write.logIndex ?? void 0,
|
|
4307
|
+
committedAt: write.committedAt,
|
|
4308
|
+
contractAddress: write.address
|
|
4309
|
+
});
|
|
4310
|
+
}
|
|
4311
|
+
if (search.done(writes)) return end("done");
|
|
4312
|
+
const link = page?.links?.next;
|
|
4313
|
+
path = nextLogPath(link, { base, contract: contractAddress });
|
|
4314
|
+
if (!path && link !== null && link !== void 0 && link !== "") throw mirrorRefusal.nextPage();
|
|
4315
|
+
}
|
|
4316
|
+
upper = lower;
|
|
4317
|
+
}
|
|
4318
|
+
return end("done");
|
|
3742
4319
|
}
|
|
3743
4320
|
};
|
|
3744
4321
|
}
|
|
@@ -4057,7 +4634,7 @@ var hasOnly = (v, required, optional = []) => required.every((k) => Object.proto
|
|
|
4057
4634
|
function computeSealHistoryDigestV1(form) {
|
|
4058
4635
|
const rest = { ...form };
|
|
4059
4636
|
delete rest.digest;
|
|
4060
|
-
return
|
|
4637
|
+
return import_ethers14.ethers.keccak256(import_ethers14.ethers.toUtf8Bytes(canonicalizeJcs(rest)));
|
|
4061
4638
|
}
|
|
4062
4639
|
function entryShapeOk2(e) {
|
|
4063
4640
|
if (!isPlainObject5(e) || !hasOnly(e, ENTRY_KEYS, ["recordHash"])) return false;
|
|
@@ -6844,7 +7421,7 @@ async function readWorkspaceSecretFile(path) {
|
|
|
6844
7421
|
var import_promises = require("node:fs/promises");
|
|
6845
7422
|
var import_node_path = require("node:path");
|
|
6846
7423
|
var PIN_FILE_SCHEMA = "pacspace-pins/v1";
|
|
6847
|
-
var
|
|
7424
|
+
var HEX643 = /^[0-9a-f]{64}$/;
|
|
6848
7425
|
function filePinStore(path) {
|
|
6849
7426
|
const read = async () => {
|
|
6850
7427
|
let text;
|
|
@@ -6864,7 +7441,7 @@ function filePinStore(path) {
|
|
|
6864
7441
|
return {
|
|
6865
7442
|
async get(workspaceId) {
|
|
6866
7443
|
const pin = (await read())[workspaceId];
|
|
6867
|
-
return pin && typeof pin.publicKeyId === "string" &&
|
|
7444
|
+
return pin && typeof pin.publicKeyId === "string" && HEX643.test(pin.publicKeyId) ? { ...pin } : null;
|
|
6868
7445
|
},
|
|
6869
7446
|
async set(workspaceId, pin) {
|
|
6870
7447
|
const pins = await read();
|