zk-credits 0.2.0 → 0.2.2
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/README.md +74 -42
- package/dist/base-registered-trial.d.ts +33 -0
- package/dist/base-registered-trial.js +168 -0
- package/dist/base-sidecar.d.ts +14 -1
- package/dist/base-sidecar.js +82 -72
- package/dist/cli-runtime.d.ts +1 -0
- package/dist/cli-runtime.js +2 -1
- package/dist/cli.js +418 -16
- package/dist/node-sidecar-lifecycle.d.ts +2 -0
- package/dist/node-sidecar-lifecycle.js +29 -7
- package/dist/responses-bridge.d.ts +14 -0
- package/dist/responses-bridge.js +328 -0
- package/dist/setup-config.d.ts +36 -0
- package/dist/setup-config.js +320 -0
- package/dist/sidecar.js +52 -8
- package/dist/zk-credits.js +1409 -189
- package/package.json +2 -1
package/dist/zk-credits.js
CHANGED
|
@@ -34651,7 +34651,7 @@ var require_lib = __commonJS({
|
|
|
34651
34651
|
};
|
|
34652
34652
|
}
|
|
34653
34653
|
// @__NO_SIDE_EFFECTS__
|
|
34654
|
-
function
|
|
34654
|
+
function join7(separator = "") {
|
|
34655
34655
|
astr("join", separator);
|
|
34656
34656
|
return {
|
|
34657
34657
|
encode: (from) => {
|
|
@@ -34867,15 +34867,15 @@ var require_lib = __commonJS({
|
|
|
34867
34867
|
convertRadix2,
|
|
34868
34868
|
radix,
|
|
34869
34869
|
radix2,
|
|
34870
|
-
join:
|
|
34870
|
+
join: join7,
|
|
34871
34871
|
padding
|
|
34872
34872
|
};
|
|
34873
|
-
exports.base16 = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(4), /* @__PURE__ */ alphabet("0123456789ABCDEF"), /* @__PURE__ */
|
|
34874
|
-
exports.base32 = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), /* @__PURE__ */ padding(5), /* @__PURE__ */
|
|
34875
|
-
exports.base32nopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), /* @__PURE__ */
|
|
34876
|
-
exports.base32hex = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), /* @__PURE__ */ padding(5), /* @__PURE__ */
|
|
34877
|
-
exports.base32hexnopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), /* @__PURE__ */
|
|
34878
|
-
exports.base32crockford = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), /* @__PURE__ */
|
|
34873
|
+
exports.base16 = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(4), /* @__PURE__ */ alphabet("0123456789ABCDEF"), /* @__PURE__ */ join7(""));
|
|
34874
|
+
exports.base32 = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), /* @__PURE__ */ padding(5), /* @__PURE__ */ join7(""));
|
|
34875
|
+
exports.base32nopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), /* @__PURE__ */ join7(""));
|
|
34876
|
+
exports.base32hex = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), /* @__PURE__ */ padding(5), /* @__PURE__ */ join7(""));
|
|
34877
|
+
exports.base32hexnopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), /* @__PURE__ */ join7(""));
|
|
34878
|
+
exports.base32crockford = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(5), /* @__PURE__ */ alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), /* @__PURE__ */ join7(""), /* @__PURE__ */ normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
|
|
34879
34879
|
var hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === "function" && typeof Uint8Array.fromBase64 === "function")();
|
|
34880
34880
|
var decodeBase64Builtin = (s, isUrl) => {
|
|
34881
34881
|
astr("base64", s);
|
|
@@ -34893,8 +34893,8 @@ var require_lib = __commonJS({
|
|
|
34893
34893
|
decode(s) {
|
|
34894
34894
|
return decodeBase64Builtin(s, false);
|
|
34895
34895
|
}
|
|
34896
|
-
} : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), /* @__PURE__ */ padding(6), /* @__PURE__ */
|
|
34897
|
-
exports.base64nopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), /* @__PURE__ */
|
|
34896
|
+
} : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), /* @__PURE__ */ padding(6), /* @__PURE__ */ join7(""));
|
|
34897
|
+
exports.base64nopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), /* @__PURE__ */ join7(""));
|
|
34898
34898
|
exports.base64url = hasBase64Builtin ? {
|
|
34899
34899
|
encode(b) {
|
|
34900
34900
|
abytes(b);
|
|
@@ -34903,9 +34903,9 @@ var require_lib = __commonJS({
|
|
|
34903
34903
|
decode(s) {
|
|
34904
34904
|
return decodeBase64Builtin(s, true);
|
|
34905
34905
|
}
|
|
34906
|
-
} : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), /* @__PURE__ */ padding(6), /* @__PURE__ */
|
|
34907
|
-
exports.base64urlnopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), /* @__PURE__ */
|
|
34908
|
-
var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */
|
|
34906
|
+
} : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), /* @__PURE__ */ padding(6), /* @__PURE__ */ join7(""));
|
|
34907
|
+
exports.base64urlnopad = /* @__PURE__ */ chain(/* @__PURE__ */ radix2(6), /* @__PURE__ */ alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), /* @__PURE__ */ join7(""));
|
|
34908
|
+
var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join7(""));
|
|
34909
34909
|
exports.base58 = /* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
|
|
34910
34910
|
exports.base58flickr = /* @__PURE__ */ genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");
|
|
34911
34911
|
exports.base58xrp = /* @__PURE__ */ genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");
|
|
@@ -34937,7 +34937,7 @@ var require_lib = __commonJS({
|
|
|
34937
34937
|
var createBase58check = (sha256) => /* @__PURE__ */ chain(checksum(4, (data) => sha256(sha256(data))), exports.base58);
|
|
34938
34938
|
exports.createBase58check = createBase58check;
|
|
34939
34939
|
exports.base58check = exports.createBase58check;
|
|
34940
|
-
var BECH_ALPHABET = /* @__PURE__ */ chain(/* @__PURE__ */ alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), /* @__PURE__ */
|
|
34940
|
+
var BECH_ALPHABET = /* @__PURE__ */ chain(/* @__PURE__ */ alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), /* @__PURE__ */ join7(""));
|
|
34941
34941
|
var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059];
|
|
34942
34942
|
function bech32Polymod(pre) {
|
|
34943
34943
|
const b = pre >> 25;
|
|
@@ -35046,7 +35046,7 @@ var require_lib = __commonJS({
|
|
|
35046
35046
|
return Uint8Array.fromHex(s);
|
|
35047
35047
|
}
|
|
35048
35048
|
};
|
|
35049
|
-
exports.hex = hasHexBuiltin ? hexBuiltin : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(4), /* @__PURE__ */ alphabet("0123456789abcdef"), /* @__PURE__ */
|
|
35049
|
+
exports.hex = hasHexBuiltin ? hexBuiltin : /* @__PURE__ */ chain(/* @__PURE__ */ radix2(4), /* @__PURE__ */ alphabet("0123456789abcdef"), /* @__PURE__ */ join7(""), /* @__PURE__ */ normalize((s) => {
|
|
35050
35050
|
if (typeof s !== "string" || s.length % 2 !== 0)
|
|
35051
35051
|
throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
|
|
35052
35052
|
return s.toLowerCase();
|
|
@@ -38760,20 +38760,20 @@ var require_TempoAddress = __commonJS({
|
|
|
38760
38760
|
"use strict";
|
|
38761
38761
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
38762
38762
|
exports.InvalidPrefixError = void 0;
|
|
38763
|
-
exports.resolve =
|
|
38763
|
+
exports.resolve = resolve3;
|
|
38764
38764
|
exports.format = format;
|
|
38765
38765
|
exports.parse = parse;
|
|
38766
38766
|
exports.validate = validate;
|
|
38767
38767
|
var core_Address = require_Address();
|
|
38768
38768
|
var Errors = require_Errors();
|
|
38769
38769
|
var Hex = require_Hex();
|
|
38770
|
-
function
|
|
38770
|
+
function resolve3(address2) {
|
|
38771
38771
|
if (address2.startsWith("tempo"))
|
|
38772
38772
|
return parse(address2).address;
|
|
38773
38773
|
return address2;
|
|
38774
38774
|
}
|
|
38775
38775
|
function format(address2) {
|
|
38776
|
-
const resolved =
|
|
38776
|
+
const resolved = resolve3(address2);
|
|
38777
38777
|
return `tempox${resolved.toLowerCase()}`;
|
|
38778
38778
|
}
|
|
38779
38779
|
function parse(tempoAddress) {
|
|
@@ -40096,7 +40096,7 @@ var require_KeyAuthorization = __commonJS({
|
|
|
40096
40096
|
assertAccountBinding(authorization.type, authorization.account);
|
|
40097
40097
|
const auth = authorization;
|
|
40098
40098
|
if (auth.witness !== void 0)
|
|
40099
|
-
|
|
40099
|
+
assertWitness(auth.witness);
|
|
40100
40100
|
if (auth.signature)
|
|
40101
40101
|
assertSignature(auth.signature);
|
|
40102
40102
|
const resolved = {
|
|
@@ -40139,7 +40139,7 @@ var require_KeyAuthorization = __commonJS({
|
|
|
40139
40139
|
const signature = SignatureEnvelope.fromRpc(authorization.signature);
|
|
40140
40140
|
assertSignature(signature);
|
|
40141
40141
|
if (witness !== void 0)
|
|
40142
|
-
|
|
40142
|
+
assertWitness(witness);
|
|
40143
40143
|
const scopes = allowedCalls ? allowedCalls.flatMap((callScope) => {
|
|
40144
40144
|
if (!callScope.selectorRules || callScope.selectorRules.length === 0)
|
|
40145
40145
|
return [{ address: callScope.target }];
|
|
@@ -40209,7 +40209,7 @@ var require_KeyAuthorization = __commonJS({
|
|
|
40209
40209
|
}) : void 0;
|
|
40210
40210
|
const witness = isAbsent(rawWitness) ? void 0 : rawWitness;
|
|
40211
40211
|
if (witness !== void 0)
|
|
40212
|
-
|
|
40212
|
+
assertWitness(witness);
|
|
40213
40213
|
const isAdmin = (() => {
|
|
40214
40214
|
if (isAbsent(rawIsAdmin))
|
|
40215
40215
|
return void 0;
|
|
@@ -40258,7 +40258,7 @@ var require_KeyAuthorization = __commonJS({
|
|
|
40258
40258
|
const { address: address2, scopes, chainId, expiry, limits, type, signature, witness, isAdmin, account } = authorization;
|
|
40259
40259
|
assertSignature(signature);
|
|
40260
40260
|
if (witness !== void 0)
|
|
40261
|
-
|
|
40261
|
+
assertWitness(witness);
|
|
40262
40262
|
const allowedCalls = (() => {
|
|
40263
40263
|
if (!scopes)
|
|
40264
40264
|
return void 0;
|
|
@@ -40300,7 +40300,7 @@ var require_KeyAuthorization = __commonJS({
|
|
|
40300
40300
|
assertAccountBinding(authorization.type, authorization.account);
|
|
40301
40301
|
const { address: address2, chainId, scopes, expiry, limits, witness, isAdmin, account } = authorization;
|
|
40302
40302
|
if (witness !== void 0)
|
|
40303
|
-
|
|
40303
|
+
assertWitness(witness);
|
|
40304
40304
|
const signature = (() => {
|
|
40305
40305
|
if (!authorization.signature)
|
|
40306
40306
|
return void 0;
|
|
@@ -40403,7 +40403,7 @@ var require_KeyAuthorization = __commonJS({
|
|
|
40403
40403
|
if (type === "multisig" && account == null)
|
|
40404
40404
|
throw new MissingAccountError();
|
|
40405
40405
|
}
|
|
40406
|
-
function
|
|
40406
|
+
function assertWitness(witness) {
|
|
40407
40407
|
if (Hex.size(witness) !== 32)
|
|
40408
40408
|
throw new InvalidWitnessSizeError(witness);
|
|
40409
40409
|
}
|
|
@@ -42868,13 +42868,13 @@ var require_virtualMasterPool = __commonJS({
|
|
|
42868
42868
|
"node_modules/ox/_cjs/tempo/internal/virtualMasterPool.js"(exports) {
|
|
42869
42869
|
"use strict";
|
|
42870
42870
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
42871
|
-
exports.resolve =
|
|
42871
|
+
exports.resolve = resolve3;
|
|
42872
42872
|
exports.resolveNode = resolveNode;
|
|
42873
42873
|
exports.resolveBrowser = resolveBrowser;
|
|
42874
42874
|
var Errors = require_Errors();
|
|
42875
42875
|
var cachedPool;
|
|
42876
42876
|
var isNode = typeof globalThis.process !== "undefined" && typeof globalThis.process.versions?.node === "string";
|
|
42877
|
-
async function
|
|
42877
|
+
async function resolve3() {
|
|
42878
42878
|
if (cachedPool)
|
|
42879
42879
|
return cachedPool;
|
|
42880
42880
|
cachedPool = isNode ? await resolveNode() : await resolveBrowser();
|
|
@@ -43152,7 +43152,7 @@ var require_VirtualMaster = __commonJS({
|
|
|
43152
43152
|
}
|
|
43153
43153
|
function mineSaltWithWorkerPool(value) {
|
|
43154
43154
|
const startedAt = Date.now();
|
|
43155
|
-
return new Promise((
|
|
43155
|
+
return new Promise((resolve3, reject) => {
|
|
43156
43156
|
let settled = false;
|
|
43157
43157
|
let attempts = 0;
|
|
43158
43158
|
let completedWorkers = 0;
|
|
@@ -43182,7 +43182,7 @@ var require_VirtualMaster = __commonJS({
|
|
|
43182
43182
|
settled = true;
|
|
43183
43183
|
value.signal?.removeEventListener("abort", onAbort);
|
|
43184
43184
|
terminateAll();
|
|
43185
|
-
|
|
43185
|
+
resolve3(result);
|
|
43186
43186
|
};
|
|
43187
43187
|
const fail = (error) => {
|
|
43188
43188
|
if (settled)
|
|
@@ -46248,13 +46248,13 @@ var require_withResolvers = __commonJS({
|
|
|
46248
46248
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
46249
46249
|
exports.withResolvers = withResolvers;
|
|
46250
46250
|
function withResolvers() {
|
|
46251
|
-
let
|
|
46251
|
+
let resolve3 = () => void 0;
|
|
46252
46252
|
let reject = () => void 0;
|
|
46253
46253
|
const promise = new Promise((resolve_, reject_) => {
|
|
46254
|
-
|
|
46254
|
+
resolve3 = resolve_;
|
|
46255
46255
|
reject = reject_;
|
|
46256
46256
|
});
|
|
46257
|
-
return { promise, resolve:
|
|
46257
|
+
return { promise, resolve: resolve3, reject };
|
|
46258
46258
|
}
|
|
46259
46259
|
}
|
|
46260
46260
|
});
|
|
@@ -46278,8 +46278,8 @@ var require_createBatchScheduler = __commonJS({
|
|
|
46278
46278
|
if (sort && Array.isArray(data))
|
|
46279
46279
|
data.sort(sort);
|
|
46280
46280
|
for (let i = 0; i < scheduler.length; i++) {
|
|
46281
|
-
const { resolve:
|
|
46282
|
-
|
|
46281
|
+
const { resolve: resolve3 } = scheduler[i];
|
|
46282
|
+
resolve3?.([data[i], data]);
|
|
46283
46283
|
}
|
|
46284
46284
|
}).catch((err) => {
|
|
46285
46285
|
for (let i = 0; i < scheduler.length; i++) {
|
|
@@ -46295,16 +46295,16 @@ var require_createBatchScheduler = __commonJS({
|
|
|
46295
46295
|
return {
|
|
46296
46296
|
flush,
|
|
46297
46297
|
async schedule(args) {
|
|
46298
|
-
const { promise, resolve:
|
|
46298
|
+
const { promise, resolve: resolve3, reject } = (0, withResolvers_js_1.withResolvers)();
|
|
46299
46299
|
const split = shouldSplitBatch?.([...getBatchedArgs(), args]);
|
|
46300
46300
|
if (split)
|
|
46301
46301
|
exec();
|
|
46302
46302
|
const hasActiveScheduler = getScheduler().length > 0;
|
|
46303
46303
|
if (hasActiveScheduler) {
|
|
46304
|
-
setScheduler({ args, resolve:
|
|
46304
|
+
setScheduler({ args, resolve: resolve3, reject });
|
|
46305
46305
|
return promise;
|
|
46306
46306
|
}
|
|
46307
|
-
setScheduler({ args, resolve:
|
|
46307
|
+
setScheduler({ args, resolve: resolve3, reject });
|
|
46308
46308
|
setTimeout(exec, wait);
|
|
46309
46309
|
return promise;
|
|
46310
46310
|
}
|
|
@@ -47400,11 +47400,11 @@ var require_observe = __commonJS({
|
|
|
47400
47400
|
"use strict";
|
|
47401
47401
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
47402
47402
|
exports.cleanupCache = exports.listenersCache = void 0;
|
|
47403
|
-
exports.observe =
|
|
47403
|
+
exports.observe = observe2;
|
|
47404
47404
|
exports.listenersCache = /* @__PURE__ */ new Map();
|
|
47405
47405
|
exports.cleanupCache = /* @__PURE__ */ new Map();
|
|
47406
47406
|
var callbackCount = 0;
|
|
47407
|
-
function
|
|
47407
|
+
function observe2(observerId, callbacks, fn) {
|
|
47408
47408
|
const callbackId = ++callbackCount;
|
|
47409
47409
|
const getListeners = () => exports.listenersCache.get(observerId) || [];
|
|
47410
47410
|
const unsubscribe = () => {
|
|
@@ -47463,7 +47463,7 @@ var require_wait = __commonJS({
|
|
|
47463
47463
|
exports.wait = wait;
|
|
47464
47464
|
var utils_js_1 = require_utils5();
|
|
47465
47465
|
async function wait(time, { signal } = {}) {
|
|
47466
|
-
return new Promise((
|
|
47466
|
+
return new Promise((resolve3, reject) => {
|
|
47467
47467
|
if (signal?.aborted) {
|
|
47468
47468
|
reject((0, utils_js_1.getAbortError)(signal));
|
|
47469
47469
|
return;
|
|
@@ -47471,7 +47471,7 @@ var require_wait = __commonJS({
|
|
|
47471
47471
|
const cleanup = () => signal?.removeEventListener("abort", onAbort);
|
|
47472
47472
|
const timeout = setTimeout(() => {
|
|
47473
47473
|
cleanup();
|
|
47474
|
-
|
|
47474
|
+
resolve3();
|
|
47475
47475
|
}, time);
|
|
47476
47476
|
const onAbort = () => {
|
|
47477
47477
|
clearTimeout(timeout);
|
|
@@ -49127,7 +49127,7 @@ var require_withRetry = __commonJS({
|
|
|
49127
49127
|
var utils_js_1 = require_utils5();
|
|
49128
49128
|
var wait_js_1 = require_wait();
|
|
49129
49129
|
function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry = () => true, signal } = {}) {
|
|
49130
|
-
return new Promise((
|
|
49130
|
+
return new Promise((resolve3, reject) => {
|
|
49131
49131
|
const attemptRetry = async ({ count = 0 } = {}) => {
|
|
49132
49132
|
if (signal?.aborted) {
|
|
49133
49133
|
reject((0, utils_js_1.getAbortError)(signal));
|
|
@@ -49147,7 +49147,7 @@ var require_withRetry = __commonJS({
|
|
|
49147
49147
|
};
|
|
49148
49148
|
try {
|
|
49149
49149
|
const data = await fn();
|
|
49150
|
-
|
|
49150
|
+
resolve3(data);
|
|
49151
49151
|
} catch (err) {
|
|
49152
49152
|
if (signal?.aborted) {
|
|
49153
49153
|
reject((0, utils_js_1.getAbortError)(signal));
|
|
@@ -49327,13 +49327,13 @@ var require_waitForTransactionReceipt = __commonJS({
|
|
|
49327
49327
|
let retrying = false;
|
|
49328
49328
|
let _unobserve;
|
|
49329
49329
|
let _unwatch;
|
|
49330
|
-
const { promise, resolve:
|
|
49330
|
+
const { promise, resolve: resolve3, reject } = (0, withResolvers_js_1.withResolvers)();
|
|
49331
49331
|
const timer = timeout ? setTimeout(() => {
|
|
49332
49332
|
_unwatch?.();
|
|
49333
49333
|
_unobserve?.();
|
|
49334
49334
|
reject(new transaction_js_1.WaitForTransactionReceiptTimeoutError({ hash }));
|
|
49335
49335
|
}, timeout) : void 0;
|
|
49336
|
-
_unobserve = (0, observe_js_1.observe)(observerId, { onReplaced, resolve:
|
|
49336
|
+
_unobserve = (0, observe_js_1.observe)(observerId, { onReplaced, resolve: resolve3, reject }, async (emit) => {
|
|
49337
49337
|
receipt = await (0, getAction_js_1.getAction)(client, getTransactionReceipt_js_1.getTransactionReceipt, "getTransactionReceipt")({ hash }).catch(() => void 0);
|
|
49338
49338
|
if (receipt && confirmations <= 1) {
|
|
49339
49339
|
clearTimeout(timer);
|
|
@@ -60344,7 +60344,7 @@ var require_withTimeout = __commonJS({
|
|
|
60344
60344
|
exports.withTimeout = withTimeout;
|
|
60345
60345
|
var utils_js_1 = require_utils5();
|
|
60346
60346
|
function withTimeout(fn, { errorInstance = new Error("timed out"), timeout, signal }) {
|
|
60347
|
-
return new Promise((
|
|
60347
|
+
return new Promise((resolve3, reject) => {
|
|
60348
60348
|
;
|
|
60349
60349
|
(async () => {
|
|
60350
60350
|
let timeoutId;
|
|
@@ -60359,7 +60359,7 @@ var require_withTimeout = __commonJS({
|
|
|
60359
60359
|
}
|
|
60360
60360
|
}, timeout);
|
|
60361
60361
|
}
|
|
60362
|
-
|
|
60362
|
+
resolve3(await fn({ signal: controller?.signal || null }));
|
|
60363
60363
|
} catch (err) {
|
|
60364
60364
|
if (controller?.signal.aborted && (0, utils_js_1.isAbortError)(err)) {
|
|
60365
60365
|
reject(errorInstance);
|
|
@@ -63943,7 +63943,7 @@ var require_stream = __commonJS({
|
|
|
63943
63943
|
};
|
|
63944
63944
|
duplex._final = function(callback) {
|
|
63945
63945
|
if (ws.readyState === ws.CONNECTING) {
|
|
63946
|
-
ws.once("open", function
|
|
63946
|
+
ws.once("open", function open3() {
|
|
63947
63947
|
duplex._final(callback);
|
|
63948
63948
|
});
|
|
63949
63949
|
return;
|
|
@@ -63964,7 +63964,7 @@ var require_stream = __commonJS({
|
|
|
63964
63964
|
};
|
|
63965
63965
|
duplex._write = function(chunk, encoding, callback) {
|
|
63966
63966
|
if (ws.readyState === ws.CONNECTING) {
|
|
63967
|
-
ws.once("open", function
|
|
63967
|
+
ws.once("open", function open3() {
|
|
63968
63968
|
duplex._write(chunk, encoding, callback);
|
|
63969
63969
|
});
|
|
63970
63970
|
return;
|
|
@@ -64527,10 +64527,10 @@ var require_webSocket = __commonJS({
|
|
|
64527
64527
|
socket.addEventListener("error", onError);
|
|
64528
64528
|
socket.addEventListener("open", onOpen);
|
|
64529
64529
|
if (socket.readyState === WebSocket2.CONNECTING) {
|
|
64530
|
-
await new Promise((
|
|
64530
|
+
await new Promise((resolve3, reject) => {
|
|
64531
64531
|
if (!socket)
|
|
64532
64532
|
return;
|
|
64533
|
-
socket.onopen =
|
|
64533
|
+
socket.onopen = resolve3;
|
|
64534
64534
|
socket.onerror = reject;
|
|
64535
64535
|
});
|
|
64536
64536
|
}
|
|
@@ -73671,7 +73671,7 @@ var require_sendCalls = __commonJS({
|
|
|
73671
73671
|
results.push({ reason, status: "rejected" });
|
|
73672
73672
|
}
|
|
73673
73673
|
if (experimental_fallbackDelay > 0)
|
|
73674
|
-
await new Promise((
|
|
73674
|
+
await new Promise((resolve3) => setTimeout(resolve3, experimental_fallbackDelay));
|
|
73675
73675
|
}
|
|
73676
73676
|
if (results.every((r) => r.status === "rejected"))
|
|
73677
73677
|
throw results[0].reason;
|
|
@@ -73793,9 +73793,9 @@ var require_waitForCallsStatus = __commonJS({
|
|
|
73793
73793
|
async function waitForCallsStatus(client, parameters) {
|
|
73794
73794
|
const { id, pollingInterval = client.pollingInterval, status = ({ statusCode }) => statusCode === 200 || statusCode >= 300, retryCount = 4, retryDelay = ({ count }) => ~~(1 << count) * 200, timeout = 6e4, throwOnFailure = false } = parameters;
|
|
73795
73795
|
const observerId = (0, stringify_js_1.stringify)(["waitForCallsStatus", client.uid, id]);
|
|
73796
|
-
const { promise, resolve:
|
|
73796
|
+
const { promise, resolve: resolve3, reject } = (0, withResolvers_js_1.withResolvers)();
|
|
73797
73797
|
let timer;
|
|
73798
|
-
const unobserve = (0, observe_js_1.observe)(observerId, { resolve:
|
|
73798
|
+
const unobserve = (0, observe_js_1.observe)(observerId, { resolve: resolve3, reject }, (emit) => {
|
|
73799
73799
|
const unpoll = (0, poll_js_1.poll)(async () => {
|
|
73800
73800
|
const done = (fn) => {
|
|
73801
73801
|
clearTimeout(timer);
|
|
@@ -74281,13 +74281,13 @@ var require_utils11 = __commonJS({
|
|
|
74281
74281
|
}
|
|
74282
74282
|
if (!Object.hasOwn(globalThis, "Image"))
|
|
74283
74283
|
return false;
|
|
74284
|
-
return new Promise((
|
|
74284
|
+
return new Promise((resolve3) => {
|
|
74285
74285
|
const img = new Image();
|
|
74286
74286
|
img.onload = () => {
|
|
74287
|
-
|
|
74287
|
+
resolve3(true);
|
|
74288
74288
|
};
|
|
74289
74289
|
img.onerror = () => {
|
|
74290
|
-
|
|
74290
|
+
resolve3(false);
|
|
74291
74291
|
};
|
|
74292
74292
|
img.src = uri;
|
|
74293
74293
|
});
|
|
@@ -78763,7 +78763,7 @@ var require_webSocket2 = __commonJS({
|
|
|
78763
78763
|
},
|
|
78764
78764
|
async subscribe({ params, onData, onError }) {
|
|
78765
78765
|
const rpcClient = await (0, webSocket_js_1.getWebSocketRpcClient)(url_, wsRpcClientOpts);
|
|
78766
|
-
const { result: subscriptionId } = await new Promise((
|
|
78766
|
+
const { result: subscriptionId } = await new Promise((resolve3, reject) => rpcClient.request({
|
|
78767
78767
|
body: {
|
|
78768
78768
|
method: "eth_subscribe",
|
|
78769
78769
|
params
|
|
@@ -78780,7 +78780,7 @@ var require_webSocket2 = __commonJS({
|
|
|
78780
78780
|
return;
|
|
78781
78781
|
}
|
|
78782
78782
|
if (typeof response.id === "number") {
|
|
78783
|
-
|
|
78783
|
+
resolve3(response);
|
|
78784
78784
|
return;
|
|
78785
78785
|
}
|
|
78786
78786
|
if (response.method !== "eth_subscription")
|
|
@@ -78791,12 +78791,12 @@ var require_webSocket2 = __commonJS({
|
|
|
78791
78791
|
return {
|
|
78792
78792
|
subscriptionId,
|
|
78793
78793
|
async unsubscribe() {
|
|
78794
|
-
return new Promise((
|
|
78794
|
+
return new Promise((resolve3) => rpcClient.request({
|
|
78795
78795
|
body: {
|
|
78796
78796
|
method: "eth_unsubscribe",
|
|
78797
78797
|
params: [subscriptionId]
|
|
78798
78798
|
},
|
|
78799
|
-
onResponse:
|
|
78799
|
+
onResponse: resolve3
|
|
78800
78800
|
}));
|
|
78801
78801
|
}
|
|
78802
78802
|
};
|
|
@@ -80654,8 +80654,9 @@ var require_cjs2 = __commonJS({
|
|
|
80654
80654
|
|
|
80655
80655
|
// dist/cli.js
|
|
80656
80656
|
import { homedir } from "node:os";
|
|
80657
|
-
import { readFile as
|
|
80658
|
-
import { join as
|
|
80657
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
80658
|
+
import { join as join6 } from "node:path";
|
|
80659
|
+
import { createInterface } from "node:readline/promises";
|
|
80659
80660
|
|
|
80660
80661
|
// dist/codex-launcher.js
|
|
80661
80662
|
import { spawn } from "node:child_process";
|
|
@@ -80767,7 +80768,7 @@ async function isCodexProfileInstalled(codexHome) {
|
|
|
80767
80768
|
var spawnCommand = (command, args, options) => spawn(command, args, options);
|
|
80768
80769
|
async function launchCodexProcess(args, spawnImpl = spawnCommand) {
|
|
80769
80770
|
const child = spawnImpl("codex", ["--profile", CODEX_PROFILE_NAME, ...args], { stdio: "inherit" });
|
|
80770
|
-
return new Promise((
|
|
80771
|
+
return new Promise((resolve3, reject) => {
|
|
80771
80772
|
child.once("error", (error) => {
|
|
80772
80773
|
if (error.code === "ENOENT") {
|
|
80773
80774
|
reject(new Error("Codex CLI was not found; install it before running zk-credits codex"));
|
|
@@ -80775,7 +80776,7 @@ async function launchCodexProcess(args, spawnImpl = spawnCommand) {
|
|
|
80775
80776
|
}
|
|
80776
80777
|
reject(error);
|
|
80777
80778
|
});
|
|
80778
|
-
child.once("exit", (code) =>
|
|
80779
|
+
child.once("exit", (code) => resolve3(code ?? 1));
|
|
80779
80780
|
});
|
|
80780
80781
|
}
|
|
80781
80782
|
|
|
@@ -80817,7 +80818,7 @@ function assertManagedProviderArguments(args) {
|
|
|
80817
80818
|
}
|
|
80818
80819
|
}
|
|
80819
80820
|
function waitForCline(child) {
|
|
80820
|
-
return new Promise((
|
|
80821
|
+
return new Promise((resolve3, reject) => {
|
|
80821
80822
|
child.once("error", (error) => {
|
|
80822
80823
|
if (error.code === "ENOENT") {
|
|
80823
80824
|
reject(new Error("Cline CLI was not found; install it with npm install --global cline"));
|
|
@@ -80825,7 +80826,7 @@ function waitForCline(child) {
|
|
|
80825
80826
|
}
|
|
80826
80827
|
reject(error);
|
|
80827
80828
|
});
|
|
80828
|
-
child.once("exit", (code) =>
|
|
80829
|
+
child.once("exit", (code) => resolve3(code ?? 1));
|
|
80829
80830
|
});
|
|
80830
80831
|
}
|
|
80831
80832
|
async function launchClineProcess(options, spawnImpl = spawnCommand2) {
|
|
@@ -80891,7 +80892,7 @@ function field(value, label) {
|
|
|
80891
80892
|
throw new Error(`Invalid ${label}`);
|
|
80892
80893
|
return parsed.toString();
|
|
80893
80894
|
}
|
|
80894
|
-
function
|
|
80895
|
+
function validateBaseCreditWitness(witness) {
|
|
80895
80896
|
if (typeof witness.root !== "string" || witness.pathElements.length !== TREE_DEPTH || witness.pathIndices.length !== TREE_DEPTH || !witness.pathElements.every((value) => /^\d+$/u.test(value)) || !witness.pathIndices.every((value) => value === 0 || value === 1)) {
|
|
80896
80897
|
throw new Error("Base membership witness is malformed");
|
|
80897
80898
|
}
|
|
@@ -80923,6 +80924,73 @@ function requestBodyBytes(body) {
|
|
|
80923
80924
|
return new Uint8Array();
|
|
80924
80925
|
throw new Error("The Base x402 sidecar requires the exact request-body bytes");
|
|
80925
80926
|
}
|
|
80927
|
+
function createBasePaymentFactory(options) {
|
|
80928
|
+
const secret = secretFromBase64Url(options.credential.secret);
|
|
80929
|
+
return async ({ method, url, body, requirements }) => {
|
|
80930
|
+
if (requirements.extra.deploymentDomain !== options.credential.deploymentDomain) {
|
|
80931
|
+
throw new Error("Credential deployment domain does not match the gateway challenge");
|
|
80932
|
+
}
|
|
80933
|
+
const slotLedger = options.slotLedger;
|
|
80934
|
+
if (!slotLedger)
|
|
80935
|
+
throw new Error("A durable slot ledger is required for the Base pilot");
|
|
80936
|
+
const selectedSlot = slotLedger.allocateProvisional();
|
|
80937
|
+
try {
|
|
80938
|
+
const nonce = randomNonce();
|
|
80939
|
+
const responseKeys = await responseKey();
|
|
80940
|
+
const requestSignal = await deriveRequestSignal({
|
|
80941
|
+
method,
|
|
80942
|
+
url,
|
|
80943
|
+
body: requestBodyBytes(body),
|
|
80944
|
+
requirements,
|
|
80945
|
+
nonce,
|
|
80946
|
+
responseKey: responseKeys.publicKey
|
|
80947
|
+
});
|
|
80948
|
+
const witness = validateBaseCreditWitness(await options.witnessProvider.witnessForCredential(options.credential));
|
|
80949
|
+
const expiry = witness.expiry ?? options.credential.expiry;
|
|
80950
|
+
if (!Number.isSafeInteger(expiry) || expiry <= 0)
|
|
80951
|
+
throw new Error("Invalid Base credential expiry");
|
|
80952
|
+
const slotBlinding = await computeSlotBlinding(secret, selectedSlot, options.credential.deploymentDomain);
|
|
80953
|
+
const nullifier = await computeNullifier(slotBlinding);
|
|
80954
|
+
const share = await computeShare(secret, requestSignal.field, slotBlinding);
|
|
80955
|
+
const timestamp = String(requirements.extra.issuedAt);
|
|
80956
|
+
const expectedPublicSignals = [
|
|
80957
|
+
witness.root,
|
|
80958
|
+
timestamp,
|
|
80959
|
+
options.credential.deploymentDomain,
|
|
80960
|
+
requestSignal.field,
|
|
80961
|
+
nullifier,
|
|
80962
|
+
share
|
|
80963
|
+
];
|
|
80964
|
+
const proof = await options.prove({
|
|
80965
|
+
secret: secretToField(secret),
|
|
80966
|
+
tier_id: String(options.credential.tierId),
|
|
80967
|
+
expiry: String(expiry),
|
|
80968
|
+
slot: String(selectedSlot),
|
|
80969
|
+
merkle_path_elements: witness.pathElements,
|
|
80970
|
+
merkle_path_indices: witness.pathIndices.map(String),
|
|
80971
|
+
root_in: witness.root,
|
|
80972
|
+
timestamp_in: timestamp,
|
|
80973
|
+
domain_in: options.credential.deploymentDomain,
|
|
80974
|
+
request_signal_in: requestSignal.field
|
|
80975
|
+
}, { requirements, credential: options.credential, expectedPublicSignals });
|
|
80976
|
+
if (!Array.isArray(proof.publicSignals) || proof.publicSignals.length !== expectedPublicSignals.length || !proof.publicSignals.every((value, index) => value === expectedPublicSignals[index])) {
|
|
80977
|
+
throw new Error("Proof public signals do not match the canonical statement");
|
|
80978
|
+
}
|
|
80979
|
+
await slotLedger.commit(selectedSlot);
|
|
80980
|
+
const payment = buildPaymentPayload({
|
|
80981
|
+
requirements,
|
|
80982
|
+
proof: proof.proof,
|
|
80983
|
+
publicSignals: [...proof.publicSignals],
|
|
80984
|
+
nonce,
|
|
80985
|
+
responseKey: responseKeys.publicKey
|
|
80986
|
+
});
|
|
80987
|
+
return { payment, responsePrivateKey: responseKeys.privateKey };
|
|
80988
|
+
} catch (error) {
|
|
80989
|
+
slotLedger.release(selectedSlot);
|
|
80990
|
+
throw error;
|
|
80991
|
+
}
|
|
80992
|
+
};
|
|
80993
|
+
}
|
|
80926
80994
|
function decryptReplay(envelopeValue, privateKey, paymentResponse) {
|
|
80927
80995
|
try {
|
|
80928
80996
|
const envelope = JSON.parse(envelopeValue);
|
|
@@ -80941,7 +81009,7 @@ function decryptReplay(envelopeValue, privateKey, paymentResponse) {
|
|
|
80941
81009
|
}
|
|
80942
81010
|
}
|
|
80943
81011
|
function createBasePrepaidClient(options) {
|
|
80944
|
-
const
|
|
81012
|
+
const createPayment = createBasePaymentFactory(options);
|
|
80945
81013
|
const fetcher = options.fetch ?? fetch;
|
|
80946
81014
|
const replayKeys = /* @__PURE__ */ new Map();
|
|
80947
81015
|
const pendingPayments = /* @__PURE__ */ new Map();
|
|
@@ -81088,9 +81156,6 @@ function createBasePrepaidClient(options) {
|
|
|
81088
81156
|
fetch: fetchWithReplay,
|
|
81089
81157
|
...options.lifecycle ? { lifecycle: options.lifecycle } : {},
|
|
81090
81158
|
createPayload: async ({ method, url, body, requirements }) => {
|
|
81091
|
-
if (requirements.extra.deploymentDomain !== options.credential.deploymentDomain) {
|
|
81092
|
-
throw new Error("Credential deployment domain does not match the gateway challenge");
|
|
81093
|
-
}
|
|
81094
81159
|
prunePending();
|
|
81095
81160
|
const key = requestKey(method, url, body, requirements);
|
|
81096
81161
|
const cached = pendingPayments.get(key);
|
|
@@ -81102,70 +81167,15 @@ function createBasePrepaidClient(options) {
|
|
|
81102
81167
|
if (inFlight)
|
|
81103
81168
|
return inFlight;
|
|
81104
81169
|
const paymentPromise = (async () => {
|
|
81105
|
-
const
|
|
81106
|
-
|
|
81107
|
-
|
|
81108
|
-
const
|
|
81109
|
-
|
|
81110
|
-
|
|
81111
|
-
|
|
81112
|
-
|
|
81113
|
-
|
|
81114
|
-
url,
|
|
81115
|
-
body: requestBodyBytes(body),
|
|
81116
|
-
requirements,
|
|
81117
|
-
nonce,
|
|
81118
|
-
responseKey: responseKeys.publicKey
|
|
81119
|
-
});
|
|
81120
|
-
const witness = assertWitness(await options.witnessProvider.witnessForCredential(options.credential));
|
|
81121
|
-
const expiry = witness.expiry ?? options.credential.expiry;
|
|
81122
|
-
if (!Number.isSafeInteger(expiry) || expiry <= 0)
|
|
81123
|
-
throw new Error("Invalid Base credential expiry");
|
|
81124
|
-
const slotBlinding = await computeSlotBlinding(secret, selectedSlot, options.credential.deploymentDomain);
|
|
81125
|
-
const nullifier = await computeNullifier(slotBlinding);
|
|
81126
|
-
const share = await computeShare(secret, requestSignal.field, slotBlinding);
|
|
81127
|
-
const timestamp = String(requirements.extra.issuedAt);
|
|
81128
|
-
const expectedPublicSignals = [
|
|
81129
|
-
witness.root,
|
|
81130
|
-
timestamp,
|
|
81131
|
-
options.credential.deploymentDomain,
|
|
81132
|
-
requestSignal.field,
|
|
81133
|
-
nullifier,
|
|
81134
|
-
share
|
|
81135
|
-
];
|
|
81136
|
-
const proof = await options.prove({
|
|
81137
|
-
secret: secretToField(secret),
|
|
81138
|
-
tier_id: String(options.credential.tierId),
|
|
81139
|
-
expiry: String(expiry),
|
|
81140
|
-
slot: String(selectedSlot),
|
|
81141
|
-
merkle_path_elements: witness.pathElements,
|
|
81142
|
-
merkle_path_indices: witness.pathIndices.map(String),
|
|
81143
|
-
root_in: witness.root,
|
|
81144
|
-
timestamp_in: timestamp,
|
|
81145
|
-
domain_in: options.credential.deploymentDomain,
|
|
81146
|
-
request_signal_in: requestSignal.field
|
|
81147
|
-
}, { requirements, credential: options.credential, expectedPublicSignals });
|
|
81148
|
-
if (!Array.isArray(proof.publicSignals) || proof.publicSignals.length !== expectedPublicSignals.length || !proof.publicSignals.every((value, index) => value === expectedPublicSignals[index])) {
|
|
81149
|
-
throw new Error("Proof public signals do not match the canonical statement");
|
|
81150
|
-
}
|
|
81151
|
-
await slotLedger.commit(selectedSlot);
|
|
81152
|
-
const payment = buildPaymentPayload({
|
|
81153
|
-
requirements,
|
|
81154
|
-
proof: proof.proof,
|
|
81155
|
-
publicSignals: [...proof.publicSignals],
|
|
81156
|
-
nonce,
|
|
81157
|
-
responseKey: responseKeys.publicKey
|
|
81158
|
-
});
|
|
81159
|
-
const expiresAt = Date.now() + REPLAY_TTL_MS;
|
|
81160
|
-
replayKeys.set(nonce, { privateKey: responseKeys.privateKey, expiresAt });
|
|
81161
|
-
pendingPayments.set(key, { payment, expiresAt });
|
|
81162
|
-
pendingByNonce.set(nonce, key);
|
|
81163
|
-
prunePending();
|
|
81164
|
-
return payment;
|
|
81165
|
-
} catch (error) {
|
|
81166
|
-
slotLedger.release(selectedSlot);
|
|
81167
|
-
throw error;
|
|
81168
|
-
}
|
|
81170
|
+
const prepared = await createPayment({ method, url, body, requirements });
|
|
81171
|
+
const payment = prepared.payment;
|
|
81172
|
+
const nonce = payment.payload.nonce;
|
|
81173
|
+
const expiresAt = Date.now() + REPLAY_TTL_MS;
|
|
81174
|
+
replayKeys.set(nonce, { privateKey: prepared.responsePrivateKey, expiresAt });
|
|
81175
|
+
pendingPayments.set(key, { payment, expiresAt });
|
|
81176
|
+
pendingByNonce.set(nonce, key);
|
|
81177
|
+
prunePending();
|
|
81178
|
+
return payment;
|
|
81169
81179
|
})();
|
|
81170
81180
|
paymentPromises.set(key, paymentPromise);
|
|
81171
81181
|
try {
|
|
@@ -81673,8 +81683,8 @@ function proverProcessFactory(proverPath) {
|
|
|
81673
81683
|
execArgv: [],
|
|
81674
81684
|
stdio: ["ignore", "pipe", "pipe", "ipc"]
|
|
81675
81685
|
});
|
|
81676
|
-
const result = new Promise((
|
|
81677
|
-
child.once("message", (message) =>
|
|
81686
|
+
const result = new Promise((resolve3, reject) => {
|
|
81687
|
+
child.once("message", (message) => resolve3(message));
|
|
81678
81688
|
child.once("error", (error) => reject(error));
|
|
81679
81689
|
child.once("exit", (code, signal) => {
|
|
81680
81690
|
if (code !== 0 && signal === null)
|
|
@@ -81688,11 +81698,11 @@ function proverProcessFactory(proverPath) {
|
|
|
81688
81698
|
terminate: async () => {
|
|
81689
81699
|
if (child.exitCode === null && child.signalCode === null)
|
|
81690
81700
|
child.kill("SIGKILL");
|
|
81691
|
-
await new Promise((
|
|
81701
|
+
await new Promise((resolve3) => {
|
|
81692
81702
|
if (child.exitCode !== null || child.signalCode !== null)
|
|
81693
|
-
|
|
81703
|
+
resolve3();
|
|
81694
81704
|
else
|
|
81695
|
-
child.once("exit", () =>
|
|
81705
|
+
child.once("exit", () => resolve3());
|
|
81696
81706
|
});
|
|
81697
81707
|
}
|
|
81698
81708
|
};
|
|
@@ -82001,8 +82011,9 @@ async function runCliCommand(args, dependencies) {
|
|
|
82001
82011
|
const model = setupModel(args);
|
|
82002
82012
|
if (!await dependencies.isCredentialConfigured())
|
|
82003
82013
|
throw new Error("Set ZK_CREDITS_CREDENTIAL_PATH before running zk-credits setup");
|
|
82004
|
-
await dependencies.
|
|
82014
|
+
await dependencies.validateSetupPrerequisites();
|
|
82005
82015
|
await dependencies.ensureSidecar();
|
|
82016
|
+
await dependencies.configureCodex(model);
|
|
82006
82017
|
dependencies.write("ZK Credits is ready for Codex.");
|
|
82007
82018
|
dependencies.write("Run: zk-credits codex");
|
|
82008
82019
|
return 0;
|
|
@@ -82062,6 +82073,39 @@ async function readLoopbackToken(tokenPath) {
|
|
|
82062
82073
|
}
|
|
82063
82074
|
|
|
82064
82075
|
// dist/node-sidecar-lifecycle.js
|
|
82076
|
+
var CHILD_ENVIRONMENT_KEYS = [
|
|
82077
|
+
"HOME",
|
|
82078
|
+
"PATH",
|
|
82079
|
+
"TMP",
|
|
82080
|
+
"TEMP",
|
|
82081
|
+
"TMPDIR",
|
|
82082
|
+
"LANG",
|
|
82083
|
+
"LC_ALL",
|
|
82084
|
+
"TZ",
|
|
82085
|
+
"SystemRoot",
|
|
82086
|
+
"WINDIR",
|
|
82087
|
+
"COMSPEC",
|
|
82088
|
+
"PATHEXT",
|
|
82089
|
+
"ZK_CREDITS_CREDENTIAL_PATH",
|
|
82090
|
+
"ZK_CREDITS_ARTIFACT_DIR",
|
|
82091
|
+
"ZK_CREDITS_WITNESS_PATH",
|
|
82092
|
+
"ZK_CREDITS_GATEWAY_URL",
|
|
82093
|
+
"BASE_RPC_URL",
|
|
82094
|
+
"BASE_PRIVATE_CREDIT_BOND_ADDRESS",
|
|
82095
|
+
"BASE_DEPLOYMENT_BLOCK",
|
|
82096
|
+
"BASE_CONFIRMATIONS"
|
|
82097
|
+
];
|
|
82098
|
+
function sidecarEnvironment(stateDirectory2, port) {
|
|
82099
|
+
const environment = {};
|
|
82100
|
+
for (const key of CHILD_ENVIRONMENT_KEYS) {
|
|
82101
|
+
const value = process.env[key];
|
|
82102
|
+
if (value !== void 0)
|
|
82103
|
+
environment[key] = value;
|
|
82104
|
+
}
|
|
82105
|
+
environment.ZK_CREDITS_HOME = stateDirectory2;
|
|
82106
|
+
environment.ZK_CREDITS_SIDECAR_PORT = port;
|
|
82107
|
+
return environment;
|
|
82108
|
+
}
|
|
82065
82109
|
async function startDetachedProcess(specification) {
|
|
82066
82110
|
await mkdir6(dirname5(specification.logPath), { recursive: true, mode: 448 });
|
|
82067
82111
|
const log = await open(specification.logPath, "a", 384);
|
|
@@ -82070,12 +82114,16 @@ async function startDetachedProcess(specification) {
|
|
|
82070
82114
|
const child = spawn3(specification.executable, specification.args, {
|
|
82071
82115
|
detached: true,
|
|
82072
82116
|
env: specification.env,
|
|
82073
|
-
stdio: ["ignore", log.fd, log.fd]
|
|
82117
|
+
stdio: [specification.stdin === void 0 ? "ignore" : "pipe", log.fd, log.fd]
|
|
82074
82118
|
});
|
|
82075
|
-
await new Promise((
|
|
82076
|
-
child.once("spawn",
|
|
82119
|
+
await new Promise((resolve3, reject) => {
|
|
82120
|
+
child.once("spawn", resolve3);
|
|
82077
82121
|
child.once("error", reject);
|
|
82078
82122
|
});
|
|
82123
|
+
if (specification.stdin !== void 0 && child.stdin) {
|
|
82124
|
+
child.stdin.on("error", () => void 0);
|
|
82125
|
+
child.stdin.end(specification.stdin);
|
|
82126
|
+
}
|
|
82079
82127
|
child.unref();
|
|
82080
82128
|
} finally {
|
|
82081
82129
|
await log.close();
|
|
@@ -82084,7 +82132,7 @@ async function startDetachedProcess(specification) {
|
|
|
82084
82132
|
var defaultRuntime = {
|
|
82085
82133
|
fetchHealth: async (url) => fetch(url, { signal: AbortSignal.timeout(500) }),
|
|
82086
82134
|
startDetachedProcess,
|
|
82087
|
-
wait: async (milliseconds) => new Promise((
|
|
82135
|
+
wait: async (milliseconds) => new Promise((resolve3) => setTimeout(resolve3, milliseconds))
|
|
82088
82136
|
};
|
|
82089
82137
|
function createNodeSidecarLifecycle(options, runtime = defaultRuntime) {
|
|
82090
82138
|
const url = new URL(options.loopbackBaseUrl);
|
|
@@ -82105,15 +82153,15 @@ function createNodeSidecarLifecycle(options, runtime = defaultRuntime) {
|
|
|
82105
82153
|
}
|
|
82106
82154
|
},
|
|
82107
82155
|
async startDetached() {
|
|
82156
|
+
if (!options.readCredentialPassword)
|
|
82157
|
+
throw new Error("Credential password prompt is unavailable");
|
|
82158
|
+
const password = await options.readCredentialPassword();
|
|
82108
82159
|
await runtime.startDetachedProcess({
|
|
82109
82160
|
executable: process.execPath,
|
|
82110
|
-
args: [options.cliEntryPath, "serve", "--port", url.port],
|
|
82111
|
-
env:
|
|
82112
|
-
|
|
82113
|
-
|
|
82114
|
-
ZK_CREDITS_SIDECAR_PORT: url.port
|
|
82115
|
-
},
|
|
82116
|
-
logPath: options.logPath
|
|
82161
|
+
args: [options.cliEntryPath, "serve", "--port", url.port, "--credential-password-stdin"],
|
|
82162
|
+
env: sidecarEnvironment(options.stateDirectory, url.port),
|
|
82163
|
+
logPath: options.logPath,
|
|
82164
|
+
stdin: password
|
|
82117
82165
|
});
|
|
82118
82166
|
},
|
|
82119
82167
|
readToken: () => readLoopbackToken(options.tokenPath),
|
|
@@ -82128,6 +82176,305 @@ async function activateSidecarServer(activation) {
|
|
|
82128
82176
|
return address2;
|
|
82129
82177
|
}
|
|
82130
82178
|
|
|
82179
|
+
// dist/setup-config.js
|
|
82180
|
+
import { randomUUID } from "node:crypto";
|
|
82181
|
+
import { chmod as chmod5, lstat, mkdir as mkdir7, open as open2, readFile as readFile5, readdir, realpath as realpath2, rename as rename4, rm } from "node:fs/promises";
|
|
82182
|
+
import { dirname as dirname6, join as join5, resolve as resolve2 } from "node:path";
|
|
82183
|
+
var WITNESS_FILENAMES = /* @__PURE__ */ new Set([
|
|
82184
|
+
"base-tree.json",
|
|
82185
|
+
"base-sepolia-tree.json",
|
|
82186
|
+
"base-tree-artifact.json",
|
|
82187
|
+
"public-tree.json",
|
|
82188
|
+
"base-witness.json",
|
|
82189
|
+
"zk-credits-witness.json",
|
|
82190
|
+
"witness.json",
|
|
82191
|
+
"tree.json"
|
|
82192
|
+
]);
|
|
82193
|
+
function isRecord2(value) {
|
|
82194
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
82195
|
+
}
|
|
82196
|
+
function absolutePath(value, label) {
|
|
82197
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
82198
|
+
throw new Error("Setup configuration " + label + " is required");
|
|
82199
|
+
}
|
|
82200
|
+
return resolve2(value);
|
|
82201
|
+
}
|
|
82202
|
+
function optionalUnsignedString(value, label) {
|
|
82203
|
+
if (value === void 0)
|
|
82204
|
+
return void 0;
|
|
82205
|
+
if (typeof value !== "string" || !/^\d+$/u.test(value)) {
|
|
82206
|
+
throw new Error("Local setup config " + label + " must be a non-negative integer");
|
|
82207
|
+
}
|
|
82208
|
+
return value;
|
|
82209
|
+
}
|
|
82210
|
+
function parseSetupConfig(value) {
|
|
82211
|
+
if (!isRecord2(value) || value.version !== 1 || !isRecord2(value.witness)) {
|
|
82212
|
+
throw new Error("Local setup config is malformed; remove ~/.zk-credits/config.json and run setup again.");
|
|
82213
|
+
}
|
|
82214
|
+
const artifactDirectory = absolutePath(value.artifactDirectory, "artifactDirectory");
|
|
82215
|
+
const witnessValue = value.witness;
|
|
82216
|
+
let witness;
|
|
82217
|
+
if (witnessValue.kind === "file") {
|
|
82218
|
+
witness = { kind: "file", path: absolutePath(witnessValue.path, "witness.path") };
|
|
82219
|
+
} else if (witnessValue.kind === "base-events") {
|
|
82220
|
+
if (typeof witnessValue.rpcUrl !== "string" || !/^https?:\/\//u.test(witnessValue.rpcUrl)) {
|
|
82221
|
+
throw new Error("Local setup config has an invalid Base RPC URL");
|
|
82222
|
+
}
|
|
82223
|
+
if (typeof witnessValue.contractAddress !== "string" || !/^0x[0-9a-fA-F]{40}$/u.test(witnessValue.contractAddress)) {
|
|
82224
|
+
throw new Error("Local setup config has an invalid Base bond contract address");
|
|
82225
|
+
}
|
|
82226
|
+
const deploymentBlock = optionalUnsignedString(witnessValue.deploymentBlock, "deploymentBlock");
|
|
82227
|
+
const confirmations = optionalUnsignedString(witnessValue.confirmations, "confirmations");
|
|
82228
|
+
witness = {
|
|
82229
|
+
kind: "base-events",
|
|
82230
|
+
rpcUrl: witnessValue.rpcUrl,
|
|
82231
|
+
contractAddress: witnessValue.contractAddress,
|
|
82232
|
+
...deploymentBlock === void 0 ? {} : { deploymentBlock },
|
|
82233
|
+
...confirmations === void 0 ? {} : { confirmations }
|
|
82234
|
+
};
|
|
82235
|
+
} else {
|
|
82236
|
+
throw new Error("Local setup config has an unknown witness source");
|
|
82237
|
+
}
|
|
82238
|
+
return { version: 1, artifactDirectory, witness };
|
|
82239
|
+
}
|
|
82240
|
+
function optionalEnvironmentInteger(environment, name) {
|
|
82241
|
+
const value = environment[name]?.trim();
|
|
82242
|
+
if (!value)
|
|
82243
|
+
return void 0;
|
|
82244
|
+
if (!/^\d+$/u.test(value))
|
|
82245
|
+
throw new Error(name + " must be a non-negative integer");
|
|
82246
|
+
return value;
|
|
82247
|
+
}
|
|
82248
|
+
async function candidateDirectories(homeDirectory, stateDirectory2) {
|
|
82249
|
+
const roots = [
|
|
82250
|
+
join5(stateDirectory2, "artifacts", "base-sepolia"),
|
|
82251
|
+
join5(homeDirectory, ".zk-credits", "artifacts", "base-sepolia"),
|
|
82252
|
+
join5(homeDirectory, "Downloads")
|
|
82253
|
+
];
|
|
82254
|
+
const candidates = [...roots];
|
|
82255
|
+
for (const root of roots) {
|
|
82256
|
+
let entries;
|
|
82257
|
+
try {
|
|
82258
|
+
entries = await readdir(root, { withFileTypes: true });
|
|
82259
|
+
} catch {
|
|
82260
|
+
continue;
|
|
82261
|
+
}
|
|
82262
|
+
for (const entry of entries) {
|
|
82263
|
+
if (entry.isDirectory())
|
|
82264
|
+
candidates.push(join5(root, entry.name));
|
|
82265
|
+
}
|
|
82266
|
+
}
|
|
82267
|
+
return [...new Set(candidates.map((path) => resolve2(path)))];
|
|
82268
|
+
}
|
|
82269
|
+
async function chooseOne(kind, candidates, chooseCandidate) {
|
|
82270
|
+
if (candidates.length === 1)
|
|
82271
|
+
return candidates[0];
|
|
82272
|
+
if (!chooseCandidate) {
|
|
82273
|
+
const variable = kind === "proving bundle" ? "ZK_CREDITS_ARTIFACT_DIR" : "ZK_CREDITS_WITNESS_PATH";
|
|
82274
|
+
throw new Error("Found more than one valid " + kind + "; set " + variable + " to choose one.");
|
|
82275
|
+
}
|
|
82276
|
+
const selected = await chooseCandidate(kind, candidates);
|
|
82277
|
+
if (!candidates.includes(resolve2(selected))) {
|
|
82278
|
+
throw new Error("The selected " + kind + " is not one of the validated local candidates");
|
|
82279
|
+
}
|
|
82280
|
+
return resolve2(selected);
|
|
82281
|
+
}
|
|
82282
|
+
async function resolveArtifactDirectory(options, saved) {
|
|
82283
|
+
const explicit = options.environment.ZK_CREDITS_ARTIFACT_DIR?.trim();
|
|
82284
|
+
const candidates = explicit ? [resolve2(options.workingDirectory ?? process.cwd(), explicit)] : [
|
|
82285
|
+
...saved ? [saved.artifactDirectory] : [],
|
|
82286
|
+
...await candidateDirectories(options.homeDirectory, options.stateDirectory)
|
|
82287
|
+
];
|
|
82288
|
+
const valid = /* @__PURE__ */ new Map();
|
|
82289
|
+
let explicitError;
|
|
82290
|
+
for (const candidate of candidates) {
|
|
82291
|
+
try {
|
|
82292
|
+
const bundle = await resolvePinnedArtifactBundle({
|
|
82293
|
+
artifactDirectory: candidate,
|
|
82294
|
+
manifest: options.manifest
|
|
82295
|
+
});
|
|
82296
|
+
let identity = resolve2(bundle.directory);
|
|
82297
|
+
try {
|
|
82298
|
+
identity = await realpath2(bundle.directory);
|
|
82299
|
+
} catch {
|
|
82300
|
+
}
|
|
82301
|
+
valid.set(identity, bundle.directory);
|
|
82302
|
+
} catch (error) {
|
|
82303
|
+
if (explicit)
|
|
82304
|
+
explicitError = error;
|
|
82305
|
+
}
|
|
82306
|
+
}
|
|
82307
|
+
if (explicit && valid.size === 0) {
|
|
82308
|
+
const reason = explicitError instanceof Error ? " " + explicitError.message : "";
|
|
82309
|
+
throw new Error("The configured proving bundle at " + explicit + " failed its pinned checks." + reason);
|
|
82310
|
+
}
|
|
82311
|
+
if (valid.size === 0) {
|
|
82312
|
+
throw new Error("Could not find a valid pinned proving bundle. Extract the bundle from your pilot contact into ~/.zk-credits/artifacts/base-sepolia or ~/Downloads, or set ZK_CREDITS_ARTIFACT_DIR.");
|
|
82313
|
+
}
|
|
82314
|
+
const selected = await chooseOne("proving bundle", [...valid.values()], options.chooseCandidate);
|
|
82315
|
+
return resolve2(selected);
|
|
82316
|
+
}
|
|
82317
|
+
function eventSourceFromEnvironment(environment) {
|
|
82318
|
+
const rpcUrl = environment.BASE_RPC_URL?.trim();
|
|
82319
|
+
const contractAddress = environment.BASE_PRIVATE_CREDIT_BOND_ADDRESS?.trim();
|
|
82320
|
+
if (!rpcUrl || !contractAddress)
|
|
82321
|
+
return void 0;
|
|
82322
|
+
const deploymentBlock = optionalEnvironmentInteger(environment, "BASE_DEPLOYMENT_BLOCK");
|
|
82323
|
+
const confirmations = optionalEnvironmentInteger(environment, "BASE_CONFIRMATIONS");
|
|
82324
|
+
return {
|
|
82325
|
+
kind: "base-events",
|
|
82326
|
+
rpcUrl,
|
|
82327
|
+
contractAddress,
|
|
82328
|
+
...deploymentBlock === void 0 ? {} : { deploymentBlock },
|
|
82329
|
+
...confirmations === void 0 ? {} : { confirmations }
|
|
82330
|
+
};
|
|
82331
|
+
}
|
|
82332
|
+
function witnessCandidates(homeDirectory, stateDirectory2) {
|
|
82333
|
+
const roots = [
|
|
82334
|
+
join5(stateDirectory2, "witnesses"),
|
|
82335
|
+
join5(stateDirectory2, "witness"),
|
|
82336
|
+
join5(homeDirectory, ".zk-credits", "witnesses"),
|
|
82337
|
+
join5(homeDirectory, "Downloads")
|
|
82338
|
+
];
|
|
82339
|
+
return [...new Set(roots.flatMap((root) => [...WITNESS_FILENAMES].map((name) => resolve2(root, name))))];
|
|
82340
|
+
}
|
|
82341
|
+
async function resolveWitnessSource(options, saved) {
|
|
82342
|
+
const environment = options.environment;
|
|
82343
|
+
const explicitPath = environment.ZK_CREDITS_WITNESS_PATH?.trim();
|
|
82344
|
+
if (explicitPath) {
|
|
82345
|
+
const source = {
|
|
82346
|
+
kind: "file",
|
|
82347
|
+
path: resolve2(options.workingDirectory ?? process.cwd(), explicitPath)
|
|
82348
|
+
};
|
|
82349
|
+
try {
|
|
82350
|
+
await options.validateWitness(source);
|
|
82351
|
+
return source;
|
|
82352
|
+
} catch (error) {
|
|
82353
|
+
const reason = error instanceof Error ? " " + error.message : "";
|
|
82354
|
+
throw new Error("The configured Base witness at " + explicitPath + " failed validation." + reason);
|
|
82355
|
+
}
|
|
82356
|
+
}
|
|
82357
|
+
const environmentSource = eventSourceFromEnvironment(environment);
|
|
82358
|
+
if (environmentSource) {
|
|
82359
|
+
try {
|
|
82360
|
+
await options.validateWitness(environmentSource);
|
|
82361
|
+
return environmentSource;
|
|
82362
|
+
} catch (error) {
|
|
82363
|
+
const reason = error instanceof Error ? " " + error.message : "";
|
|
82364
|
+
throw new Error("Base event witness sync failed." + reason);
|
|
82365
|
+
}
|
|
82366
|
+
}
|
|
82367
|
+
if (saved?.witness.kind === "base-events") {
|
|
82368
|
+
try {
|
|
82369
|
+
await options.validateWitness(saved.witness);
|
|
82370
|
+
return saved.witness;
|
|
82371
|
+
} catch (error) {
|
|
82372
|
+
const reason = error instanceof Error ? " " + error.message : "";
|
|
82373
|
+
throw new Error("Saved Base event witness source failed validation." + reason);
|
|
82374
|
+
}
|
|
82375
|
+
}
|
|
82376
|
+
if (saved?.witness.kind === "file") {
|
|
82377
|
+
try {
|
|
82378
|
+
await options.validateWitness(saved.witness);
|
|
82379
|
+
return saved.witness;
|
|
82380
|
+
} catch {
|
|
82381
|
+
}
|
|
82382
|
+
}
|
|
82383
|
+
const valid = [];
|
|
82384
|
+
for (const path of witnessCandidates(options.homeDirectory, options.stateDirectory)) {
|
|
82385
|
+
try {
|
|
82386
|
+
const info = await lstat(path);
|
|
82387
|
+
if (!info.isFile())
|
|
82388
|
+
continue;
|
|
82389
|
+
const source = { kind: "file", path };
|
|
82390
|
+
await options.validateWitness(source);
|
|
82391
|
+
valid.push(path);
|
|
82392
|
+
} catch {
|
|
82393
|
+
}
|
|
82394
|
+
}
|
|
82395
|
+
if (valid.length > 0) {
|
|
82396
|
+
return { kind: "file", path: await chooseOne("witness file", valid, options.chooseCandidate) };
|
|
82397
|
+
}
|
|
82398
|
+
throw new Error("Could not find a public Base witness for this credential. Put base-tree.json or witness.json in ~/.zk-credits/witnesses or ~/Downloads, set ZK_CREDITS_WITNESS_PATH, or configure BASE_RPC_URL and BASE_PRIVATE_CREDIT_BOND_ADDRESS.");
|
|
82399
|
+
}
|
|
82400
|
+
async function resolveSetupInputs(options) {
|
|
82401
|
+
const saved = await readSetupConfig(options.configPath);
|
|
82402
|
+
const artifactDirectory = await resolveArtifactDirectory(options, saved);
|
|
82403
|
+
const witness = await resolveWitnessSource(options, saved);
|
|
82404
|
+
return { version: 1, artifactDirectory, witness };
|
|
82405
|
+
}
|
|
82406
|
+
async function readSetupConfig(path) {
|
|
82407
|
+
let raw;
|
|
82408
|
+
try {
|
|
82409
|
+
const info = await lstat(path);
|
|
82410
|
+
if (!info.isFile())
|
|
82411
|
+
throw new Error("Local setup config must be a regular file");
|
|
82412
|
+
raw = await readFile5(path, "utf8");
|
|
82413
|
+
} catch (error) {
|
|
82414
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
|
|
82415
|
+
return void 0;
|
|
82416
|
+
throw error;
|
|
82417
|
+
}
|
|
82418
|
+
try {
|
|
82419
|
+
return parseSetupConfig(JSON.parse(raw));
|
|
82420
|
+
} catch (error) {
|
|
82421
|
+
if (error instanceof SyntaxError) {
|
|
82422
|
+
throw new Error("Local setup config is not valid JSON; remove ~/.zk-credits/config.json and run setup again.");
|
|
82423
|
+
}
|
|
82424
|
+
throw error;
|
|
82425
|
+
}
|
|
82426
|
+
}
|
|
82427
|
+
async function writeSetupConfig(path, config) {
|
|
82428
|
+
const normalized = parseSetupConfig(config);
|
|
82429
|
+
const directory = dirname6(resolve2(path));
|
|
82430
|
+
await mkdir7(directory, { recursive: true, mode: 448 });
|
|
82431
|
+
const destination = resolve2(path);
|
|
82432
|
+
try {
|
|
82433
|
+
const existing = await lstat(destination);
|
|
82434
|
+
if (existing.isSymbolicLink())
|
|
82435
|
+
throw new Error("Local setup config cannot be a symbolic link");
|
|
82436
|
+
} catch (error) {
|
|
82437
|
+
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT"))
|
|
82438
|
+
throw error;
|
|
82439
|
+
}
|
|
82440
|
+
const temporary = join5(directory, ".config-" + randomUUID() + ".tmp");
|
|
82441
|
+
try {
|
|
82442
|
+
const file = await open2(temporary, "wx", 384);
|
|
82443
|
+
try {
|
|
82444
|
+
await file.writeFile(JSON.stringify(normalized, null, 2) + "\n", "utf8");
|
|
82445
|
+
await file.sync();
|
|
82446
|
+
} finally {
|
|
82447
|
+
await file.close();
|
|
82448
|
+
}
|
|
82449
|
+
await rename4(temporary, destination);
|
|
82450
|
+
await chmod5(destination, 384);
|
|
82451
|
+
} finally {
|
|
82452
|
+
await rm(temporary, { force: true });
|
|
82453
|
+
}
|
|
82454
|
+
}
|
|
82455
|
+
function applySetupConfig(environment, config) {
|
|
82456
|
+
if (!environment.ZK_CREDITS_ARTIFACT_DIR?.trim()) {
|
|
82457
|
+
environment.ZK_CREDITS_ARTIFACT_DIR = config.artifactDirectory;
|
|
82458
|
+
}
|
|
82459
|
+
if (config.witness.kind === "file") {
|
|
82460
|
+
if (!environment.ZK_CREDITS_WITNESS_PATH?.trim()) {
|
|
82461
|
+
environment.ZK_CREDITS_WITNESS_PATH = config.witness.path;
|
|
82462
|
+
}
|
|
82463
|
+
return;
|
|
82464
|
+
}
|
|
82465
|
+
if (!environment.BASE_RPC_URL?.trim())
|
|
82466
|
+
environment.BASE_RPC_URL = config.witness.rpcUrl;
|
|
82467
|
+
if (!environment.BASE_PRIVATE_CREDIT_BOND_ADDRESS?.trim()) {
|
|
82468
|
+
environment.BASE_PRIVATE_CREDIT_BOND_ADDRESS = config.witness.contractAddress;
|
|
82469
|
+
}
|
|
82470
|
+
if (!environment.BASE_DEPLOYMENT_BLOCK?.trim() && config.witness.deploymentBlock !== void 0) {
|
|
82471
|
+
environment.BASE_DEPLOYMENT_BLOCK = config.witness.deploymentBlock;
|
|
82472
|
+
}
|
|
82473
|
+
if (!environment.BASE_CONFIRMATIONS?.trim() && config.witness.confirmations !== void 0) {
|
|
82474
|
+
environment.BASE_CONFIRMATIONS = config.witness.confirmations;
|
|
82475
|
+
}
|
|
82476
|
+
}
|
|
82477
|
+
|
|
82131
82478
|
// dist/sidecar-lifecycle.js
|
|
82132
82479
|
async function ensureSidecarReady(dependencies, options = {}) {
|
|
82133
82480
|
if (await dependencies.isHealthy())
|
|
@@ -82145,6 +82492,331 @@ async function ensureSidecarReady(dependencies, options = {}) {
|
|
|
82145
82492
|
|
|
82146
82493
|
// dist/sidecar.js
|
|
82147
82494
|
import { createServer } from "node:http";
|
|
82495
|
+
|
|
82496
|
+
// dist/responses-bridge.js
|
|
82497
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
82498
|
+
function isRecord3(value) {
|
|
82499
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
82500
|
+
}
|
|
82501
|
+
function hasOnlyKeys(value, allowed) {
|
|
82502
|
+
return Object.keys(value).every((key) => allowed.includes(key));
|
|
82503
|
+
}
|
|
82504
|
+
function textContent(value) {
|
|
82505
|
+
if (typeof value === "string")
|
|
82506
|
+
return value;
|
|
82507
|
+
if (!Array.isArray(value))
|
|
82508
|
+
return void 0;
|
|
82509
|
+
const parts = [];
|
|
82510
|
+
for (const part of value) {
|
|
82511
|
+
if (!isRecord3(part) || !hasOnlyKeys(part, ["type", "text"]) || part.type !== "input_text" && part.type !== "output_text" || typeof part.text !== "string")
|
|
82512
|
+
return void 0;
|
|
82513
|
+
parts.push({ type: "text", text: part.text });
|
|
82514
|
+
}
|
|
82515
|
+
return parts.length === 1 ? parts[0].text : parts;
|
|
82516
|
+
}
|
|
82517
|
+
function responseInputMessages(input) {
|
|
82518
|
+
if (typeof input === "string")
|
|
82519
|
+
return [{ role: "user", content: input }];
|
|
82520
|
+
if (!Array.isArray(input))
|
|
82521
|
+
return void 0;
|
|
82522
|
+
const messages = [];
|
|
82523
|
+
for (const item of input) {
|
|
82524
|
+
if (!isRecord3(item) || typeof item.type !== "string")
|
|
82525
|
+
return void 0;
|
|
82526
|
+
if (item.type === "message") {
|
|
82527
|
+
if (!hasOnlyKeys(item, ["type", "id", "role", "content"]) || item.id !== void 0 && typeof item.id !== "string" || !["system", "developer", "user", "assistant"].includes(String(item.role)))
|
|
82528
|
+
return void 0;
|
|
82529
|
+
const content = textContent(item.content);
|
|
82530
|
+
if (content === void 0)
|
|
82531
|
+
return void 0;
|
|
82532
|
+
messages.push({ role: item.role, content });
|
|
82533
|
+
continue;
|
|
82534
|
+
}
|
|
82535
|
+
if (item.type === "function_call") {
|
|
82536
|
+
if (!hasOnlyKeys(item, ["type", "id", "status", "call_id", "name", "arguments"]) || typeof item.call_id !== "string" || typeof item.name !== "string" || typeof item.arguments !== "string" || item.id !== void 0 && typeof item.id !== "string" || item.status !== void 0 && typeof item.status !== "string")
|
|
82537
|
+
return void 0;
|
|
82538
|
+
messages.push({
|
|
82539
|
+
role: "assistant",
|
|
82540
|
+
content: null,
|
|
82541
|
+
tool_calls: [{ id: item.call_id, type: "function", function: { name: item.name, arguments: item.arguments } }]
|
|
82542
|
+
});
|
|
82543
|
+
continue;
|
|
82544
|
+
}
|
|
82545
|
+
if (item.type === "function_call_output") {
|
|
82546
|
+
if (!hasOnlyKeys(item, ["type", "id", "status", "call_id", "output"]) || typeof item.call_id !== "string" || typeof item.output !== "string" || item.id !== void 0 && typeof item.id !== "string" || item.status !== void 0 && typeof item.status !== "string")
|
|
82547
|
+
return void 0;
|
|
82548
|
+
messages.push({ role: "tool", tool_call_id: item.call_id, content: item.output });
|
|
82549
|
+
continue;
|
|
82550
|
+
}
|
|
82551
|
+
return void 0;
|
|
82552
|
+
}
|
|
82553
|
+
return messages;
|
|
82554
|
+
}
|
|
82555
|
+
function responseTools(value) {
|
|
82556
|
+
if (!Array.isArray(value))
|
|
82557
|
+
return void 0;
|
|
82558
|
+
const tools = [];
|
|
82559
|
+
for (const tool of value) {
|
|
82560
|
+
if (!isRecord3(tool) || typeof tool.type !== "string")
|
|
82561
|
+
return void 0;
|
|
82562
|
+
if (tool.type === "function") {
|
|
82563
|
+
if (!hasOnlyKeys(tool, ["type", "name", "description", "parameters", "strict"]) || typeof tool.name !== "string" || tool.name.length === 0 || tool.description !== void 0 && typeof tool.description !== "string" || tool.parameters !== void 0 && !isRecord3(tool.parameters) || tool.strict !== void 0 && typeof tool.strict !== "boolean")
|
|
82564
|
+
return void 0;
|
|
82565
|
+
const definition = { name: tool.name };
|
|
82566
|
+
if (tool.description !== void 0)
|
|
82567
|
+
definition.description = tool.description;
|
|
82568
|
+
if (tool.parameters !== void 0)
|
|
82569
|
+
definition.parameters = tool.parameters;
|
|
82570
|
+
if (tool.strict !== void 0)
|
|
82571
|
+
definition.strict = tool.strict;
|
|
82572
|
+
tools.push({ type: "function", function: definition });
|
|
82573
|
+
continue;
|
|
82574
|
+
}
|
|
82575
|
+
if (tool.type === "web_search") {
|
|
82576
|
+
if (!hasOnlyKeys(tool, ["type", "external_web_access"]) || tool.external_web_access !== void 0 && typeof tool.external_web_access !== "boolean")
|
|
82577
|
+
return void 0;
|
|
82578
|
+
continue;
|
|
82579
|
+
}
|
|
82580
|
+
if (tool.type === "namespace") {
|
|
82581
|
+
if (!hasOnlyKeys(tool, ["type", "name", "description", "tools"]) || typeof tool.name !== "string" || tool.description !== void 0 && typeof tool.description !== "string" || !Array.isArray(tool.tools) || tool.tools.some((nested) => !isRecord3(nested) || nested.type !== "function" || typeof nested.name !== "string"))
|
|
82582
|
+
return void 0;
|
|
82583
|
+
continue;
|
|
82584
|
+
}
|
|
82585
|
+
return void 0;
|
|
82586
|
+
}
|
|
82587
|
+
return tools;
|
|
82588
|
+
}
|
|
82589
|
+
function translatedToolChoice(value) {
|
|
82590
|
+
if (value === "none" || value === "auto" || value === "required")
|
|
82591
|
+
return value;
|
|
82592
|
+
if (!isRecord3(value) || value.type !== "function" || !hasOnlyKeys(value, ["type", "name"]) || typeof value.name !== "string")
|
|
82593
|
+
return void 0;
|
|
82594
|
+
return { type: "function", function: { name: value.name } };
|
|
82595
|
+
}
|
|
82596
|
+
function translateResponsesRequest(body) {
|
|
82597
|
+
if (!isRecord3(body))
|
|
82598
|
+
return { ok: false, error: "invalid_request_body" };
|
|
82599
|
+
const allowed = [
|
|
82600
|
+
"model",
|
|
82601
|
+
"instructions",
|
|
82602
|
+
"input",
|
|
82603
|
+
"stream",
|
|
82604
|
+
"tools",
|
|
82605
|
+
"tool_choice",
|
|
82606
|
+
"max_output_tokens",
|
|
82607
|
+
"parallel_tool_calls",
|
|
82608
|
+
"store",
|
|
82609
|
+
"client_metadata",
|
|
82610
|
+
"prompt_cache_key",
|
|
82611
|
+
"include",
|
|
82612
|
+
"reasoning",
|
|
82613
|
+
"temperature",
|
|
82614
|
+
"top_p",
|
|
82615
|
+
"stop",
|
|
82616
|
+
"seed",
|
|
82617
|
+
"presence_penalty",
|
|
82618
|
+
"frequency_penalty",
|
|
82619
|
+
"logit_bias"
|
|
82620
|
+
];
|
|
82621
|
+
if (!hasOnlyKeys(body, allowed))
|
|
82622
|
+
return { ok: false, error: "unsupported_request_field" };
|
|
82623
|
+
if (typeof body.model !== "string" || body.model.length === 0)
|
|
82624
|
+
return { ok: false, error: "model_required" };
|
|
82625
|
+
if (body.stream !== true)
|
|
82626
|
+
return { ok: false, error: "streaming_required" };
|
|
82627
|
+
if (body.store !== void 0 && body.store !== false)
|
|
82628
|
+
return { ok: false, error: "stored_responses_unsupported" };
|
|
82629
|
+
if (body.instructions !== void 0 && typeof body.instructions !== "string")
|
|
82630
|
+
return { ok: false, error: "invalid_instructions" };
|
|
82631
|
+
if (body.prompt_cache_key !== void 0 && typeof body.prompt_cache_key !== "string")
|
|
82632
|
+
return { ok: false, error: "invalid_prompt_cache_key" };
|
|
82633
|
+
if (body.client_metadata !== void 0 && (!isRecord3(body.client_metadata) || Object.values(body.client_metadata).some((value) => typeof value !== "string"))) {
|
|
82634
|
+
return { ok: false, error: "invalid_client_metadata" };
|
|
82635
|
+
}
|
|
82636
|
+
if (body.include !== void 0 && (!Array.isArray(body.include) || body.include.some((value) => value !== "reasoning.encrypted_content"))) {
|
|
82637
|
+
return { ok: false, error: "unsupported_include" };
|
|
82638
|
+
}
|
|
82639
|
+
if (body.reasoning !== void 0 && (!isRecord3(body.reasoning) || !hasOnlyKeys(body.reasoning, ["summary"]) || body.reasoning.summary !== void 0 && !["auto", "concise", "detailed"].includes(String(body.reasoning.summary)))) {
|
|
82640
|
+
return { ok: false, error: "unsupported_reasoning_controls" };
|
|
82641
|
+
}
|
|
82642
|
+
if (body.parallel_tool_calls !== void 0 && typeof body.parallel_tool_calls !== "boolean") {
|
|
82643
|
+
return { ok: false, error: "invalid_parallel_tool_calls" };
|
|
82644
|
+
}
|
|
82645
|
+
const messages = [];
|
|
82646
|
+
if (body.instructions !== void 0)
|
|
82647
|
+
messages.push({ role: "developer", content: body.instructions });
|
|
82648
|
+
const inputMessages = responseInputMessages(body.input);
|
|
82649
|
+
if (!inputMessages)
|
|
82650
|
+
return { ok: false, error: "unsupported_input_item" };
|
|
82651
|
+
messages.push(...inputMessages);
|
|
82652
|
+
const chatRequest = { model: body.model, messages };
|
|
82653
|
+
if (body.tools !== void 0) {
|
|
82654
|
+
const tools = responseTools(body.tools);
|
|
82655
|
+
if (!tools)
|
|
82656
|
+
return { ok: false, error: "unsupported_tool" };
|
|
82657
|
+
if (tools.length)
|
|
82658
|
+
chatRequest.tools = tools;
|
|
82659
|
+
}
|
|
82660
|
+
if (body.tool_choice !== void 0) {
|
|
82661
|
+
const toolChoice = translatedToolChoice(body.tool_choice);
|
|
82662
|
+
if (toolChoice === void 0)
|
|
82663
|
+
return { ok: false, error: "invalid_tool_choice" };
|
|
82664
|
+
chatRequest.tool_choice = toolChoice;
|
|
82665
|
+
}
|
|
82666
|
+
if (body.max_output_tokens !== void 0) {
|
|
82667
|
+
if (!Number.isInteger(body.max_output_tokens) || body.max_output_tokens <= 0) {
|
|
82668
|
+
return { ok: false, error: "invalid_max_output_tokens" };
|
|
82669
|
+
}
|
|
82670
|
+
chatRequest.max_completion_tokens = body.max_output_tokens;
|
|
82671
|
+
}
|
|
82672
|
+
if (body.parallel_tool_calls !== void 0)
|
|
82673
|
+
chatRequest.parallel_tool_calls = body.parallel_tool_calls;
|
|
82674
|
+
for (const key of ["temperature", "top_p", "stop", "seed", "presence_penalty", "frequency_penalty", "logit_bias"]) {
|
|
82675
|
+
if (body[key] !== void 0)
|
|
82676
|
+
chatRequest[key] = body[key];
|
|
82677
|
+
}
|
|
82678
|
+
return { ok: true, chatRequest, responseModel: body.model };
|
|
82679
|
+
}
|
|
82680
|
+
function usageFor(chat) {
|
|
82681
|
+
if (!isRecord3(chat.usage))
|
|
82682
|
+
return null;
|
|
82683
|
+
const promptTokens = chat.usage.prompt_tokens;
|
|
82684
|
+
const completionTokens = chat.usage.completion_tokens;
|
|
82685
|
+
const totalTokens = chat.usage.total_tokens;
|
|
82686
|
+
if (![promptTokens, completionTokens, totalTokens].every((value) => Number.isInteger(value) && value >= 0))
|
|
82687
|
+
return null;
|
|
82688
|
+
return {
|
|
82689
|
+
input_tokens: promptTokens,
|
|
82690
|
+
output_tokens: completionTokens,
|
|
82691
|
+
total_tokens: totalTokens
|
|
82692
|
+
};
|
|
82693
|
+
}
|
|
82694
|
+
function responsesEventStream(chatValue, model) {
|
|
82695
|
+
if (!isRecord3(chatValue) || !Array.isArray(chatValue.choices) || !isRecord3(chatValue.choices[0])) {
|
|
82696
|
+
throw new Error("Gateway returned an invalid chat completion");
|
|
82697
|
+
}
|
|
82698
|
+
const choice = chatValue.choices[0];
|
|
82699
|
+
if (!isRecord3(choice.message))
|
|
82700
|
+
throw new Error("Gateway returned an invalid chat message");
|
|
82701
|
+
const message = choice.message;
|
|
82702
|
+
const responseSuffix = randomUUID2().replaceAll("-", "");
|
|
82703
|
+
const responseId = `resp_${responseSuffix}`;
|
|
82704
|
+
const events = [];
|
|
82705
|
+
let sequence = 0;
|
|
82706
|
+
const add = (event, data) => {
|
|
82707
|
+
events.push({ event, data: { ...data, sequence_number: sequence++ } });
|
|
82708
|
+
};
|
|
82709
|
+
const createdAt = Number.isInteger(chatValue.created) ? chatValue.created : Math.floor(Date.now() / 1e3);
|
|
82710
|
+
const usage = usageFor(chatValue);
|
|
82711
|
+
const base = {
|
|
82712
|
+
id: responseId,
|
|
82713
|
+
object: "response",
|
|
82714
|
+
created_at: createdAt,
|
|
82715
|
+
status: "in_progress",
|
|
82716
|
+
completed_at: null,
|
|
82717
|
+
error: null,
|
|
82718
|
+
incomplete_details: null,
|
|
82719
|
+
model,
|
|
82720
|
+
output: [],
|
|
82721
|
+
parallel_tool_calls: true,
|
|
82722
|
+
metadata: {},
|
|
82723
|
+
usage: null
|
|
82724
|
+
};
|
|
82725
|
+
add("response.created", { type: "response.created", response: base });
|
|
82726
|
+
add("response.in_progress", { type: "response.in_progress", response: base });
|
|
82727
|
+
const output = [];
|
|
82728
|
+
const text = message.content;
|
|
82729
|
+
const refusal = message.refusal;
|
|
82730
|
+
if (text !== null && text !== void 0 && typeof text !== "string") {
|
|
82731
|
+
throw new Error("Gateway returned an unsupported chat content value");
|
|
82732
|
+
}
|
|
82733
|
+
if (refusal !== void 0 && typeof refusal !== "string")
|
|
82734
|
+
throw new Error("Gateway returned an invalid refusal value");
|
|
82735
|
+
if (typeof text === "string" || typeof refusal === "string") {
|
|
82736
|
+
const itemId = `msg_${randomUUID2().replaceAll("-", "")}`;
|
|
82737
|
+
const isRefusal = typeof refusal === "string";
|
|
82738
|
+
const part = isRefusal ? { type: "refusal", refusal } : { type: "output_text", text: text ?? "", annotations: [] };
|
|
82739
|
+
const item = { id: itemId, type: "message", status: "completed", role: "assistant", content: [part] };
|
|
82740
|
+
add("response.output_item.added", {
|
|
82741
|
+
type: "response.output_item.added",
|
|
82742
|
+
output_index: output.length,
|
|
82743
|
+
item: { id: itemId, type: "message", status: "in_progress", role: "assistant", content: [] }
|
|
82744
|
+
});
|
|
82745
|
+
add("response.content_part.added", {
|
|
82746
|
+
type: "response.content_part.added",
|
|
82747
|
+
output_index: output.length,
|
|
82748
|
+
content_index: 0,
|
|
82749
|
+
part: isRefusal ? { type: "refusal", refusal: "" } : { type: "output_text", text: "", annotations: [] }
|
|
82750
|
+
});
|
|
82751
|
+
if (isRefusal) {
|
|
82752
|
+
add("response.refusal.delta", { type: "response.refusal.delta", item_id: itemId, output_index: output.length, content_index: 0, delta: refusal });
|
|
82753
|
+
add("response.refusal.done", { type: "response.refusal.done", item_id: itemId, output_index: output.length, content_index: 0, refusal });
|
|
82754
|
+
} else {
|
|
82755
|
+
add("response.output_text.delta", { type: "response.output_text.delta", item_id: itemId, output_index: output.length, content_index: 0, delta: text });
|
|
82756
|
+
add("response.output_text.done", { type: "response.output_text.done", item_id: itemId, output_index: output.length, content_index: 0, text });
|
|
82757
|
+
}
|
|
82758
|
+
add("response.content_part.done", { type: "response.content_part.done", output_index: output.length, content_index: 0, part });
|
|
82759
|
+
add("response.output_item.done", { type: "response.output_item.done", output_index: output.length, item });
|
|
82760
|
+
output.push(item);
|
|
82761
|
+
}
|
|
82762
|
+
if (message.tool_calls !== void 0) {
|
|
82763
|
+
if (!Array.isArray(message.tool_calls))
|
|
82764
|
+
throw new Error("Gateway returned invalid tool calls");
|
|
82765
|
+
for (const callValue of message.tool_calls) {
|
|
82766
|
+
if (!isRecord3(callValue) || callValue.type !== "function" || !isRecord3(callValue.function) || typeof callValue.function.name !== "string" || typeof callValue.function.arguments !== "string") {
|
|
82767
|
+
throw new Error("Gateway returned an invalid function call");
|
|
82768
|
+
}
|
|
82769
|
+
const callId = typeof callValue.id === "string" ? callValue.id : `call_${randomUUID2().replaceAll("-", "")}`;
|
|
82770
|
+
const itemId = `fc_${randomUUID2().replaceAll("-", "")}`;
|
|
82771
|
+
const item = {
|
|
82772
|
+
id: itemId,
|
|
82773
|
+
type: "function_call",
|
|
82774
|
+
status: "completed",
|
|
82775
|
+
call_id: callId,
|
|
82776
|
+
name: callValue.function.name,
|
|
82777
|
+
arguments: callValue.function.arguments
|
|
82778
|
+
};
|
|
82779
|
+
add("response.output_item.added", {
|
|
82780
|
+
type: "response.output_item.added",
|
|
82781
|
+
output_index: output.length,
|
|
82782
|
+
item: { ...item, status: "in_progress", arguments: "" }
|
|
82783
|
+
});
|
|
82784
|
+
add("response.function_call_arguments.delta", {
|
|
82785
|
+
type: "response.function_call_arguments.delta",
|
|
82786
|
+
item_id: itemId,
|
|
82787
|
+
output_index: output.length,
|
|
82788
|
+
delta: callValue.function.arguments
|
|
82789
|
+
});
|
|
82790
|
+
add("response.function_call_arguments.done", {
|
|
82791
|
+
type: "response.function_call_arguments.done",
|
|
82792
|
+
item_id: itemId,
|
|
82793
|
+
output_index: output.length,
|
|
82794
|
+
arguments: callValue.function.arguments
|
|
82795
|
+
});
|
|
82796
|
+
add("response.output_item.done", { type: "response.output_item.done", output_index: output.length, item });
|
|
82797
|
+
output.push(item);
|
|
82798
|
+
}
|
|
82799
|
+
}
|
|
82800
|
+
const incomplete = choice.finish_reason === "length";
|
|
82801
|
+
const final = {
|
|
82802
|
+
...base,
|
|
82803
|
+
status: incomplete ? "incomplete" : "completed",
|
|
82804
|
+
completed_at: Math.floor(Date.now() / 1e3),
|
|
82805
|
+
incomplete_details: incomplete ? { reason: "max_output_tokens" } : null,
|
|
82806
|
+
output,
|
|
82807
|
+
...usage ? { usage } : {}
|
|
82808
|
+
};
|
|
82809
|
+
add(incomplete ? "response.incomplete" : "response.completed", {
|
|
82810
|
+
type: incomplete ? "response.incomplete" : "response.completed",
|
|
82811
|
+
response: final
|
|
82812
|
+
});
|
|
82813
|
+
return events.map(({ event, data }) => `event: ${event}
|
|
82814
|
+
data: ${JSON.stringify(data)}
|
|
82815
|
+
|
|
82816
|
+
`).join("");
|
|
82817
|
+
}
|
|
82818
|
+
|
|
82819
|
+
// dist/sidecar.js
|
|
82148
82820
|
import { PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER as PAYMENT_RESPONSE_HEADER2 } from "@zk-credits/x402-zk-prepaid";
|
|
82149
82821
|
var MAX_REQUEST_BYTES = 2e6;
|
|
82150
82822
|
var PAYMENT_HEADERS = [PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER2, "cache-control"];
|
|
@@ -82181,12 +82853,12 @@ async function readJsonBody(req) {
|
|
|
82181
82853
|
throw new Error("OpenAI request body must be valid JSON");
|
|
82182
82854
|
}
|
|
82183
82855
|
}
|
|
82184
|
-
function
|
|
82856
|
+
function isRecord4(value) {
|
|
82185
82857
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
82186
82858
|
}
|
|
82187
82859
|
var STREAM_KEYS = ["stream", "stream_options", "streamOptions", "stream-options"];
|
|
82188
82860
|
function completionRejection(body) {
|
|
82189
|
-
if (!
|
|
82861
|
+
if (!isRecord4(body))
|
|
82190
82862
|
return "invalid_request_body";
|
|
82191
82863
|
if (STREAM_KEYS.some((key) => Object.prototype.hasOwnProperty.call(body, key)))
|
|
82192
82864
|
return "streaming_not_supported";
|
|
@@ -82220,6 +82892,31 @@ async function relayGatewayResponse(res, upstream) {
|
|
|
82220
82892
|
reader.releaseLock();
|
|
82221
82893
|
}
|
|
82222
82894
|
}
|
|
82895
|
+
async function relayResponsesGatewayResponse(res, upstream, responseModel) {
|
|
82896
|
+
if (upstream.status < 200 || upstream.status >= 300) {
|
|
82897
|
+
await relayGatewayResponse(res, upstream);
|
|
82898
|
+
return;
|
|
82899
|
+
}
|
|
82900
|
+
const upstreamText = await upstream.text();
|
|
82901
|
+
let completion;
|
|
82902
|
+
try {
|
|
82903
|
+
completion = JSON.parse(upstreamText);
|
|
82904
|
+
} catch {
|
|
82905
|
+
throw new Error("Gateway returned an invalid chat completion");
|
|
82906
|
+
}
|
|
82907
|
+
const eventStream = responsesEventStream(completion, responseModel);
|
|
82908
|
+
const headers = {
|
|
82909
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
82910
|
+
"Cache-Control": "no-cache"
|
|
82911
|
+
};
|
|
82912
|
+
for (const name of PAYMENT_HEADERS) {
|
|
82913
|
+
const value = upstream.headers.get(name);
|
|
82914
|
+
if (value)
|
|
82915
|
+
headers[name] = value;
|
|
82916
|
+
}
|
|
82917
|
+
res.writeHead(upstream.status, headers);
|
|
82918
|
+
res.end(eventStream);
|
|
82919
|
+
}
|
|
82223
82920
|
function createSidecarServer(options) {
|
|
82224
82921
|
const gatewayBaseUrl = options.gatewayBaseUrl.replace(/\/$/u, "");
|
|
82225
82922
|
let server = null;
|
|
@@ -82255,7 +82952,7 @@ function createSidecarServer(options) {
|
|
|
82255
82952
|
sendJson(res, 200, options.metrics());
|
|
82256
82953
|
return;
|
|
82257
82954
|
}
|
|
82258
|
-
if (req.method !== "POST" || pathname !== "/v1/chat/completions") {
|
|
82955
|
+
if (req.method !== "POST" || pathname !== "/v1/chat/completions" && pathname !== "/v1/responses") {
|
|
82259
82956
|
sendJson(res, 404, { error: "unsupported_openai_path" });
|
|
82260
82957
|
return;
|
|
82261
82958
|
}
|
|
@@ -82265,17 +82962,33 @@ function createSidecarServer(options) {
|
|
|
82265
82962
|
}
|
|
82266
82963
|
try {
|
|
82267
82964
|
const body = await readJsonBody(req);
|
|
82268
|
-
const
|
|
82269
|
-
|
|
82270
|
-
|
|
82271
|
-
|
|
82965
|
+
const isResponses = pathname === "/v1/responses";
|
|
82966
|
+
let outboundBody = body.raw;
|
|
82967
|
+
let responseModel = "";
|
|
82968
|
+
if (isResponses) {
|
|
82969
|
+
const translation = translateResponsesRequest(body.parsed);
|
|
82970
|
+
if (!translation.ok) {
|
|
82971
|
+
sendJson(res, 400, { error: translation.error });
|
|
82972
|
+
return;
|
|
82973
|
+
}
|
|
82974
|
+
outboundBody = JSON.stringify(translation.chatRequest);
|
|
82975
|
+
responseModel = translation.responseModel;
|
|
82976
|
+
} else {
|
|
82977
|
+
const rejection = completionRejection(body.parsed);
|
|
82978
|
+
if (rejection) {
|
|
82979
|
+
sendJson(res, 400, { error: rejection });
|
|
82980
|
+
return;
|
|
82981
|
+
}
|
|
82272
82982
|
}
|
|
82273
|
-
const upstream = await options.prepaidClient.fetch(`${gatewayBaseUrl}
|
|
82983
|
+
const upstream = await options.prepaidClient.fetch(`${gatewayBaseUrl}/v1/chat/completions`, {
|
|
82274
82984
|
method: "POST",
|
|
82275
82985
|
headers: { "Content-Type": "application/json" },
|
|
82276
|
-
body:
|
|
82986
|
+
body: outboundBody
|
|
82277
82987
|
});
|
|
82278
|
-
|
|
82988
|
+
if (isResponses)
|
|
82989
|
+
await relayResponsesGatewayResponse(res, upstream, responseModel);
|
|
82990
|
+
else
|
|
82991
|
+
await relayGatewayResponse(res, upstream);
|
|
82279
82992
|
} catch (error) {
|
|
82280
82993
|
if (!res.headersSent) {
|
|
82281
82994
|
sendJson(res, 502, {
|
|
@@ -82295,11 +83008,11 @@ function createSidecarServer(options) {
|
|
|
82295
83008
|
const request = handler(req, res).finally(() => inFlight.delete(request));
|
|
82296
83009
|
inFlight.add(request);
|
|
82297
83010
|
});
|
|
82298
|
-
await new Promise((
|
|
83011
|
+
await new Promise((resolve3, reject) => {
|
|
82299
83012
|
server.once("error", reject);
|
|
82300
83013
|
server.listen(port, "127.0.0.1", () => {
|
|
82301
83014
|
server.off("error", reject);
|
|
82302
|
-
|
|
83015
|
+
resolve3();
|
|
82303
83016
|
});
|
|
82304
83017
|
});
|
|
82305
83018
|
const address2 = server.address();
|
|
@@ -82310,21 +83023,171 @@ function createSidecarServer(options) {
|
|
|
82310
83023
|
return;
|
|
82311
83024
|
const activeServer = server;
|
|
82312
83025
|
server = null;
|
|
82313
|
-
await new Promise((
|
|
83026
|
+
await new Promise((resolve3, reject) => activeServer.close((error) => {
|
|
82314
83027
|
if (error)
|
|
82315
83028
|
reject(error);
|
|
82316
83029
|
else
|
|
82317
|
-
|
|
83030
|
+
resolve3();
|
|
82318
83031
|
}));
|
|
82319
83032
|
await Promise.all(inFlight);
|
|
82320
83033
|
}
|
|
82321
83034
|
};
|
|
82322
83035
|
}
|
|
82323
83036
|
|
|
83037
|
+
// dist/base-registered-trial.js
|
|
83038
|
+
import { x402Client } from "@x402/core/client";
|
|
83039
|
+
import { BASE_SEPOLIA_NETWORK, decodeHeader as decodeHeader2, encodeHeader, lifecycleFailure, lifecycleStage, PAYMENT_REQUIRED_HEADER as PAYMENT_REQUIRED_HEADER2, PAYMENT_RESPONSE_HEADER as PAYMENT_RESPONSE_HEADER3, PAYMENT_SIGNATURE_HEADER as PAYMENT_SIGNATURE_HEADER2, registerZkPrepaidClient, ZK_PREPAID_SCHEME } from "@zk-credits/x402-zk-prepaid";
|
|
83040
|
+
function observe(options, event) {
|
|
83041
|
+
try {
|
|
83042
|
+
options.lifecycle?.(event);
|
|
83043
|
+
} catch {
|
|
83044
|
+
}
|
|
83045
|
+
}
|
|
83046
|
+
function withFailure(options, result, startingCommittedSlots, failurePhase, failure) {
|
|
83047
|
+
result.failurePhase = failurePhase;
|
|
83048
|
+
if (failure)
|
|
83049
|
+
observe(options, lifecycleFailure(failure));
|
|
83050
|
+
result.committedSlotDelta = (options.slotLedger?.snapshot().committed ?? startingCommittedSlots) - startingCommittedSlots;
|
|
83051
|
+
return result;
|
|
83052
|
+
}
|
|
83053
|
+
function requestHeaders(headers) {
|
|
83054
|
+
return new Headers(headers);
|
|
83055
|
+
}
|
|
83056
|
+
async function runBaseRegisteredTrialExchange(options) {
|
|
83057
|
+
const ledger = options.slotLedger;
|
|
83058
|
+
if (!ledger)
|
|
83059
|
+
throw new Error("A durable slot ledger is required for the Base pilot");
|
|
83060
|
+
const startingCommittedSlots = ledger.snapshot().committed;
|
|
83061
|
+
const result = {
|
|
83062
|
+
challengeStatus: null,
|
|
83063
|
+
challengeReceived: false,
|
|
83064
|
+
proofPrepared: false,
|
|
83065
|
+
paymentSignatureSent: false,
|
|
83066
|
+
paymentStatus: null,
|
|
83067
|
+
paymentResponseConfirmed: false,
|
|
83068
|
+
responseStatus: null,
|
|
83069
|
+
responseSucceeded: false,
|
|
83070
|
+
committedSlotDelta: 0
|
|
83071
|
+
};
|
|
83072
|
+
let target;
|
|
83073
|
+
try {
|
|
83074
|
+
target = new URL(options.url);
|
|
83075
|
+
} catch {
|
|
83076
|
+
return withFailure(options, result, startingCommittedSlots, "challenge_request_mismatch");
|
|
83077
|
+
}
|
|
83078
|
+
if (target.protocol !== "https:" || target.username !== "" || target.password !== "" || target.search !== "" || target.hash !== "" || target.pathname !== "/v1/chat/completions") {
|
|
83079
|
+
return withFailure(options, result, startingCommittedSlots, "challenge_request_mismatch");
|
|
83080
|
+
}
|
|
83081
|
+
const fetcher = options.fetch ?? fetch;
|
|
83082
|
+
const requestInit = {
|
|
83083
|
+
method: "POST",
|
|
83084
|
+
body: options.body,
|
|
83085
|
+
headers: requestHeaders(options.headers),
|
|
83086
|
+
redirect: "error"
|
|
83087
|
+
};
|
|
83088
|
+
let challengeResponse;
|
|
83089
|
+
try {
|
|
83090
|
+
challengeResponse = await fetcher(target, requestInit);
|
|
83091
|
+
} catch {
|
|
83092
|
+
return withFailure(options, result, startingCommittedSlots, "challenge_transport", "transport_failed");
|
|
83093
|
+
}
|
|
83094
|
+
result.challengeStatus = challengeResponse.status;
|
|
83095
|
+
if (challengeResponse.status !== 402) {
|
|
83096
|
+
return withFailure(options, result, startingCommittedSlots, "challenge_status", "payment_rejected");
|
|
83097
|
+
}
|
|
83098
|
+
const encodedRequired = challengeResponse.headers.get(PAYMENT_REQUIRED_HEADER2);
|
|
83099
|
+
if (!encodedRequired) {
|
|
83100
|
+
return withFailure(options, result, startingCommittedSlots, "challenge_header", "challenge_unsupported");
|
|
83101
|
+
}
|
|
83102
|
+
let required;
|
|
83103
|
+
try {
|
|
83104
|
+
required = decodeHeader2(encodedRequired);
|
|
83105
|
+
} catch {
|
|
83106
|
+
return withFailure(options, result, startingCommittedSlots, "challenge_invalid", "challenge_unreadable");
|
|
83107
|
+
}
|
|
83108
|
+
if (required.x402Version !== 2 || !Array.isArray(required.accepts) || !required.accepts.some((accepted) => accepted.scheme === ZK_PREPAID_SCHEME && accepted.network === BASE_SEPOLIA_NETWORK)) {
|
|
83109
|
+
return withFailure(options, result, startingCommittedSlots, "challenge_unsupported", "challenge_unsupported");
|
|
83110
|
+
}
|
|
83111
|
+
const challengeUrl = required.resource?.url;
|
|
83112
|
+
if (challengeUrl && challengeUrl !== target.toString()) {
|
|
83113
|
+
return withFailure(options, result, startingCommittedSlots, "challenge_request_mismatch", "challenge_unsupported");
|
|
83114
|
+
}
|
|
83115
|
+
result.challengeReceived = true;
|
|
83116
|
+
observe(options, lifecycleStage("challenge_received"));
|
|
83117
|
+
const createPayment = createBasePaymentFactory(options);
|
|
83118
|
+
const directAdapter = registerZkPrepaidClient(new x402Client((_version, accepts) => {
|
|
83119
|
+
const selected = accepts.find((accepted) => accepted.scheme === ZK_PREPAID_SCHEME && accepted.network === BASE_SEPOLIA_NETWORK);
|
|
83120
|
+
if (!selected)
|
|
83121
|
+
throw new Error("zk_prepaid_challenge_missing");
|
|
83122
|
+
return selected;
|
|
83123
|
+
}).setSpendControls(false), async ({ requirements }) => {
|
|
83124
|
+
const prepared = await createPayment({
|
|
83125
|
+
url: target.toString(),
|
|
83126
|
+
method: "POST",
|
|
83127
|
+
body: options.body,
|
|
83128
|
+
requirements
|
|
83129
|
+
});
|
|
83130
|
+
return prepared.payment;
|
|
83131
|
+
});
|
|
83132
|
+
let payment;
|
|
83133
|
+
try {
|
|
83134
|
+
payment = await directAdapter.createPaymentPayload(required);
|
|
83135
|
+
result.proofPrepared = true;
|
|
83136
|
+
observe(options, lifecycleStage("payment_prepared"));
|
|
83137
|
+
} catch {
|
|
83138
|
+
return withFailure(options, result, startingCommittedSlots, "proof_generation", "payment_preparation_failed");
|
|
83139
|
+
}
|
|
83140
|
+
const headers = requestHeaders(options.headers);
|
|
83141
|
+
headers.set(PAYMENT_SIGNATURE_HEADER2, encodeHeader(payment));
|
|
83142
|
+
result.paymentSignatureSent = true;
|
|
83143
|
+
let paidResponse;
|
|
83144
|
+
try {
|
|
83145
|
+
paidResponse = await fetcher(target, { ...requestInit, headers });
|
|
83146
|
+
} catch {
|
|
83147
|
+
return withFailure(options, result, startingCommittedSlots, "payment_transport", "transport_failed");
|
|
83148
|
+
}
|
|
83149
|
+
result.paymentStatus = paidResponse.status;
|
|
83150
|
+
result.responseStatus = paidResponse.status;
|
|
83151
|
+
if (paidResponse.status === 402) {
|
|
83152
|
+
return withFailure(options, result, startingCommittedSlots, "payment_rejected", "payment_rejected");
|
|
83153
|
+
}
|
|
83154
|
+
const encodedPaymentResponse = paidResponse.headers.get(PAYMENT_RESPONSE_HEADER3);
|
|
83155
|
+
if (!encodedPaymentResponse) {
|
|
83156
|
+
return withFailure(options, result, startingCommittedSlots, "payment_response_missing", "settlement_failed");
|
|
83157
|
+
}
|
|
83158
|
+
try {
|
|
83159
|
+
const settlement = decodeHeader2(encodedPaymentResponse);
|
|
83160
|
+
if (settlement.success !== true || settlement.network !== BASE_SEPOLIA_NETWORK || settlement.transaction !== "") {
|
|
83161
|
+
return withFailure(options, result, startingCommittedSlots, "payment_response_invalid", "settlement_failed");
|
|
83162
|
+
}
|
|
83163
|
+
} catch {
|
|
83164
|
+
return withFailure(options, result, startingCommittedSlots, "payment_response_invalid", "settlement_failed");
|
|
83165
|
+
}
|
|
83166
|
+
result.paymentResponseConfirmed = true;
|
|
83167
|
+
observe(options, lifecycleStage("settlement_confirmed"));
|
|
83168
|
+
if (!paidResponse.ok) {
|
|
83169
|
+
return withFailure(options, result, startingCommittedSlots, "response_not_ok", "payment_rejected");
|
|
83170
|
+
}
|
|
83171
|
+
result.responseSucceeded = true;
|
|
83172
|
+
observe(options, lifecycleStage("exchange_succeeded"));
|
|
83173
|
+
result.committedSlotDelta = ledger.snapshot().committed - startingCommittedSlots;
|
|
83174
|
+
return result;
|
|
83175
|
+
}
|
|
83176
|
+
|
|
82324
83177
|
// dist/cli.js
|
|
83178
|
+
import { BASE_SEPOLIA_NETWORK as BASE_SEPOLIA_NETWORK2 } from "@zk-credits/x402-zk-prepaid";
|
|
83179
|
+
var DEFAULT_GATEWAY_URL = "https://zk-credits-gateway.onrender.com";
|
|
82325
83180
|
var DEFAULT_PORT = 3210;
|
|
82326
83181
|
function stateDirectory() {
|
|
82327
|
-
return process.env.ZK_CREDITS_HOME ||
|
|
83182
|
+
return process.env.ZK_CREDITS_HOME || join6(homedir(), ".zk-credits");
|
|
83183
|
+
}
|
|
83184
|
+
function setupConfigPath(directory = stateDirectory()) {
|
|
83185
|
+
return join6(directory, "config.json");
|
|
83186
|
+
}
|
|
83187
|
+
async function applySavedSetupConfig(environment, directory = stateDirectory()) {
|
|
83188
|
+
const config = await readSetupConfig(setupConfigPath(directory));
|
|
83189
|
+
if (config)
|
|
83190
|
+
applySetupConfig(environment, config);
|
|
82328
83191
|
}
|
|
82329
83192
|
function loopbackBaseUrl() {
|
|
82330
83193
|
const port = Number(process.env.ZK_CREDITS_SIDECAR_PORT || DEFAULT_PORT);
|
|
@@ -82343,6 +83206,55 @@ function readPort(args) {
|
|
|
82343
83206
|
}
|
|
82344
83207
|
return parsed;
|
|
82345
83208
|
}
|
|
83209
|
+
async function chooseSetupCandidate(kind, candidates) {
|
|
83210
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
83211
|
+
const variable = kind === "proving bundle" ? "ZK_CREDITS_ARTIFACT_DIR" : "ZK_CREDITS_WITNESS_PATH";
|
|
83212
|
+
throw new Error("Found more than one valid local " + kind + ". Rerun in an interactive terminal or set " + variable + " explicitly.");
|
|
83213
|
+
}
|
|
83214
|
+
const input = createInterface({ input: process.stdin, output: process.stdout });
|
|
83215
|
+
try {
|
|
83216
|
+
console.log("Found multiple valid " + kind + "s:");
|
|
83217
|
+
candidates.forEach((candidate, index2) => console.log(" " + (index2 + 1) + ") " + candidate));
|
|
83218
|
+
const answer = await input.question("Select a number: ");
|
|
83219
|
+
const index = Number(answer);
|
|
83220
|
+
if (!Number.isInteger(index) || index < 1 || index > candidates.length) {
|
|
83221
|
+
throw new Error("Choose one of the listed local candidates");
|
|
83222
|
+
}
|
|
83223
|
+
return candidates[index - 1];
|
|
83224
|
+
} finally {
|
|
83225
|
+
input.close();
|
|
83226
|
+
}
|
|
83227
|
+
}
|
|
83228
|
+
async function witnessProviderForSource(source, cachePath) {
|
|
83229
|
+
if (source.kind === "file") {
|
|
83230
|
+
let value;
|
|
83231
|
+
try {
|
|
83232
|
+
value = JSON.parse(await readFile6(source.path, "utf8"));
|
|
83233
|
+
} catch {
|
|
83234
|
+
throw new Error("The Base witness file could not be read as JSON");
|
|
83235
|
+
}
|
|
83236
|
+
return createFileWitnessProvider(value);
|
|
83237
|
+
}
|
|
83238
|
+
return createBaseEventWitnessProvider({
|
|
83239
|
+
rpcUrl: source.rpcUrl,
|
|
83240
|
+
contractAddress: source.contractAddress,
|
|
83241
|
+
deploymentBlock: source.deploymentBlock === void 0 ? void 0 : BigInt(source.deploymentBlock),
|
|
83242
|
+
confirmations: source.confirmations === void 0 ? void 0 : BigInt(source.confirmations),
|
|
83243
|
+
cachePath
|
|
83244
|
+
});
|
|
83245
|
+
}
|
|
83246
|
+
async function readCredentialPasswordFromStdin() {
|
|
83247
|
+
const chunks = [];
|
|
83248
|
+
let byteLength = 0;
|
|
83249
|
+
for await (const chunk of process.stdin) {
|
|
83250
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
83251
|
+
byteLength += bytes.length;
|
|
83252
|
+
if (byteLength > 4096)
|
|
83253
|
+
throw new Error("Credential password input is too long");
|
|
83254
|
+
chunks.push(bytes);
|
|
83255
|
+
}
|
|
83256
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
83257
|
+
}
|
|
82346
83258
|
async function readHiddenValue(prompt) {
|
|
82347
83259
|
if (!process.stdin.isTTY || !process.stdin.setRawMode) {
|
|
82348
83260
|
throw new Error("credential backup requires an interactive terminal");
|
|
@@ -82350,16 +83262,17 @@ async function readHiddenValue(prompt) {
|
|
|
82350
83262
|
process.stdout.write(prompt);
|
|
82351
83263
|
process.stdin.setRawMode(true);
|
|
82352
83264
|
process.stdin.resume();
|
|
82353
|
-
return new Promise((
|
|
83265
|
+
return new Promise((resolve3, reject) => {
|
|
82354
83266
|
let value = "";
|
|
82355
83267
|
const done = (error) => {
|
|
82356
83268
|
process.stdin.off("data", onData);
|
|
82357
83269
|
process.stdin.setRawMode(false);
|
|
83270
|
+
process.stdin.pause();
|
|
82358
83271
|
process.stdout.write("\n");
|
|
82359
83272
|
if (error)
|
|
82360
83273
|
reject(error);
|
|
82361
83274
|
else
|
|
82362
|
-
|
|
83275
|
+
resolve3(value.trim());
|
|
82363
83276
|
};
|
|
82364
83277
|
const onData = (chunk) => {
|
|
82365
83278
|
for (const byte of chunk) {
|
|
@@ -82382,7 +83295,7 @@ async function readHiddenValue(prompt) {
|
|
|
82382
83295
|
});
|
|
82383
83296
|
}
|
|
82384
83297
|
async function readEncryptedCredential(path, password) {
|
|
82385
|
-
const parsed = JSON.parse(await
|
|
83298
|
+
const parsed = JSON.parse(await readFile6(path, "utf8"));
|
|
82386
83299
|
if (parsed.format !== "zk-credits-credential" || parsed.version !== 1 && parsed.version !== 2) {
|
|
82387
83300
|
throw new Error("Credential file is not a supported zk-credits export");
|
|
82388
83301
|
}
|
|
@@ -82395,50 +83308,304 @@ function printHelp() {
|
|
|
82395
83308
|
zk-credits codex [codex arguments...]
|
|
82396
83309
|
zk-credits status
|
|
82397
83310
|
zk-credits serve [--port <port>]
|
|
83311
|
+
zk-credits trial-registered-adapter
|
|
82398
83312
|
eval "$(zk-credits env)"
|
|
82399
83313
|
|
|
82400
83314
|
"zk-credits cline" and the Codex companion configure and launch coding agents
|
|
82401
|
-
against the x402 zk-prepaid loopback sidecar. The
|
|
82402
|
-
POST /v1/chat/completions
|
|
82403
|
-
|
|
82404
|
-
|
|
82405
|
-
|
|
83315
|
+
against the x402 zk-prepaid loopback sidecar. The gateway spend path is
|
|
83316
|
+
non-streaming POST /v1/chat/completions; Codex Responses requests pass through
|
|
83317
|
+
the sidecar's bounded local compatibility bridge.
|
|
83318
|
+
"zk-credits trial-registered-adapter" runs one confirmed, billable internal
|
|
83319
|
+
trial request through the directly registered official x402 client adapter.
|
|
83320
|
+
Set ZK_CREDITS_CREDENTIAL_PATH before setup. The wizard searches Downloads and
|
|
83321
|
+
~/.zk-credits for the pinned bundle and local Base witness, validates both,
|
|
83322
|
+
then saves their paths locally. Alternatively, set ZK_CREDITS_ARTIFACT_DIR and
|
|
83323
|
+
ZK_CREDITS_WITNESS_PATH explicitly. Setup prompts for the credential password
|
|
83324
|
+
without echo; the encrypted export is decrypted only in local memory.`);
|
|
82406
83325
|
}
|
|
82407
|
-
async function
|
|
82408
|
-
const port = readPort(args);
|
|
82409
|
-
const statePaths = sidecarStatePaths(stateDirectory());
|
|
82410
|
-
const localToken = createLoopbackToken();
|
|
83326
|
+
async function loadBaseClientRuntime(passwordInput) {
|
|
82411
83327
|
const credentialPath = process.env.ZK_CREDITS_CREDENTIAL_PATH;
|
|
82412
83328
|
if (!credentialPath)
|
|
82413
83329
|
throw new Error("Set ZK_CREDITS_CREDENTIAL_PATH to the encrypted browser export");
|
|
82414
|
-
const password =
|
|
83330
|
+
const password = passwordInput ?? await readHiddenValue("Credential backup password: ");
|
|
82415
83331
|
const credential = await readEncryptedCredential(credentialPath, password);
|
|
82416
83332
|
const witnessPath = process.env.ZK_CREDITS_WITNESS_PATH;
|
|
82417
83333
|
const artifactDirectory = process.env.ZK_CREDITS_ARTIFACT_DIR;
|
|
82418
83334
|
if (!artifactDirectory) {
|
|
82419
83335
|
throw new Error("Set ZK_CREDITS_ARTIFACT_DIR to the directory holding the installed pinned proving bundle");
|
|
82420
83336
|
}
|
|
82421
|
-
const
|
|
83337
|
+
const witnessProvider = witnessPath ? createFileWitnessProvider(JSON.parse(await readFile6(witnessPath, "utf8"))) : process.env.BASE_RPC_URL && process.env.BASE_PRIVATE_CREDIT_BOND_ADDRESS ? createBaseEventWitnessProvider({
|
|
82422
83338
|
rpcUrl: process.env.BASE_RPC_URL,
|
|
82423
83339
|
contractAddress: process.env.BASE_PRIVATE_CREDIT_BOND_ADDRESS,
|
|
82424
83340
|
deploymentBlock: process.env.BASE_DEPLOYMENT_BLOCK && /^\d+$/u.test(process.env.BASE_DEPLOYMENT_BLOCK) ? BigInt(process.env.BASE_DEPLOYMENT_BLOCK) : void 0,
|
|
82425
83341
|
confirmations: process.env.BASE_CONFIRMATIONS && /^\d+$/u.test(process.env.BASE_CONFIRMATIONS) ? BigInt(process.env.BASE_CONFIRMATIONS) : void 0,
|
|
82426
|
-
cachePath:
|
|
83342
|
+
cachePath: join6(stateDirectory(), "base-event-sync.json")
|
|
82427
83343
|
}) : (() => {
|
|
82428
83344
|
throw new Error("Set ZK_CREDITS_WITNESS_PATH or configure BASE_RPC_URL and BASE_PRIVATE_CREDIT_BOND_ADDRESS");
|
|
82429
83345
|
})();
|
|
82430
83346
|
const proofMetrics = createBaseProofMetrics();
|
|
82431
83347
|
const exchangeMetrics = createZkPrepaidLifecycleMetrics();
|
|
82432
|
-
const slotLedger = await BaseSlotLedger.open({ path:
|
|
83348
|
+
const slotLedger = await BaseSlotLedger.open({ path: join6(stateDirectory(), "base-slots.json") });
|
|
82433
83349
|
const prove = await createPinnedBaseProofGenerator({ artifactDirectory, metrics: proofMetrics });
|
|
83350
|
+
validateBaseCreditWitness(await witnessProvider.witnessForCredential(credential));
|
|
83351
|
+
return { credential, witnessProvider, slotLedger, proofMetrics, exchangeMetrics, prove };
|
|
83352
|
+
}
|
|
83353
|
+
var GATEWAY_COUNTER_NAMES = [
|
|
83354
|
+
"challenge_issued",
|
|
83355
|
+
"proof_valid",
|
|
83356
|
+
"proof_invalid",
|
|
83357
|
+
"reservation_new",
|
|
83358
|
+
"reservation_existing",
|
|
83359
|
+
"claim_committed",
|
|
83360
|
+
"claim_cancelled",
|
|
83361
|
+
"claim_replayed",
|
|
83362
|
+
"claim_conflict",
|
|
83363
|
+
"dispatch_ok",
|
|
83364
|
+
"dispatch_error",
|
|
83365
|
+
"dispatch_timeout",
|
|
83366
|
+
"cap_exhausted_utc_day",
|
|
83367
|
+
"cap_exhausted_rolling_30d",
|
|
83368
|
+
"paused_rejected",
|
|
83369
|
+
"request_rejected"
|
|
83370
|
+
];
|
|
83371
|
+
var GATEWAY_CLAIM_COUNT_NAMES = ["reserved", "ready", "committed", "cancelled"];
|
|
83372
|
+
var GATEWAY_READINESS_CHECK_NAMES = /* @__PURE__ */ new Set(["launchControl", "database", "baseRoot", "baseRpc", "verifierAssets", "provider"]);
|
|
83373
|
+
function isRecord5(value) {
|
|
83374
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
83375
|
+
}
|
|
83376
|
+
function safeCount(value) {
|
|
83377
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
83378
|
+
}
|
|
83379
|
+
function gatewayOrigin() {
|
|
83380
|
+
const origin = new URL(process.env.ZK_CREDITS_GATEWAY_URL || DEFAULT_GATEWAY_URL);
|
|
83381
|
+
if (origin.protocol !== "https:" || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== "/") {
|
|
83382
|
+
throw new Error("The internal trial requires a plain HTTPS gateway origin");
|
|
83383
|
+
}
|
|
83384
|
+
return origin;
|
|
83385
|
+
}
|
|
83386
|
+
async function readGatewayJson(url, headers) {
|
|
83387
|
+
try {
|
|
83388
|
+
const response = await fetch(url, { headers, signal: AbortSignal.timeout(1e4) });
|
|
83389
|
+
let body;
|
|
83390
|
+
try {
|
|
83391
|
+
body = await response.json();
|
|
83392
|
+
} catch {
|
|
83393
|
+
body = void 0;
|
|
83394
|
+
}
|
|
83395
|
+
return { status: response.status, body };
|
|
83396
|
+
} catch {
|
|
83397
|
+
return { status: null };
|
|
83398
|
+
}
|
|
83399
|
+
}
|
|
83400
|
+
async function gatewayReadiness(origin) {
|
|
83401
|
+
const response = await readGatewayJson(new URL("/ready", origin), { accept: "application/json" });
|
|
83402
|
+
const report = isRecord5(response.body) ? response.body : void 0;
|
|
83403
|
+
const checks = Array.isArray(report?.checks) ? report.checks : [];
|
|
83404
|
+
const failedChecks = checks.flatMap((check) => isRecord5(check) && check.ok === true ? [] : [isRecord5(check) && typeof check.name === "string" && GATEWAY_READINESS_CHECK_NAMES.has(check.name) ? check.name : "unknown"]);
|
|
83405
|
+
const hasLaunchCheck = checks.some((check) => isRecord5(check) && check.name === "launchControl" && check.ok === true);
|
|
83406
|
+
return {
|
|
83407
|
+
status: response.status,
|
|
83408
|
+
passed: response.status === 200 && report?.ready === true && failedChecks.length === 0 && hasLaunchCheck,
|
|
83409
|
+
failedChecks
|
|
83410
|
+
};
|
|
83411
|
+
}
|
|
83412
|
+
async function gatewayTrialSnapshot(origin, token) {
|
|
83413
|
+
const response = await readGatewayJson(new URL("/v1/admin/status", origin), {
|
|
83414
|
+
accept: "application/json",
|
|
83415
|
+
authorization: `Bearer ${token}`
|
|
83416
|
+
});
|
|
83417
|
+
const body = isRecord5(response.body) ? response.body : void 0;
|
|
83418
|
+
const launch = isRecord5(body?.launchControl) ? body.launchControl : void 0;
|
|
83419
|
+
const base = isRecord5(body?.base) ? body.base : void 0;
|
|
83420
|
+
const spend = isRecord5(body?.spend) ? body.spend : void 0;
|
|
83421
|
+
const rawMetrics = isRecord5(body?.metrics) ? body.metrics : void 0;
|
|
83422
|
+
const rawClaims = isRecord5(body?.claims) ? body.claims : void 0;
|
|
83423
|
+
const metrics = {};
|
|
83424
|
+
const claims = {};
|
|
83425
|
+
let countersValid = Boolean(rawMetrics && rawClaims);
|
|
83426
|
+
for (const name of GATEWAY_COUNTER_NAMES) {
|
|
83427
|
+
const count = safeCount(rawMetrics?.[name]);
|
|
83428
|
+
if (count === void 0)
|
|
83429
|
+
countersValid = false;
|
|
83430
|
+
else
|
|
83431
|
+
metrics[name] = count;
|
|
83432
|
+
}
|
|
83433
|
+
for (const name of GATEWAY_CLAIM_COUNT_NAMES) {
|
|
83434
|
+
const count = safeCount(rawClaims?.[name]);
|
|
83435
|
+
if (count !== void 0)
|
|
83436
|
+
claims[name] = count;
|
|
83437
|
+
else
|
|
83438
|
+
countersValid = false;
|
|
83439
|
+
}
|
|
83440
|
+
const headroom = (value) => typeof value === "string" && /^\d+$/u.test(value) && BigInt(value) > 0n;
|
|
83441
|
+
const currentRoot = typeof base?.currentRoot === "string" && base.currentRoot.length > 0 ? base.currentRoot : void 0;
|
|
83442
|
+
const knownRoot = currentRoot !== void 0;
|
|
83443
|
+
const lag = typeof base?.lagBlocks === "string" && /^\d+$/u.test(base.lagBlocks) ? BigInt(base.lagBlocks) : void 0;
|
|
83444
|
+
const snapshot = countersValid && currentRoot ? { metrics, claims, currentRoot } : void 0;
|
|
83445
|
+
return {
|
|
83446
|
+
status: response.status,
|
|
83447
|
+
...snapshot ? { snapshot } : {},
|
|
83448
|
+
gatePassed: response.status === 200 && body?.network === BASE_SEPOLIA_NETWORK2 && launch?.state === "enabled" && knownRoot && safeCount(base?.knownRootCount) !== void 0 && (safeCount(base?.knownRootCount) ?? 0) > 0 && lag !== void 0 && lag <= 300n && headroom(spend?.dailyHeadroomMicroUsd) && headroom(spend?.rollingHeadroomMicroUsd) && countersValid
|
|
83449
|
+
};
|
|
83450
|
+
}
|
|
83451
|
+
async function confirmDirectTrial() {
|
|
83452
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
83453
|
+
throw new Error("the internal trial requires a local interactive terminal");
|
|
83454
|
+
const input = createInterface({ input: process.stdin, output: process.stdout });
|
|
83455
|
+
try {
|
|
83456
|
+
const answer = await input.question("Confirm local recovery completed, this slot ledger was not copied to another client, one credit remains, and you approve one billable internal exchange. Type RUN ONE INTERNAL EXCHANGE: ");
|
|
83457
|
+
return answer.trim() === "RUN ONE INTERNAL EXCHANGE";
|
|
83458
|
+
} finally {
|
|
83459
|
+
input.close();
|
|
83460
|
+
}
|
|
83461
|
+
}
|
|
83462
|
+
function gatewayCounterDelta(before, after) {
|
|
83463
|
+
return {
|
|
83464
|
+
metrics: Object.fromEntries(GATEWAY_COUNTER_NAMES.map((name) => [name, after.metrics[name] - before.metrics[name]])),
|
|
83465
|
+
claims: Object.fromEntries(GATEWAY_CLAIM_COUNT_NAMES.map((name) => [name, after.claims[name] - before.claims[name]]))
|
|
83466
|
+
};
|
|
83467
|
+
}
|
|
83468
|
+
async function trialRegisteredAdapter() {
|
|
83469
|
+
if (!await confirmDirectTrial()) {
|
|
83470
|
+
console.log(JSON.stringify({ path: "registered-adapter", status: "not_run" }));
|
|
83471
|
+
return;
|
|
83472
|
+
}
|
|
83473
|
+
try {
|
|
83474
|
+
const runtime = await loadBaseClientRuntime();
|
|
83475
|
+
if (runtime.credential.tierId !== 0 || runtime.credential.deploymentDomain !== "84532" || runtime.credential.expiry <= Math.floor(Date.now() / 1e3)) {
|
|
83476
|
+
console.log(JSON.stringify({ path: "registered-adapter", status: "stopped", failurePhase: "credential_gate" }));
|
|
83477
|
+
return;
|
|
83478
|
+
}
|
|
83479
|
+
const startingSlots = runtime.slotLedger.snapshot();
|
|
83480
|
+
if (startingSlots.committed >= startingSlots.capacity) {
|
|
83481
|
+
console.log(JSON.stringify({
|
|
83482
|
+
path: "registered-adapter",
|
|
83483
|
+
status: "stopped",
|
|
83484
|
+
failurePhase: "local_credit_gate",
|
|
83485
|
+
localCredits: { capacity: startingSlots.capacity, committed: startingSlots.committed, available: 0 }
|
|
83486
|
+
}));
|
|
83487
|
+
return;
|
|
83488
|
+
}
|
|
83489
|
+
const gateway = gatewayOrigin();
|
|
83490
|
+
const adminToken = process.env.BILLING_INTERNAL_TOKEN || await readHiddenValue("Gateway admin token: ");
|
|
83491
|
+
if (!adminToken.trim()) {
|
|
83492
|
+
console.log(JSON.stringify({ path: "registered-adapter", status: "stopped", failurePhase: "admin_auth" }));
|
|
83493
|
+
return;
|
|
83494
|
+
}
|
|
83495
|
+
const lifecycle = createNodeSidecarLifecycle({
|
|
83496
|
+
loopbackBaseUrl: loopbackBaseUrl(),
|
|
83497
|
+
stateDirectory: stateDirectory(),
|
|
83498
|
+
tokenPath: sidecarStatePaths(stateDirectory()).tokenPath,
|
|
83499
|
+
logPath: sidecarStatePaths(stateDirectory()).logPath,
|
|
83500
|
+
cliEntryPath: process.argv[1] ?? ""
|
|
83501
|
+
});
|
|
83502
|
+
const codexHome = resolveCodexHome(process.env, homedir());
|
|
83503
|
+
const [sidecarRunning, codexProfileInstalled] = await Promise.all([
|
|
83504
|
+
lifecycle.isHealthy(),
|
|
83505
|
+
isCodexProfileInstalled(codexHome)
|
|
83506
|
+
]);
|
|
83507
|
+
const launcherStatus = { codexProfileInstalled, sidecarRunning };
|
|
83508
|
+
if (sidecarRunning) {
|
|
83509
|
+
console.log(JSON.stringify({ path: "registered-adapter", status: "stopped", failurePhase: "sidecar_running", launcherStatus }));
|
|
83510
|
+
return;
|
|
83511
|
+
}
|
|
83512
|
+
const witness = await runtime.witnessProvider.witnessForCredential(runtime.credential);
|
|
83513
|
+
const readiness = await gatewayReadiness(gateway);
|
|
83514
|
+
if (!readiness.passed) {
|
|
83515
|
+
console.log(JSON.stringify({ path: "registered-adapter", status: "stopped", failurePhase: "readiness", launcherStatus, readiness }));
|
|
83516
|
+
return;
|
|
83517
|
+
}
|
|
83518
|
+
const adminBefore = await gatewayTrialSnapshot(gateway, adminToken);
|
|
83519
|
+
if (!adminBefore.gatePassed || !adminBefore.snapshot) {
|
|
83520
|
+
console.log(JSON.stringify({ path: "registered-adapter", status: "stopped", failurePhase: "admin_status", launcherStatus, readiness, adminStatus: adminBefore.status }));
|
|
83521
|
+
return;
|
|
83522
|
+
}
|
|
83523
|
+
if (witness.root !== adminBefore.snapshot.currentRoot) {
|
|
83524
|
+
console.log(JSON.stringify({ path: "registered-adapter", status: "stopped", failurePhase: "root_mismatch", launcherStatus, readiness, adminStatus: adminBefore.status }));
|
|
83525
|
+
return;
|
|
83526
|
+
}
|
|
83527
|
+
const baselineSlots = runtime.slotLedger.snapshot();
|
|
83528
|
+
const baselineProof = runtime.proofMetrics.snapshot();
|
|
83529
|
+
const baselineLifecycle = runtime.exchangeMetrics.snapshot();
|
|
83530
|
+
const requestUrl = new URL("/v1/chat/completions", gateway).toString();
|
|
83531
|
+
const requestBody = JSON.stringify({
|
|
83532
|
+
model: "deepseek/deepseek-v4-flash",
|
|
83533
|
+
messages: [{ role: "user", content: "Reply with exactly: internal trial complete." }],
|
|
83534
|
+
stream: false
|
|
83535
|
+
});
|
|
83536
|
+
const exchange = await runBaseRegisteredTrialExchange({
|
|
83537
|
+
url: requestUrl,
|
|
83538
|
+
body: requestBody,
|
|
83539
|
+
headers: { "content-type": "application/json" },
|
|
83540
|
+
credential: runtime.credential,
|
|
83541
|
+
witnessProvider: runtime.witnessProvider,
|
|
83542
|
+
prove: runtime.prove,
|
|
83543
|
+
slotLedger: runtime.slotLedger,
|
|
83544
|
+
lifecycle: runtime.exchangeMetrics.observe
|
|
83545
|
+
});
|
|
83546
|
+
const adminAfter = await gatewayTrialSnapshot(gateway, adminToken);
|
|
83547
|
+
const proofAfter = runtime.proofMetrics.snapshot();
|
|
83548
|
+
const lifecycleAfter = runtime.exchangeMetrics.snapshot();
|
|
83549
|
+
const slotAfter = runtime.slotLedger.snapshot();
|
|
83550
|
+
const localDeltas = {
|
|
83551
|
+
proofAttempts: proofAfter.attempts - baselineProof.attempts,
|
|
83552
|
+
proofSuccesses: proofAfter.successes - baselineProof.successes,
|
|
83553
|
+
proofFailures: proofAfter.failures - baselineProof.failures,
|
|
83554
|
+
challengesReceived: lifecycleAfter.challengesReceived - baselineLifecycle.challengesReceived,
|
|
83555
|
+
paymentsPrepared: lifecycleAfter.paymentsPrepared - baselineLifecycle.paymentsPrepared,
|
|
83556
|
+
settlementsConfirmed: lifecycleAfter.settlementsConfirmed - baselineLifecycle.settlementsConfirmed,
|
|
83557
|
+
exchangeSuccesses: lifecycleAfter.exchangeSuccesses - baselineLifecycle.exchangeSuccesses,
|
|
83558
|
+
exchangeFailures: lifecycleAfter.failures - baselineLifecycle.failures,
|
|
83559
|
+
committedSlots: slotAfter.committed - baselineSlots.committed
|
|
83560
|
+
};
|
|
83561
|
+
const counterDelta = adminAfter.snapshot ? gatewayCounterDelta(adminBefore.snapshot, adminAfter.snapshot) : void 0;
|
|
83562
|
+
const expectedGatewayCounters = ["challenge_issued", "proof_valid", "reservation_new", "claim_committed", "dispatch_ok"];
|
|
83563
|
+
const gatewayCountersMatch = Boolean(counterDelta) && expectedGatewayCounters.every((name) => counterDelta.metrics[name] === 1) && Object.entries(counterDelta?.metrics ?? {}).every(([name, value]) => expectedGatewayCounters.includes(name) || value === 0) && counterDelta?.claims.committed === 1 && Object.entries(counterDelta?.claims ?? {}).every(([name, value]) => name === "committed" || value === 0);
|
|
83564
|
+
const failurePhase = exchange.failurePhase ?? (!exchange.responseSucceeded ? "response_not_ok" : void 0) ?? (adminAfter.status !== 200 || !adminAfter.snapshot ? "postflight_admin_status" : void 0) ?? (!gatewayCountersMatch ? "gateway_counter_delta" : void 0);
|
|
83565
|
+
console.log(JSON.stringify({
|
|
83566
|
+
path: "registered-adapter",
|
|
83567
|
+
readiness: { status: readiness.status, passed: readiness.passed, failedChecks: readiness.failedChecks },
|
|
83568
|
+
launcherStatus,
|
|
83569
|
+
adminStatus: { before: adminBefore.status, after: adminAfter.status },
|
|
83570
|
+
localCredits: {
|
|
83571
|
+
capacity: baselineSlots.capacity,
|
|
83572
|
+
committedBefore: baselineSlots.committed,
|
|
83573
|
+
committedAfter: slotAfter.committed,
|
|
83574
|
+
availableBefore: baselineSlots.capacity - baselineSlots.committed,
|
|
83575
|
+
availableAfter: slotAfter.capacity - slotAfter.committed
|
|
83576
|
+
},
|
|
83577
|
+
exchange: {
|
|
83578
|
+
challengeStatus: exchange.challengeStatus,
|
|
83579
|
+
challengeReceived: exchange.challengeReceived,
|
|
83580
|
+
proofPrepared: exchange.proofPrepared,
|
|
83581
|
+
paymentSignatureSent: exchange.paymentSignatureSent,
|
|
83582
|
+
paymentStatus: exchange.paymentStatus,
|
|
83583
|
+
paymentResponseConfirmed: exchange.paymentResponseConfirmed,
|
|
83584
|
+
responseStatus: exchange.responseStatus,
|
|
83585
|
+
responseSucceeded: exchange.responseSucceeded,
|
|
83586
|
+
committedSlotDelta: exchange.committedSlotDelta
|
|
83587
|
+
},
|
|
83588
|
+
localCounterDelta: localDeltas,
|
|
83589
|
+
gatewayCounterDelta: counterDelta ?? null,
|
|
83590
|
+
failurePhase
|
|
83591
|
+
}));
|
|
83592
|
+
} catch {
|
|
83593
|
+
console.log(JSON.stringify({ path: "registered-adapter", status: "stopped", failurePhase: "local_setup" }));
|
|
83594
|
+
}
|
|
83595
|
+
}
|
|
83596
|
+
async function serve(args, passwordInput) {
|
|
83597
|
+
const port = readPort(args);
|
|
83598
|
+
const statePaths = sidecarStatePaths(stateDirectory());
|
|
83599
|
+
const localToken = createLoopbackToken();
|
|
83600
|
+
const { credential, witnessProvider, proofMetrics, exchangeMetrics, slotLedger, prove } = await loadBaseClientRuntime(passwordInput);
|
|
82434
83601
|
const prepaid = createBasePrepaidClient({
|
|
82435
83602
|
credential,
|
|
82436
|
-
witnessProvider
|
|
83603
|
+
witnessProvider,
|
|
82437
83604
|
prove,
|
|
82438
83605
|
slotLedger,
|
|
82439
83606
|
lifecycle: exchangeMetrics.observe
|
|
82440
83607
|
});
|
|
82441
|
-
const gatewayBaseUrl = process.env.ZK_CREDITS_GATEWAY_URL ||
|
|
83608
|
+
const gatewayBaseUrl = process.env.ZK_CREDITS_GATEWAY_URL || DEFAULT_GATEWAY_URL;
|
|
82442
83609
|
const sidecar = createSidecarServer({
|
|
82443
83610
|
localToken,
|
|
82444
83611
|
gatewayBaseUrl,
|
|
@@ -82474,22 +83641,39 @@ async function main() {
|
|
|
82474
83641
|
printHelp();
|
|
82475
83642
|
return;
|
|
82476
83643
|
}
|
|
83644
|
+
const sidecarHome = stateDirectory();
|
|
83645
|
+
if (args[0] !== "setup" && args[0] !== "status" && args[0] !== "env") {
|
|
83646
|
+
await applySavedSetupConfig(process.env, sidecarHome);
|
|
83647
|
+
}
|
|
82477
83648
|
if (args[0] === "serve") {
|
|
82478
|
-
|
|
83649
|
+
const passwordFromStdin = args.includes("--credential-password-stdin") ? await readCredentialPasswordFromStdin() : void 0;
|
|
83650
|
+
await serve(args.slice(1).filter((argument) => argument !== "--credential-password-stdin"), passwordFromStdin);
|
|
83651
|
+
return;
|
|
83652
|
+
}
|
|
83653
|
+
if (args[0] === "trial-registered-adapter") {
|
|
83654
|
+
await trialRegisteredAdapter();
|
|
82479
83655
|
return;
|
|
82480
83656
|
}
|
|
82481
|
-
const sidecarHome = stateDirectory();
|
|
82482
83657
|
const statePaths = sidecarStatePaths(sidecarHome);
|
|
82483
83658
|
const codexHome = resolveCodexHome(process.env, homedir());
|
|
82484
83659
|
const cliEntryPath = process.argv[1];
|
|
82485
83660
|
if (!cliEntryPath)
|
|
82486
83661
|
throw new Error("Unable to resolve the zk-credits executable path");
|
|
83662
|
+
let setupCredentialPassword;
|
|
82487
83663
|
const lifecycle = createNodeSidecarLifecycle({
|
|
82488
83664
|
loopbackBaseUrl: loopbackBaseUrl(),
|
|
82489
83665
|
stateDirectory: sidecarHome,
|
|
82490
83666
|
tokenPath: statePaths.tokenPath,
|
|
82491
83667
|
logPath: statePaths.logPath,
|
|
82492
|
-
cliEntryPath
|
|
83668
|
+
cliEntryPath,
|
|
83669
|
+
readCredentialPassword: async () => {
|
|
83670
|
+
if (setupCredentialPassword !== void 0) {
|
|
83671
|
+
const password = setupCredentialPassword;
|
|
83672
|
+
setupCredentialPassword = void 0;
|
|
83673
|
+
return password;
|
|
83674
|
+
}
|
|
83675
|
+
return readHiddenValue("Credential backup password: ");
|
|
83676
|
+
}
|
|
82493
83677
|
});
|
|
82494
83678
|
const exitCode = await runCliCommand(args, {
|
|
82495
83679
|
loopbackBaseUrl: loopbackBaseUrl(),
|
|
@@ -82500,12 +83684,48 @@ async function main() {
|
|
|
82500
83684
|
if (!path)
|
|
82501
83685
|
return false;
|
|
82502
83686
|
try {
|
|
82503
|
-
await
|
|
83687
|
+
await readFile6(path);
|
|
82504
83688
|
return true;
|
|
82505
83689
|
} catch {
|
|
82506
83690
|
return false;
|
|
82507
83691
|
}
|
|
82508
83692
|
},
|
|
83693
|
+
validateSetupPrerequisites: async () => {
|
|
83694
|
+
const credentialPath = process.env.ZK_CREDITS_CREDENTIAL_PATH;
|
|
83695
|
+
if (!credentialPath?.trim())
|
|
83696
|
+
throw new Error("Set ZK_CREDITS_CREDENTIAL_PATH to the encrypted browser export");
|
|
83697
|
+
const password = await readHiddenValue("Credential backup password: ");
|
|
83698
|
+
const credential = await readEncryptedCredential(credentialPath, password);
|
|
83699
|
+
const manifest = await loadCircuitManifest();
|
|
83700
|
+
const config = await resolveSetupInputs({
|
|
83701
|
+
environment: process.env,
|
|
83702
|
+
homeDirectory: homedir(),
|
|
83703
|
+
stateDirectory: sidecarHome,
|
|
83704
|
+
configPath: setupConfigPath(sidecarHome),
|
|
83705
|
+
manifest,
|
|
83706
|
+
validateWitness: async (source) => {
|
|
83707
|
+
const provider = await witnessProviderForSource(source, join6(stateDirectory(), "base-event-sync.json"));
|
|
83708
|
+
validateBaseCreditWitness(await provider.witnessForCredential(credential));
|
|
83709
|
+
},
|
|
83710
|
+
chooseCandidate: chooseSetupCandidate
|
|
83711
|
+
});
|
|
83712
|
+
const artifactDirectory = config.artifactDirectory;
|
|
83713
|
+
try {
|
|
83714
|
+
await createPinnedBaseProofGenerator({
|
|
83715
|
+
artifactDirectory,
|
|
83716
|
+
metrics: createBaseProofMetrics()
|
|
83717
|
+
});
|
|
83718
|
+
} catch (error) {
|
|
83719
|
+
if (error instanceof Error)
|
|
83720
|
+
throw new Error(`Pinned proving bundle check failed: ${error.message}`);
|
|
83721
|
+
throw new Error("Pinned proving bundle check failed. Reinstall the bundle from your pilot invite.");
|
|
83722
|
+
}
|
|
83723
|
+
await writeSetupConfig(setupConfigPath(sidecarHome), config);
|
|
83724
|
+
applySetupConfig(process.env, config);
|
|
83725
|
+
setupCredentialPassword = password;
|
|
83726
|
+
console.log("Pinned proving bundle and witness validated for this activated credential.");
|
|
83727
|
+
console.log("Local setup paths saved to " + setupConfigPath(sidecarHome));
|
|
83728
|
+
},
|
|
82509
83729
|
configureCodex: async (model) => {
|
|
82510
83730
|
await writeCodexProfile({ codexHome, loopbackBaseUrl: loopbackBaseUrl(), model });
|
|
82511
83731
|
},
|