@escro/mcp 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tools.cjs CHANGED
@@ -2297,8 +2297,8 @@ var import_bs583 = __toESM(require("bs58"), 1);
2297
2297
  var import_web32 = require("@solana/web3.js");
2298
2298
  var import_bs584 = __toESM(require("bs58"), 1);
2299
2299
  var import_web33 = require("@solana/web3.js");
2300
- var import_bs585 = __toESM(require("bs58"), 1);
2301
2300
  var import_web34 = require("@solana/web3.js");
2301
+ var import_bs585 = __toESM(require("bs58"), 1);
2302
2302
  var import_bs586 = __toESM(require("bs58"), 1);
2303
2303
  var import_bs587 = __toESM(require("bs58"), 1);
2304
2304
  var import_web35 = require("@solana/web3.js");
@@ -2337,7 +2337,6 @@ var SOLANA_CAIP2_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
2337
2337
  function escrowFee(amount, feeBps) {
2338
2338
  return amount * BigInt(feeBps) / 10000n;
2339
2339
  }
2340
- var CURRENT_ACCOUNT_VERSION = 1;
2341
2340
  var ONCHAIN_REFUND_GRACE_SECONDS = 900;
2342
2341
  var ONCHAIN_TIMEOUT_SECONDS = 86400;
2343
2342
  var CLOCK_SKEW_SECONDS = 60;
@@ -2390,6 +2389,27 @@ var ESCROW_INSTRUCTIONS = {
2390
2389
  arbitration_release: spec([118, 157, 141, 26, 104, 117, 94, 229], 4, "ARBITRATION_RELEASE"),
2391
2390
  arbitration_refund: spec([255, 194, 84, 248, 185, 249, 120, 122], 4, "ARBITRATION_REFUND")
2392
2391
  };
2392
+ var NON_ESCROW_INSTRUCTIONS = {
2393
+ initialize_platform: Uint8Array.from([119, 201, 101, 45, 75, 122, 89, 3]),
2394
+ initialize_admin_config: Uint8Array.from([133, 214, 35, 2, 50, 232, 95, 164]),
2395
+ close_platform: Uint8Array.from([27, 145, 216, 122, 13, 15, 46, 201]),
2396
+ update_platform: Uint8Array.from([46, 78, 138, 189, 47, 163, 120, 85]),
2397
+ set_admin_authority: Uint8Array.from([72, 49, 37, 167, 149, 98, 49, 174]),
2398
+ migrate_escrow_v1_to_v2: Uint8Array.from([70, 76, 99, 21, 154, 50, 111, 221])
2399
+ };
2400
+ var RETIRED_INSTRUCTIONS = {
2401
+ claim_open_task: Uint8Array.from([31, 61, 16, 69, 194, 74, 72, 148])
2402
+ };
2403
+ var ANCHOR_IDL_INSTRUCTION_TAG = Uint8Array.from([
2404
+ 64,
2405
+ 244,
2406
+ 188,
2407
+ 120,
2408
+ 167,
2409
+ 233,
2410
+ 105,
2411
+ 10
2412
+ ]);
2393
2413
  var utf8 = (s) => new TextEncoder().encode(s);
2394
2414
  function deriveEscrowPda(programId, buyer, taskId) {
2395
2415
  return import_web32.PublicKey.findProgramAddressSync(
@@ -2450,6 +2470,7 @@ var SPEND_CAP_ERROR_CODES = {
2450
2470
  /** The outstanding deposits could not be read. */
2451
2471
  unreadable: "SPEND_CAP_UNREADABLE"
2452
2472
  };
2473
+ var ESCROW_READABLE_VERSIONS = [1, 2];
2453
2474
  var ONCHAIN_REFUND_GRACE_SECONDS2 = 900;
2454
2475
  var ONCHAIN_TIMEOUT_SECONDS2 = 86400;
2455
2476
  var CLOCK_SKEW_SECONDS2 = 60;
@@ -2574,7 +2595,7 @@ var Reader2 = class {
2574
2595
  }
2575
2596
  switch (type) {
2576
2597
  case "pubkey":
2577
- return import_bs586.default.encode(this.take(32));
2598
+ return import_bs585.default.encode(this.take(32));
2578
2599
  case "string": {
2579
2600
  const length = this.view(4).getUint32(0, true);
2580
2601
  return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(this.take(length));
@@ -2642,7 +2663,8 @@ function build(name, f) {
2642
2663
  deadline: num(f, "deadline"),
2643
2664
  specHash: str(f, "spec_hash"),
2644
2665
  createdAt: num(f, "created_at"),
2645
- assignedWorker: optStr(f, "assigned_worker")
2666
+ assignedWorker: optStr(f, "assigned_worker"),
2667
+ marketplaceId: optStr(f, "marketplace_id")
2646
2668
  };
2647
2669
  case "TaskClaimed":
2648
2670
  return {
@@ -2714,6 +2736,9 @@ function decodeEscroEvent(data) {
2714
2736
  reader.end();
2715
2737
  return build(name, fields);
2716
2738
  }
2739
+ function isMarketStamped(created) {
2740
+ return created.marketplaceId !== null;
2741
+ }
2717
2742
  var INVOKE = /^Program (\w+) invoke \[(\d+)\]$/;
2718
2743
  var EXIT = /^Program (\w+) (?:success|failed)/;
2719
2744
  var DATA = "Program data: ";
@@ -2784,6 +2809,27 @@ var ESCROW_INSTRUCTIONS2 = {
2784
2809
  arbitration_release: spec2([118, 157, 141, 26, 104, 117, 94, 229], 4, "ARBITRATION_RELEASE"),
2785
2810
  arbitration_refund: spec2([255, 194, 84, 248, 185, 249, 120, 122], 4, "ARBITRATION_REFUND")
2786
2811
  };
2812
+ var NON_ESCROW_INSTRUCTIONS2 = {
2813
+ initialize_platform: Uint8Array.from([119, 201, 101, 45, 75, 122, 89, 3]),
2814
+ initialize_admin_config: Uint8Array.from([133, 214, 35, 2, 50, 232, 95, 164]),
2815
+ close_platform: Uint8Array.from([27, 145, 216, 122, 13, 15, 46, 201]),
2816
+ update_platform: Uint8Array.from([46, 78, 138, 189, 47, 163, 120, 85]),
2817
+ set_admin_authority: Uint8Array.from([72, 49, 37, 167, 149, 98, 49, 174]),
2818
+ migrate_escrow_v1_to_v2: Uint8Array.from([70, 76, 99, 21, 154, 50, 111, 221])
2819
+ };
2820
+ var RETIRED_INSTRUCTIONS2 = {
2821
+ claim_open_task: Uint8Array.from([31, 61, 16, 69, 194, 74, 72, 148])
2822
+ };
2823
+ var ANCHOR_IDL_INSTRUCTION_TAG2 = Uint8Array.from([
2824
+ 64,
2825
+ 244,
2826
+ 188,
2827
+ 120,
2828
+ 167,
2829
+ 233,
2830
+ 105,
2831
+ 10
2832
+ ]);
2787
2833
  var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
2788
2834
  var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2789
2835
  function parsedJson(text) {
@@ -2831,20 +2877,20 @@ function transactionVersionFetch(fetchFn) {
2831
2877
  );
2832
2878
  };
2833
2879
  }
2834
- var ChainReadError = class extends EscroError {
2835
- constructor(code, message, options = {}) {
2836
- super(message, code, void 0, "cause" in options ? { cause: options.cause } : void 0);
2837
- __publicField(this, "reason");
2838
- this.name = "ChainReadError";
2839
- this.reason = options.reason;
2840
- }
2841
- };
2842
- var ARCHIVAL_RPC_NOTE = "A settled escrow is closed on chain and survives only in transaction history; if it is older than this RPC's history, read it through an archival RPC.";
2843
- var CHAIN_READ_MAX_TRANSACTIONS = 50;
2844
- var CHAIN_READ_MAX_SIGNATURE_PAGES = 5;
2845
- var SIGNATURE_PAGE = 1e3;
2880
+ var ESCROW_ACCOUNT_ALLOCATIONS = { 1: 537, 2: 672 };
2881
+ var PRE_VERSION_ESCROW_ACCOUNT_SIZES = [463, 536];
2882
+ var E2E_SHORT_TIMEOUT_SECONDS = 8;
2846
2883
  var ESCROW_ACCOUNT_DISCRIMINATOR = [36, 69, 48, 18, 128, 225, 125, 135];
2847
- var ESCROW_ACCOUNT_LAYOUT = [
2884
+ var ESCROW_ACCOUNT_STATES = [
2885
+ "Created",
2886
+ "Funded",
2887
+ "InProgress",
2888
+ "Submitted",
2889
+ "Completed",
2890
+ "Disputed",
2891
+ "Refunded"
2892
+ ];
2893
+ var ESCROW_ACCOUNT_V1_FIELDS = [
2848
2894
  { name: "version", kind: "u8" },
2849
2895
  { name: "buyer", kind: "pubkey" },
2850
2896
  { name: "assigned_worker", kind: "option<pubkey>" },
@@ -2855,7 +2901,7 @@ var ESCROW_ACCOUNT_LAYOUT = [
2855
2901
  { name: "spec_hash", kind: "string" },
2856
2902
  { name: "deliverable_hash", kind: "option<string>" },
2857
2903
  { name: "proof_uri", kind: "option<string>" },
2858
- { name: "state", kind: "enum" },
2904
+ { name: "state", kind: "state" },
2859
2905
  { name: "created_at", kind: "i64" },
2860
2906
  { name: "updated_at", kind: "i64" },
2861
2907
  { name: "submitted_at", kind: "option<i64>" },
@@ -2865,125 +2911,372 @@ var ESCROW_ACCOUNT_LAYOUT = [
2865
2911
  { name: "referrer_wallet", kind: "option<pubkey>" },
2866
2912
  { name: "referrer_bps", kind: "u16" }
2867
2913
  ];
2868
- var ESCROW_ACCOUNT_SIZE = 537;
2869
- var STATE_VARIANTS = [
2870
- "Created",
2871
- "Funded",
2872
- "InProgress",
2873
- "Submitted",
2874
- "Completed",
2875
- "Disputed",
2876
- "Refunded"
2914
+ var ESCROW_TERMS_FIELDS = [
2915
+ { name: "settlement_mode", kind: "settlement_mode" },
2916
+ { name: "review_window_seconds", kind: "u32" },
2917
+ { name: "evaluator", kind: "pubkey" },
2918
+ { name: "payout_network", kind: "bytes32" },
2919
+ { name: "operator", kind: "pubkey" },
2920
+ { name: "operator_fee_bps", kind: "u16" },
2921
+ { name: "arbitrator", kind: "pubkey" }
2877
2922
  ];
2878
- var STATE_OF = {
2879
- Created: EscrowState.CREATED,
2880
- Funded: EscrowState.FUNDED,
2881
- InProgress: EscrowState.IN_PROGRESS,
2882
- Submitted: EscrowState.SUBMITTED,
2883
- Completed: EscrowState.COMPLETED,
2884
- Disputed: EscrowState.DISPUTED,
2885
- Refunded: EscrowState.REFUNDED
2886
- };
2887
- var MAX_TASK_ID_BYTES = 32;
2888
- var AccountProblem = class extends Error {
2889
- constructor(reason, detail) {
2890
- super(detail);
2891
- __publicField(this, "reason", reason);
2892
- __publicField(this, "detail", detail);
2923
+ var SETTLEMENT_MODE_BYTES = { release: 0, refund: 1 };
2924
+ var ZERO_KEY = import_bs587.default.encode(new Uint8Array(32));
2925
+ var ZERO_HEX32 = "0".repeat(64);
2926
+ var MAX_U32 = 4294967295;
2927
+ function v1DefaultTerms(buyer, v1ReviewWindowSeconds) {
2928
+ if (!Number.isInteger(v1ReviewWindowSeconds) || v1ReviewWindowSeconds < 1 || v1ReviewWindowSeconds > MAX_U32) {
2929
+ throw new RangeError(
2930
+ `version-1 review window ${String(v1ReviewWindowSeconds)} is not an integer in 1..${String(MAX_U32)}`
2931
+ );
2932
+ }
2933
+ return {
2934
+ settlementMode: "release",
2935
+ reviewWindowSeconds: v1ReviewWindowSeconds,
2936
+ evaluator: buyer,
2937
+ payoutNetwork: ZERO_HEX32,
2938
+ operator: ZERO_KEY,
2939
+ operatorFeeBps: 0,
2940
+ arbitrator: ZERO_KEY
2941
+ };
2942
+ }
2943
+ var EscrowAccountDecodeError = class extends Error {
2944
+ constructor(reason, dataLength, version, field2, detail) {
2945
+ const at = [
2946
+ `${String(dataLength)} bytes`,
2947
+ ...version === null ? [] : [`version ${String(version)}`],
2948
+ ...field2 === null ? [] : [`field ${field2}`]
2949
+ ].join(", ");
2950
+ super(`${reason}: ${at}: ${detail}`);
2951
+ __publicField(this, "reason");
2952
+ __publicField(this, "dataLength");
2953
+ __publicField(this, "version");
2954
+ __publicField(this, "field");
2955
+ this.name = "EscrowAccountDecodeError";
2956
+ this.reason = reason;
2957
+ this.dataLength = dataLength;
2958
+ this.version = version;
2959
+ this.field = field2;
2893
2960
  }
2894
2961
  };
2895
- var AccountReader = class {
2896
- constructor(data) {
2897
- __publicField(this, "data", data);
2898
- __publicField(this, "at", 0);
2962
+ var Walk = class {
2963
+ constructor(data, version) {
2964
+ __publicField(this, "at", 8);
2965
+ __publicField(this, "values", /* @__PURE__ */ new Map());
2966
+ __publicField(this, "utf8", new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }));
2967
+ __publicField(this, "data");
2968
+ __publicField(this, "version");
2969
+ this.data = data;
2970
+ this.version = version;
2899
2971
  }
2900
- take(n) {
2972
+ fields(list) {
2973
+ for (const { name, kind } of list) this.values.set(name, this.read(name, kind));
2974
+ }
2975
+ refuse(field2, detail) {
2976
+ return new EscrowAccountDecodeError("layout", this.data.length, this.version, field2, detail);
2977
+ }
2978
+ take(field2, n) {
2901
2979
  if (this.at + n > this.data.length) {
2902
- throw new AccountProblem("layout", "a field reads past the content");
2980
+ throw this.refuse(
2981
+ field2,
2982
+ `${String(n)} bytes at offset ${String(this.at)} run past the account`
2983
+ );
2903
2984
  }
2904
2985
  const bytes = this.data.subarray(this.at, this.at + n);
2905
2986
  this.at += n;
2906
2987
  return bytes;
2907
2988
  }
2908
- view(n) {
2909
- const bytes = this.take(n);
2989
+ view(field2, n) {
2990
+ const bytes = this.take(field2, n);
2910
2991
  return new DataView(bytes.buffer, bytes.byteOffset, n);
2911
2992
  }
2912
- skip(n) {
2913
- this.take(n);
2993
+ optionTag(field2) {
2994
+ const tag = this.view(field2, 1).getUint8(0);
2995
+ if (tag > 1) throw this.refuse(field2, `option tag ${String(tag)} is neither 0 nor 1`);
2996
+ return tag === 1;
2914
2997
  }
2915
- scalar(kind) {
2916
- if (kind === "pubkey") return import_bs585.default.encode(this.take(32));
2917
- if (kind === "string") {
2918
- const length = this.view(4).getUint32(0, true);
2919
- try {
2920
- return new TextDecoder("utf-8", { fatal: true }).decode(this.take(length));
2921
- } catch (err) {
2922
- if (err instanceof AccountProblem) throw err;
2923
- throw new AccountProblem("layout", "a string field is not UTF-8");
2924
- }
2925
- }
2926
- const value = this.view(8).getBigInt64(0, true);
2927
- if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
2928
- throw new AccountProblem("layout", "an i64 field is outside the safe integer range");
2929
- }
2930
- return Number(value);
2931
- }
2932
- read(kind) {
2998
+ read(field2, kind) {
2933
2999
  switch (kind) {
2934
3000
  case "u8":
2935
- return this.view(1).getUint8(0);
3001
+ return this.view(field2, 1).getUint8(0);
2936
3002
  case "u16":
2937
- return this.view(2).getUint16(0, true);
3003
+ return this.view(field2, 2).getUint16(0, true);
3004
+ case "u32":
3005
+ return this.view(field2, 4).getUint32(0, true);
2938
3006
  case "u64":
2939
- return this.view(8).getBigUint64(0, true);
2940
- case "pubkey":
2941
- case "string":
3007
+ return this.view(field2, 8).getBigUint64(0, true);
2942
3008
  case "i64":
2943
- return this.scalar(kind);
2944
- case "enum": {
2945
- const index = this.view(1).getUint8(0);
2946
- const variant = STATE_VARIANTS[index];
2947
- if (variant === void 0) {
2948
- throw new AccountProblem("layout", `state ${String(index)} is no EscrowState variant`);
3009
+ return this.view(field2, 8).getBigInt64(0, true);
3010
+ case "pubkey":
3011
+ return import_bs587.default.encode(this.take(field2, 32));
3012
+ case "bytes32":
3013
+ return Array.from(this.take(field2, 32), (b) => b.toString(16).padStart(2, "0")).join("");
3014
+ case "string": {
3015
+ const length = this.view(field2, 4).getUint32(0, true);
3016
+ const bytes = this.take(field2, length);
3017
+ try {
3018
+ return this.utf8.decode(bytes);
3019
+ } catch {
3020
+ throw this.refuse(field2, "the string is not valid UTF-8");
2949
3021
  }
2950
- return variant;
2951
3022
  }
2952
3023
  case "option<pubkey>":
3024
+ return this.optionTag(field2) ? this.read(field2, "pubkey") : null;
2953
3025
  case "option<string>":
2954
- case "option<i64>": {
2955
- const tag = this.view(1).getUint8(0);
2956
- if (tag === 0) return null;
2957
- if (tag !== 1) throw new AccountProblem("layout", `an option tag is ${String(tag)}`);
2958
- return this.scalar(
2959
- kind === "option<pubkey>" ? "pubkey" : kind === "option<string>" ? "string" : "i64"
2960
- );
3026
+ return this.optionTag(field2) ? this.read(field2, "string") : null;
3027
+ case "option<i64>":
3028
+ return this.optionTag(field2) ? this.read(field2, "i64") : null;
3029
+ case "state": {
3030
+ const byte = this.view(field2, 1).getUint8(0);
3031
+ const state = ESCROW_ACCOUNT_STATES[byte];
3032
+ if (state === void 0) throw this.refuse(field2, `state byte ${String(byte)}`);
3033
+ return state;
3034
+ }
3035
+ case "settlement_mode": {
3036
+ const byte = this.view(field2, 1).getUint8(0);
3037
+ if (byte === SETTLEMENT_MODE_BYTES.release) return "release";
3038
+ if (byte === SETTLEMENT_MODE_BYTES.refund) return "refund";
3039
+ throw this.refuse(field2, `settlement mode byte ${String(byte)}`);
2961
3040
  }
2962
3041
  }
2963
3042
  }
3043
+ value(name) {
3044
+ if (!this.values.has(name)) throw new Error(`EscrowAccount field ${name} was not read`);
3045
+ return this.values.get(name) ?? null;
3046
+ }
3047
+ num(name) {
3048
+ const v = this.value(name);
3049
+ if (typeof v !== "number") throw new Error(`EscrowAccount field ${name} is not a number`);
3050
+ return v;
3051
+ }
3052
+ big(name) {
3053
+ const v = this.value(name);
3054
+ if (typeof v !== "bigint")
3055
+ throw new Error(`EscrowAccount field ${name} is not a 64-bit integer`);
3056
+ return v;
3057
+ }
3058
+ str(name) {
3059
+ const v = this.value(name);
3060
+ if (typeof v !== "string") throw new Error(`EscrowAccount field ${name} is not a string`);
3061
+ return v;
3062
+ }
3063
+ optStr(name) {
3064
+ return this.value(name) === null ? null : this.str(name);
3065
+ }
3066
+ optBig(name) {
3067
+ return this.value(name) === null ? null : this.big(name);
3068
+ }
3069
+ state() {
3070
+ const v = this.str("state");
3071
+ const state = ESCROW_ACCOUNT_STATES.find((s) => s === v);
3072
+ if (state === void 0) throw new Error(`EscrowAccount state ${v} is not a variant`);
3073
+ return state;
3074
+ }
3075
+ settlementMode() {
3076
+ const v = this.str("settlement_mode");
3077
+ if (v !== "release" && v !== "refund") {
3078
+ throw new Error(`EscrowAccount settlement mode ${v} is not a variant`);
3079
+ }
3080
+ return v;
3081
+ }
2964
3082
  };
2965
- function decodeAccount(data) {
2966
- if (data.length < ESCROW_ACCOUNT_DISCRIMINATOR.length || ESCROW_ACCOUNT_DISCRIMINATOR.some((byte, i) => data[i] !== byte)) {
2967
- throw new AccountProblem("discriminator", "its discriminator is not EscrowAccount's");
3083
+ function isReadableVersion(byte) {
3084
+ return ESCROW_READABLE_VERSIONS.includes(byte);
3085
+ }
3086
+ function decodeEscrowAccount(data, opts) {
3087
+ const length = data.length;
3088
+ if (length < 8 || ESCROW_ACCOUNT_DISCRIMINATOR.some((byte, i) => data[i] !== byte)) {
3089
+ throw new EscrowAccountDecodeError(
3090
+ "discriminator",
3091
+ length,
3092
+ null,
3093
+ null,
3094
+ "not the EscrowAccount discriminator"
3095
+ );
2968
3096
  }
2969
- const version = data[ESCROW_ACCOUNT_DISCRIMINATOR.length];
2970
- if (version !== void 0 && version !== CURRENT_ACCOUNT_VERSION) {
2971
- throw new AccountProblem(
3097
+ if (PRE_VERSION_ESCROW_ACCOUNT_SIZES.includes(length)) {
3098
+ throw new EscrowAccountDecodeError(
3099
+ "pre-version",
3100
+ length,
3101
+ null,
3102
+ null,
3103
+ "a layout that predates the version byte"
3104
+ );
3105
+ }
3106
+ const versionByte = data[8];
3107
+ if (versionByte === void 0) {
3108
+ throw new EscrowAccountDecodeError("size", length, null, null, "no version byte");
3109
+ }
3110
+ if (!isReadableVersion(versionByte)) {
3111
+ throw new EscrowAccountDecodeError(
2972
3112
  "version",
2973
- `its version is ${String(version)}; this reader reads version ${String(CURRENT_ACCOUNT_VERSION)}`
3113
+ length,
3114
+ versionByte,
3115
+ null,
3116
+ `not a readable version (${ESCROW_READABLE_VERSIONS.join(", ")})`
3117
+ );
3118
+ }
3119
+ const allocation = ESCROW_ACCOUNT_ALLOCATIONS[versionByte];
3120
+ if (length !== allocation) {
3121
+ throw new EscrowAccountDecodeError(
3122
+ "size",
3123
+ length,
3124
+ versionByte,
3125
+ null,
3126
+ `version ${String(versionByte)} is allocated ${String(allocation)} bytes`
2974
3127
  );
2975
3128
  }
2976
- if (data.length !== ESCROW_ACCOUNT_SIZE) {
3129
+ const walk = new Walk(data, versionByte);
3130
+ walk.fields(ESCROW_ACCOUNT_V1_FIELDS);
3131
+ if (versionByte === 2) walk.fields(ESCROW_TERMS_FIELDS);
3132
+ const buyer = walk.str("buyer");
3133
+ const terms = versionByte === 1 ? v1DefaultTerms(buyer, opts.v1ReviewWindowSeconds) : {
3134
+ settlementMode: walk.settlementMode(),
3135
+ reviewWindowSeconds: walk.num("review_window_seconds"),
3136
+ evaluator: walk.str("evaluator"),
3137
+ payoutNetwork: walk.str("payout_network"),
3138
+ operator: walk.str("operator"),
3139
+ operatorFeeBps: walk.num("operator_fee_bps"),
3140
+ arbitrator: walk.str("arbitrator")
3141
+ };
3142
+ return {
3143
+ version: versionByte,
3144
+ buyer,
3145
+ assignedWorker: walk.optStr("assigned_worker"),
3146
+ taskId: walk.str("task_id"),
3147
+ amountUsdc: walk.big("amount_usdc"),
3148
+ feeBps: walk.num("fee_bps"),
3149
+ deadline: walk.big("deadline"),
3150
+ specHash: walk.str("spec_hash"),
3151
+ deliverableHash: walk.optStr("deliverable_hash"),
3152
+ proofUri: walk.optStr("proof_uri"),
3153
+ state: walk.state(),
3154
+ createdAt: walk.big("created_at"),
3155
+ updatedAt: walk.big("updated_at"),
3156
+ submittedAt: walk.optBig("submitted_at"),
3157
+ minAmount: walk.big("min_amount"),
3158
+ bump: walk.num("bump"),
3159
+ marketplaceId: walk.optStr("marketplace_id"),
3160
+ referrerWallet: walk.optStr("referrer_wallet"),
3161
+ referrerBps: walk.num("referrer_bps"),
3162
+ terms
3163
+ };
3164
+ }
3165
+ var DEFAULT_JOB_REVIEW_WINDOWS = [
3166
+ ONCHAIN_TIMEOUT_SECONDS2,
3167
+ E2E_SHORT_TIMEOUT_SECONDS
3168
+ ];
3169
+ var TERM_KEYS = [
3170
+ ["settlement_mode", "settlementMode"],
3171
+ ["review_window_seconds", "reviewWindowSeconds"],
3172
+ ["evaluator", "evaluator"],
3173
+ ["payout_network", "payoutNetwork"],
3174
+ ["operator", "operator"],
3175
+ ["operator_fee_bps", "operatorFeeBps"],
3176
+ ["arbitrator", "arbitrator"]
3177
+ ];
3178
+ function nonDefaultJobTerms(account) {
3179
+ if (account.version === 1) return [];
3180
+ const { terms } = account;
3181
+ const window = DEFAULT_JOB_REVIEW_WINDOWS.includes(terms.reviewWindowSeconds) ? terms.reviewWindowSeconds : ONCHAIN_TIMEOUT_SECONDS2;
3182
+ const expected = v1DefaultTerms(account.buyer, window);
3183
+ const found = TERM_KEYS.filter(([, key]) => terms[key] !== expected[key]).map(([name]) => name);
3184
+ return account.marketplaceId === null ? found : [...found, "marketplace_id"];
3185
+ }
3186
+ var ChainReadError = class extends EscroError {
3187
+ constructor(code, message, options = {}) {
3188
+ super(message, code, void 0, "cause" in options ? { cause: options.cause } : void 0);
3189
+ __publicField(this, "reason");
3190
+ this.name = "ChainReadError";
3191
+ this.reason = options.reason;
3192
+ }
3193
+ };
3194
+ var ARCHIVAL_RPC_NOTE = "A settled escrow is closed on chain and survives only in transaction history; if it is older than this RPC's history, read it through an archival RPC.";
3195
+ var CHAIN_READ_MAX_TRANSACTIONS = 50;
3196
+ var CHAIN_READ_MAX_SIGNATURE_PAGES = 5;
3197
+ var SIGNATURE_PAGE = 1e3;
3198
+ var FIELD_KINDS = [
3199
+ "pubkey",
3200
+ "u8",
3201
+ "u16",
3202
+ "u64",
3203
+ "i64",
3204
+ "string",
3205
+ "option<pubkey>",
3206
+ "option<string>",
3207
+ "option<i64>"
3208
+ ];
3209
+ function fieldKind(kind) {
3210
+ if (kind === "state") return "enum";
3211
+ const found = FIELD_KINDS.find((k) => k === kind);
3212
+ if (found === void 0) throw new Error(`no version-1 EscrowAccount field is of kind ${kind}`);
3213
+ return found;
3214
+ }
3215
+ var ESCROW_ACCOUNT_LAYOUT = ESCROW_ACCOUNT_V1_FIELDS.map(({ name, kind }) => ({ name, kind: fieldKind(kind) }));
3216
+ var ESCROW_ACCOUNT_SIZE = ESCROW_ACCOUNT_ALLOCATIONS[1];
3217
+ var STATE_OF = {
3218
+ Created: EscrowState.CREATED,
3219
+ Funded: EscrowState.FUNDED,
3220
+ InProgress: EscrowState.IN_PROGRESS,
3221
+ Submitted: EscrowState.SUBMITTED,
3222
+ Completed: EscrowState.COMPLETED,
3223
+ Disputed: EscrowState.DISPUTED,
3224
+ Refunded: EscrowState.REFUNDED
3225
+ };
3226
+ var MAX_TASK_ID_BYTES = 32;
3227
+ var AccountProblem = class extends Error {
3228
+ constructor(reason, detail) {
3229
+ super(detail);
3230
+ __publicField(this, "reason", reason);
3231
+ __publicField(this, "detail", detail);
3232
+ }
3233
+ };
3234
+ var REASON_OF = {
3235
+ discriminator: "discriminator",
3236
+ "pre-version": "version",
3237
+ version: "version",
3238
+ size: "layout",
3239
+ layout: "layout"
3240
+ };
3241
+ function safeInteger(name, value) {
3242
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
3243
+ throw new AccountProblem("layout", `${name} is outside the safe integer range`);
3244
+ }
3245
+ return Number(value);
3246
+ }
3247
+ var camelCase = (name) => name.replace(/_([a-z])/g, (_match, letter) => letter.toUpperCase());
3248
+ function recordOf(account) {
3249
+ const decoded2 = new Map(Object.entries(account));
3250
+ const record = {};
3251
+ for (const { name, kind } of ESCROW_ACCOUNT_V1_FIELDS) {
3252
+ const value = decoded2.get(camelCase(name));
3253
+ if (typeof value === "bigint" && (kind === "i64" || kind === "option<i64>")) {
3254
+ record[name] = safeInteger(name, value);
3255
+ } else if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "bigint") {
3256
+ record[name] = value;
3257
+ } else {
3258
+ throw new Error(`the decoded EscrowAccount carries no ${name}`);
3259
+ }
3260
+ }
3261
+ return record;
3262
+ }
3263
+ function decodeAccount(data) {
3264
+ let account;
3265
+ try {
3266
+ account = decodeEscrowAccount(data, { v1ReviewWindowSeconds: ONCHAIN_TIMEOUT_SECONDS });
3267
+ } catch (err) {
3268
+ if (!(err instanceof EscrowAccountDecodeError)) throw err;
3269
+ throw new AccountProblem(REASON_OF[err.reason], err.message);
3270
+ }
3271
+ const record = recordOf(account);
3272
+ const terms = nonDefaultJobTerms(account);
3273
+ if (terms.length > 0) {
2977
3274
  throw new AccountProblem(
2978
- "layout",
2979
- `it is ${String(data.length)} bytes; an EscrowAccount is ${String(ESCROW_ACCOUNT_SIZE)}`
3275
+ "version",
3276
+ `version ${String(account.version)} with terms other than the default job's (${terms.join(", ")}); this reader reads a version-2 escrow only on the default job's terms`
2980
3277
  );
2981
3278
  }
2982
- const reader = new AccountReader(data);
2983
- reader.skip(ESCROW_ACCOUNT_DISCRIMINATOR.length);
2984
- const decoded2 = {};
2985
- for (const field2 of ESCROW_ACCOUNT_LAYOUT) decoded2[field2.name] = reader.read(field2.kind);
2986
- return decoded2;
3279
+ return record;
2987
3280
  }
2988
3281
  function invalidInput(message) {
2989
3282
  return new ChainReadError("INVALID_INPUT", message);
@@ -3079,36 +3372,48 @@ function figures(base) {
3079
3372
  const feeMicro = escrowFee(base.amountMicro, base.feeBps);
3080
3373
  return { ...base, feeMicro, depositMicro: base.amountMicro + feeMicro };
3081
3374
  }
3082
- function readAccount(address, owner, data, programId, cluster) {
3083
- const at = address.toBase58();
3084
- const refuse5 = (problem) => new ChainReadError(
3375
+ function clusterProgramId(cluster) {
3376
+ const id = getProgramId(cluster);
3377
+ assertProgramIdNotPlaceholder(id, cluster);
3378
+ return new import_web34.PublicKey(id);
3379
+ }
3380
+ function refusedAt(at, problem) {
3381
+ return new ChainReadError(
3085
3382
  "CHAIN_ACCOUNT_INVALID",
3086
3383
  `The account at ${at} is not a current EscrowAccount: ${problem.detail}`,
3087
3384
  { reason: problem.reason }
3088
3385
  );
3386
+ }
3387
+ function ownedAccount(at, owner, data, programId) {
3089
3388
  if (!owner.equals(programId)) {
3090
- throw refuse5(
3389
+ throw refusedAt(
3390
+ at,
3091
3391
  new AccountProblem(
3092
3392
  "owner",
3093
3393
  `it is owned by ${owner.toBase58()}, not the program ${programId.toBase58()}`
3094
3394
  )
3095
3395
  );
3096
3396
  }
3097
- let decoded2;
3098
3397
  try {
3099
- decoded2 = decodeAccount(data);
3398
+ return decodeAccount(data);
3100
3399
  } catch (err) {
3101
- if (err instanceof AccountProblem) throw refuse5(err);
3400
+ if (err instanceof AccountProblem) throw refusedAt(at, err);
3102
3401
  throw err;
3103
3402
  }
3403
+ }
3404
+ function readAccount(address, owner, data, programId, cluster) {
3405
+ const at = address.toBase58();
3406
+ const decoded2 = ownedAccount(at, owner, data, programId);
3104
3407
  const buyer = stringOf(decoded2, "buyer");
3105
3408
  const taskId = stringOf(decoded2, "task_id");
3106
3409
  const derived = new TextEncoder().encode(taskId).length <= MAX_TASK_ID_BYTES ? deriveEscrowPda(programId, new import_web34.PublicKey(buyer), taskId) : null;
3107
3410
  if (!derived?.equals(address)) {
3108
- throw refuse5(new AccountProblem("pda", "its buyer and task id do not derive this address"));
3411
+ throw refusedAt(
3412
+ at,
3413
+ new AccountProblem("pda", "its buyer and task id do not derive this address")
3414
+ );
3109
3415
  }
3110
- const variant = stringOf(decoded2, "state");
3111
- const state = STATE_OF[variant];
3416
+ const state = STATE_OF[stringOf(decoded2, "state")];
3112
3417
  return {
3113
3418
  source: "account",
3114
3419
  cluster,
@@ -3246,6 +3551,13 @@ function readHistory(lifecycle, address, programId, cluster) {
3246
3551
  if (create?.name !== "EscrowCreated" || last === void 0) {
3247
3552
  throw new Error(`the lifecycle of ${address} does not open with EscrowCreated`);
3248
3553
  }
3554
+ if (isMarketStamped(create)) {
3555
+ throw new ChainReadError(
3556
+ "CHAIN_ACCOUNT_INVALID",
3557
+ `The escrow at ${address} was created in a market (its EscrowCreated carries a marketplace_id); this reader reads a closed escrow only without a market stamp`,
3558
+ { reason: "version" }
3559
+ );
3560
+ }
3249
3561
  let settlement;
3250
3562
  let state;
3251
3563
  const settled = last.event;
@@ -3308,27 +3620,230 @@ function readHistory(lifecycle, address, programId, cluster) {
3308
3620
  signatures: lifecycle.map((t) => t.signature)
3309
3621
  };
3310
3622
  }
3311
- async function readEscrowFromChain(target, options) {
3312
- const maxTransactions = options.maxTransactions ?? CHAIN_READ_MAX_TRANSACTIONS;
3313
- if (!Number.isSafeInteger(maxTransactions) || maxTransactions < 1) {
3314
- throw invalidInput("maxTransactions must be a positive integer");
3315
- }
3316
- const id = getProgramId(options.cluster);
3317
- assertProgramIdNotPlaceholder(id, options.cluster);
3318
- const programId = new import_web34.PublicKey(id);
3319
- const address = resolveTarget(target, programId);
3320
- const rpc = options.rpc;
3321
- const account = await call(
3322
- "getAccountInfo",
3323
- () => rpc.getAccountInfo(address, { commitment: "confirmed" })
3324
- );
3325
- const closedButFunded = account !== null && account.owner.equals(import_web34.SystemProgram.programId) && account.data.length === 0;
3326
- if (account !== null && !closedButFunded) {
3327
- return readAccount(address, account.owner, account.data, programId, options.cluster);
3328
- }
3329
- const lifecycle = await readLifecycle(rpc, address, id, maxTransactions);
3330
- return readHistory(lifecycle, address.toBase58(), id, options.cluster);
3331
- }
3623
+ async function readEscrowFromChain(target, options) {
3624
+ const maxTransactions = options.maxTransactions ?? CHAIN_READ_MAX_TRANSACTIONS;
3625
+ if (!Number.isSafeInteger(maxTransactions) || maxTransactions < 1) {
3626
+ throw invalidInput("maxTransactions must be a positive integer");
3627
+ }
3628
+ const programId = clusterProgramId(options.cluster);
3629
+ const id = programId.toBase58();
3630
+ const address = resolveTarget(target, programId);
3631
+ const rpc = options.rpc;
3632
+ const account = await call(
3633
+ "getAccountInfo",
3634
+ () => rpc.getAccountInfo(address, { commitment: "confirmed" })
3635
+ );
3636
+ const closedButFunded = account !== null && account.owner.equals(import_web34.SystemProgram.programId) && account.data.length === 0;
3637
+ if (account !== null && !closedButFunded) {
3638
+ return readAccount(address, account.owner, account.data, programId, options.cluster);
3639
+ }
3640
+ const lifecycle = await readLifecycle(rpc, address, id, maxTransactions);
3641
+ return readHistory(lifecycle, address.toBase58(), id, options.cluster);
3642
+ }
3643
+ function parseIpv4(text) {
3644
+ const octets = text.split(".");
3645
+ if (octets.length !== 4) return null;
3646
+ let n = 0;
3647
+ for (const octet of octets) {
3648
+ if (!/^(?:0|[1-9][0-9]{0,2})$/.test(octet) || Number(octet) > 255) return null;
3649
+ n = n * 256 + Number(octet);
3650
+ }
3651
+ return n;
3652
+ }
3653
+ function ipv6Groups(side, holdsTail) {
3654
+ if (side === "") return [];
3655
+ const fields = side.split(":");
3656
+ const groups = [];
3657
+ for (const [i, field2] of fields.entries()) {
3658
+ if (holdsTail && i === fields.length - 1 && field2.includes(".")) {
3659
+ const v4 = parseIpv4(field2);
3660
+ if (v4 === null) return null;
3661
+ groups.push(Math.floor(v4 / 65536), v4 % 65536);
3662
+ } else if (/^[0-9a-f]{1,4}$/i.test(field2)) {
3663
+ groups.push(parseInt(field2, 16));
3664
+ } else {
3665
+ return null;
3666
+ }
3667
+ }
3668
+ return groups;
3669
+ }
3670
+ function parseIpv6(text) {
3671
+ if (!/^[0-9a-f:.]+$/i.test(text)) return null;
3672
+ const sides = text.split("::");
3673
+ if (sides.length > 2) return null;
3674
+ const [head = "", tail] = sides;
3675
+ const left = ipv6Groups(head, tail === void 0);
3676
+ const right = tail === void 0 ? [] : ipv6Groups(tail, true);
3677
+ if (left === null || right === null) return null;
3678
+ const explicit = left.length + right.length;
3679
+ if (tail === void 0 ? explicit !== 8 : explicit > 7) return null;
3680
+ const groups = [...left, ...new Array(8 - explicit).fill(0), ...right];
3681
+ return groups.reduce((n, group) => n << 16n | BigInt(group), 0n);
3682
+ }
3683
+ function ipv4Range(cidr) {
3684
+ const [address = "", bits = ""] = cidr.split("/");
3685
+ const base = parseIpv4(address);
3686
+ if (base === null) throw new Error(`the refused set holds an unparseable range ${cidr}`);
3687
+ return { base, bits: Number(bits) };
3688
+ }
3689
+ function ipv6Range(cidr) {
3690
+ const [address = "", bits = ""] = cidr.split("/");
3691
+ const base = parseIpv6(address);
3692
+ if (base === null) throw new Error(`the refused set holds an unparseable range ${cidr}`);
3693
+ return { base, bits: Number(bits) };
3694
+ }
3695
+ var inIpv4Range = (n, { base, bits }) => Math.floor(n / 2 ** (32 - bits)) === Math.floor(base / 2 ** (32 - bits));
3696
+ var inIpv6Range = (n, { base, bits }) => n >> BigInt(128 - bits) === base >> BigInt(128 - bits);
3697
+ var REFUSED_IPV4 = [
3698
+ "0.0.0.0/8",
3699
+ "10.0.0.0/8",
3700
+ "100.64.0.0/10",
3701
+ "127.0.0.0/8",
3702
+ "168.63.129.16/32",
3703
+ "169.254.0.0/16",
3704
+ "172.16.0.0/12",
3705
+ "192.0.0.0/24",
3706
+ "192.168.0.0/16",
3707
+ "198.18.0.0/15",
3708
+ "224.0.0.0/4",
3709
+ "240.0.0.0/4"
3710
+ ].map(ipv4Range);
3711
+ var REFUSED_IPV6 = [
3712
+ "::/128",
3713
+ "::1/128",
3714
+ "fc00::/7",
3715
+ "fe80::/10",
3716
+ "fec0::/10",
3717
+ "ff00::/8",
3718
+ "2001::/32",
3719
+ "2002::/16",
3720
+ "64:ff9b:1::/48"
3721
+ ].map(ipv6Range);
3722
+ var IPV4_EMBEDDINGS = ["::ffff:0:0/96", "::/96", "64:ff9b::/96"].map(ipv6Range);
3723
+ function isPublicAddress(address) {
3724
+ const v4 = parseIpv4(address);
3725
+ if (v4 !== null) return !REFUSED_IPV4.some((range) => inIpv4Range(v4, range));
3726
+ const v6 = parseIpv6(address);
3727
+ if (v6 === null) return false;
3728
+ if (REFUSED_IPV6.some((range) => inIpv6Range(v6, range))) return false;
3729
+ if (IPV4_EMBEDDINGS.some((range) => inIpv6Range(v6, range))) {
3730
+ return isPublicAddress(
3731
+ [24n, 16n, 8n, 0n].map((shift) => String(v6 >> shift & 0xffn)).join(".")
3732
+ );
3733
+ }
3734
+ return true;
3735
+ }
3736
+ function isLocalhostName(hostname) {
3737
+ const name = (hostname.endsWith(".") ? hostname.slice(0, -1) : hostname).toLowerCase();
3738
+ return name === "localhost" || name.endsWith(".localhost");
3739
+ }
3740
+ function literalReach(hostname) {
3741
+ if (hostname.startsWith("[") && hostname.endsWith("]")) {
3742
+ return isPublicAddress(hostname.slice(1, -1)) ? "public" : "private";
3743
+ }
3744
+ if (parseIpv4(hostname) !== null) return isPublicAddress(hostname) ? "public" : "private";
3745
+ if (isLocalhostName(hostname)) return "private";
3746
+ return null;
3747
+ }
3748
+ async function nameReach(hostname, lookup2) {
3749
+ let answers;
3750
+ try {
3751
+ answers = await lookup2(hostname, { all: true });
3752
+ } catch {
3753
+ return null;
3754
+ }
3755
+ if (answers.length === 0) return null;
3756
+ const publicCount = answers.filter(({ address }) => isPublicAddress(address)).length;
3757
+ if (publicCount === answers.length) return "public";
3758
+ return publicCount === 0 ? "private" : "mixed";
3759
+ }
3760
+ async function payUrlRefusal(url, options) {
3761
+ if (!URL.canParse(url)) return null;
3762
+ const { protocol, hostname } = new URL(url);
3763
+ if (protocol !== "http:" && protocol !== "https:") return null;
3764
+ const allowPrivate = options.allowPrivateHosts;
3765
+ const mainnetHttp = options.cluster !== "devnet" && protocol === "http:";
3766
+ if (mainnetHttp && !allowPrivate) return "mainnet_http";
3767
+ if (allowPrivate && !mainnetHttp) return null;
3768
+ const literal = literalReach(hostname);
3769
+ if (!allowPrivate && literal === "private") return "private_host";
3770
+ const reach = literal ?? await nameReach(hostname, options.lookup);
3771
+ if (reach === null) return "unresolved_host";
3772
+ if (!allowPrivate) return reach === "public" ? null : "private_host";
3773
+ return reach === "private" ? null : "mainnet_http";
3774
+ }
3775
+ function payAddressRule(options) {
3776
+ const publicOnly = (address) => isPublicAddress(address);
3777
+ if (!URL.canParse(options.url)) return publicOnly;
3778
+ const { protocol } = new URL(options.url);
3779
+ if (protocol !== "http:" && protocol !== "https:") return publicOnly;
3780
+ if (!options.allowPrivateHosts) return publicOnly;
3781
+ if (options.cluster !== "devnet" && protocol === "http:") {
3782
+ return (address, target) => target === "spec" || !isPublicAddress(address);
3783
+ }
3784
+ return void 0;
3785
+ }
3786
+ var ESCROW_RAIL_SCHEMES = ["on-delivery", "job-escrow"];
3787
+ function deadlineBoundedPolicy(terms) {
3788
+ const bound = terms.maxDeadlineSeconds;
3789
+ if (!Number.isSafeInteger(bound) || bound < 1) {
3790
+ throw new EscroError(
3791
+ `maxDeadlineSeconds must be a positive whole number of seconds, got ${String(bound)}`,
3792
+ "VALIDATION_ERROR"
3793
+ );
3794
+ }
3795
+ const escrowOnly = terms.escrowOnly;
3796
+ if (escrowOnly !== void 0 && typeof escrowOnly !== "boolean") {
3797
+ throw new EscroError(
3798
+ `escrowOnly must be true, false or absent, got ${typeof escrowOnly}`,
3799
+ "VALIDATION_ERROR"
3800
+ );
3801
+ }
3802
+ const now = terms.now ?? (() => Date.now());
3803
+ const amount = String(terms.amountMicroUsdc);
3804
+ const network = terms.cluster === "devnet" ? SOLANA_CAIP2_DEVNET : SOLANA_CAIP2_MAINNET;
3805
+ return (accepts) => {
3806
+ const reading = now();
3807
+ if (typeof reading !== "number" || !Number.isSafeInteger(reading)) {
3808
+ throw new EscroError(
3809
+ "The pay policy's clock must return whole milliseconds; nothing was signed or funded",
3810
+ "VALIDATION_ERROR"
3811
+ );
3812
+ }
3813
+ const latest = Math.floor(reading / 1e3) + bound;
3814
+ const onTerms = accepts.filter(
3815
+ (entry) => entry.payTo === terms.to && entry.amount === amount && entry.network === network
3816
+ );
3817
+ const escrowEntries = onTerms.filter((entry) => ESCROW_RAIL_SCHEMES.includes(entry.scheme));
3818
+ if (escrowEntries.length > 0) {
3819
+ const inBound = escrowEntries.find((entry) => {
3820
+ const deadline = entry.extra?.deadline;
3821
+ return typeof deadline === "number" && Number.isSafeInteger(deadline) && deadline <= latest;
3822
+ });
3823
+ if (inBound !== void 0) return inBound;
3824
+ throw new EscroPayError(
3825
+ "no_eligible_entry",
3826
+ `The 402 offers no escrow entry paying this worker this amount with a deadline at or before ${String(latest)} (Unix seconds: now plus ${String(bound)}). Nothing was signed or funded.`,
3827
+ { detail: "deadline" }
3828
+ );
3829
+ }
3830
+ if (escrowOnly === true) {
3831
+ throw new EscroPayError(
3832
+ "no_eligible_entry",
3833
+ `The 402 offers no escrow entry paying ${amount} micro-USDC to ${terms.to}. Nothing was signed or funded.`,
3834
+ { detail: "escrow_only" }
3835
+ );
3836
+ }
3837
+ const exact = onTerms.find((entry) => entry.scheme === "exact");
3838
+ if (exact !== void 0) return exact;
3839
+ const [first] = onTerms;
3840
+ if (first !== void 0 && onTerms.every((entry) => entry.scheme === "upto")) return first;
3841
+ throw new EscroPayError(
3842
+ "no_eligible_entry",
3843
+ `The 402 offers no entry paying ${amount} micro-USDC to ${terms.to}`
3844
+ );
3845
+ };
3846
+ }
3332
3847
  function readonlySetOf(values) {
3333
3848
  const set = new Set(values);
3334
3849
  const view = Object.freeze({
@@ -4171,210 +4686,6 @@ function sha256Hex8(content) {
4171
4686
  return (0, import_crypto2.createHash)("sha256").update(content).digest("hex");
4172
4687
  }
4173
4688
  var ZKML_DEMO_MODEL_COMMITMENT = sha256Hex8("zkml-demo-classifier-v1");
4174
- function parseIpv4(text) {
4175
- const octets = text.split(".");
4176
- if (octets.length !== 4) return null;
4177
- let n = 0;
4178
- for (const octet of octets) {
4179
- if (!/^(?:0|[1-9][0-9]{0,2})$/.test(octet) || Number(octet) > 255) return null;
4180
- n = n * 256 + Number(octet);
4181
- }
4182
- return n;
4183
- }
4184
- function ipv6Groups(side, holdsTail) {
4185
- if (side === "") return [];
4186
- const fields = side.split(":");
4187
- const groups = [];
4188
- for (const [i, field2] of fields.entries()) {
4189
- if (holdsTail && i === fields.length - 1 && field2.includes(".")) {
4190
- const v4 = parseIpv4(field2);
4191
- if (v4 === null) return null;
4192
- groups.push(Math.floor(v4 / 65536), v4 % 65536);
4193
- } else if (/^[0-9a-f]{1,4}$/i.test(field2)) {
4194
- groups.push(parseInt(field2, 16));
4195
- } else {
4196
- return null;
4197
- }
4198
- }
4199
- return groups;
4200
- }
4201
- function parseIpv6(text) {
4202
- if (!/^[0-9a-f:.]+$/i.test(text)) return null;
4203
- const sides = text.split("::");
4204
- if (sides.length > 2) return null;
4205
- const [head = "", tail] = sides;
4206
- const left = ipv6Groups(head, tail === void 0);
4207
- const right = tail === void 0 ? [] : ipv6Groups(tail, true);
4208
- if (left === null || right === null) return null;
4209
- const explicit = left.length + right.length;
4210
- if (tail === void 0 ? explicit !== 8 : explicit > 7) return null;
4211
- const groups = [...left, ...new Array(8 - explicit).fill(0), ...right];
4212
- return groups.reduce((n, group) => n << 16n | BigInt(group), 0n);
4213
- }
4214
- function ipv4Range(cidr) {
4215
- const [address = "", bits = ""] = cidr.split("/");
4216
- const base = parseIpv4(address);
4217
- if (base === null) throw new Error(`the refused set holds an unparseable range ${cidr}`);
4218
- return { base, bits: Number(bits) };
4219
- }
4220
- function ipv6Range(cidr) {
4221
- const [address = "", bits = ""] = cidr.split("/");
4222
- const base = parseIpv6(address);
4223
- if (base === null) throw new Error(`the refused set holds an unparseable range ${cidr}`);
4224
- return { base, bits: Number(bits) };
4225
- }
4226
- var inIpv4Range = (n, { base, bits }) => Math.floor(n / 2 ** (32 - bits)) === Math.floor(base / 2 ** (32 - bits));
4227
- var inIpv6Range = (n, { base, bits }) => n >> BigInt(128 - bits) === base >> BigInt(128 - bits);
4228
- var REFUSED_IPV4 = [
4229
- "0.0.0.0/8",
4230
- "10.0.0.0/8",
4231
- "100.64.0.0/10",
4232
- "127.0.0.0/8",
4233
- "168.63.129.16/32",
4234
- "169.254.0.0/16",
4235
- "172.16.0.0/12",
4236
- "192.0.0.0/24",
4237
- "192.168.0.0/16",
4238
- "198.18.0.0/15",
4239
- "224.0.0.0/4",
4240
- "240.0.0.0/4"
4241
- ].map(ipv4Range);
4242
- var REFUSED_IPV6 = [
4243
- "::/128",
4244
- "::1/128",
4245
- "fc00::/7",
4246
- "fe80::/10",
4247
- "fec0::/10",
4248
- "ff00::/8",
4249
- "2001::/32",
4250
- "2002::/16",
4251
- "64:ff9b:1::/48"
4252
- ].map(ipv6Range);
4253
- var IPV4_EMBEDDINGS = ["::ffff:0:0/96", "::/96", "64:ff9b::/96"].map(ipv6Range);
4254
- function isPublicAddress(address) {
4255
- const v4 = parseIpv4(address);
4256
- if (v4 !== null) return !REFUSED_IPV4.some((range) => inIpv4Range(v4, range));
4257
- const v6 = parseIpv6(address);
4258
- if (v6 === null) return false;
4259
- if (REFUSED_IPV6.some((range) => inIpv6Range(v6, range))) return false;
4260
- if (IPV4_EMBEDDINGS.some((range) => inIpv6Range(v6, range))) {
4261
- return isPublicAddress(
4262
- [24n, 16n, 8n, 0n].map((shift) => String(v6 >> shift & 0xffn)).join(".")
4263
- );
4264
- }
4265
- return true;
4266
- }
4267
- function isLocalhostName(hostname) {
4268
- const name = (hostname.endsWith(".") ? hostname.slice(0, -1) : hostname).toLowerCase();
4269
- return name === "localhost" || name.endsWith(".localhost");
4270
- }
4271
- function literalReach(hostname) {
4272
- if (hostname.startsWith("[") && hostname.endsWith("]")) {
4273
- return isPublicAddress(hostname.slice(1, -1)) ? "public" : "private";
4274
- }
4275
- if (parseIpv4(hostname) !== null) return isPublicAddress(hostname) ? "public" : "private";
4276
- if (isLocalhostName(hostname)) return "private";
4277
- return null;
4278
- }
4279
- async function nameReach(hostname, lookup2) {
4280
- let answers;
4281
- try {
4282
- answers = await lookup2(hostname, { all: true });
4283
- } catch {
4284
- return null;
4285
- }
4286
- if (answers.length === 0) return null;
4287
- const publicCount = answers.filter(({ address }) => isPublicAddress(address)).length;
4288
- if (publicCount === answers.length) return "public";
4289
- return publicCount === 0 ? "private" : "mixed";
4290
- }
4291
- async function payUrlRefusal(url, options) {
4292
- if (!URL.canParse(url)) return null;
4293
- const { protocol, hostname } = new URL(url);
4294
- if (protocol !== "http:" && protocol !== "https:") return null;
4295
- const allowPrivate = options.allowPrivateHosts;
4296
- const mainnetHttp = options.cluster !== "devnet" && protocol === "http:";
4297
- if (mainnetHttp && !allowPrivate) return "mainnet_http";
4298
- if (allowPrivate && !mainnetHttp) return null;
4299
- const literal = literalReach(hostname);
4300
- if (!allowPrivate && literal === "private") return "private_host";
4301
- const reach = literal ?? await nameReach(hostname, options.lookup);
4302
- if (reach === null) return "unresolved_host";
4303
- if (!allowPrivate) return reach === "public" ? null : "private_host";
4304
- return reach === "private" ? null : "mainnet_http";
4305
- }
4306
- function payAddressRule(options) {
4307
- const publicOnly = (address) => isPublicAddress(address);
4308
- if (!URL.canParse(options.url)) return publicOnly;
4309
- const { protocol } = new URL(options.url);
4310
- if (protocol !== "http:" && protocol !== "https:") return publicOnly;
4311
- if (!options.allowPrivateHosts) return publicOnly;
4312
- if (options.cluster !== "devnet" && protocol === "http:") {
4313
- return (address, target) => target === "spec" || !isPublicAddress(address);
4314
- }
4315
- return void 0;
4316
- }
4317
- var ESCROW_RAIL_SCHEMES = ["on-delivery", "job-escrow"];
4318
- function deadlineBoundedPolicy(terms) {
4319
- const bound = terms.maxDeadlineSeconds;
4320
- if (!Number.isSafeInteger(bound) || bound < 1) {
4321
- throw new EscroError(
4322
- `maxDeadlineSeconds must be a positive whole number of seconds, got ${String(bound)}`,
4323
- "VALIDATION_ERROR"
4324
- );
4325
- }
4326
- const escrowOnly = terms.escrowOnly;
4327
- if (escrowOnly !== void 0 && typeof escrowOnly !== "boolean") {
4328
- throw new EscroError(
4329
- `escrowOnly must be true, false or absent, got ${typeof escrowOnly}`,
4330
- "VALIDATION_ERROR"
4331
- );
4332
- }
4333
- const now = terms.now ?? (() => Date.now());
4334
- const amount = String(terms.amountMicroUsdc);
4335
- const network = terms.cluster === "devnet" ? SOLANA_CAIP2_DEVNET : SOLANA_CAIP2_MAINNET;
4336
- return (accepts) => {
4337
- const reading = now();
4338
- if (typeof reading !== "number" || !Number.isSafeInteger(reading)) {
4339
- throw new EscroError(
4340
- "The pay policy's clock must return whole milliseconds; nothing was signed or funded",
4341
- "VALIDATION_ERROR"
4342
- );
4343
- }
4344
- const latest = Math.floor(reading / 1e3) + bound;
4345
- const onTerms = accepts.filter(
4346
- (entry) => entry.payTo === terms.to && entry.amount === amount && entry.network === network
4347
- );
4348
- const escrowEntries = onTerms.filter((entry) => ESCROW_RAIL_SCHEMES.includes(entry.scheme));
4349
- if (escrowEntries.length > 0) {
4350
- const inBound = escrowEntries.find((entry) => {
4351
- const deadline = entry.extra?.deadline;
4352
- return typeof deadline === "number" && Number.isSafeInteger(deadline) && deadline <= latest;
4353
- });
4354
- if (inBound !== void 0) return inBound;
4355
- throw new EscroPayError(
4356
- "no_eligible_entry",
4357
- `The 402 offers no escrow entry paying this worker this amount with a deadline at or before ${String(latest)} (Unix seconds: now plus ${String(bound)}). Nothing was signed or funded.`,
4358
- { detail: "deadline" }
4359
- );
4360
- }
4361
- if (escrowOnly === true) {
4362
- throw new EscroPayError(
4363
- "no_eligible_entry",
4364
- `The 402 offers no escrow entry paying ${amount} micro-USDC to ${terms.to}. Nothing was signed or funded.`,
4365
- { detail: "escrow_only" }
4366
- );
4367
- }
4368
- const exact = onTerms.find((entry) => entry.scheme === "exact");
4369
- if (exact !== void 0) return exact;
4370
- const [first] = onTerms;
4371
- if (first !== void 0 && onTerms.every((entry) => entry.scheme === "upto")) return first;
4372
- throw new EscroPayError(
4373
- "no_eligible_entry",
4374
- `The 402 offers no entry paying ${amount} micro-USDC to ${terms.to}`
4375
- );
4376
- };
4377
- }
4378
4689
  var U64_MAX = 2n ** 64n - 1n;
4379
4690
  var ED25519_L = 2n ** 252n + 27742317777372353535851937790883648493n;
4380
4691
 
@@ -4397,6 +4708,7 @@ var EscrowState2 = /* @__PURE__ */ ((EscrowState22) => {
4397
4708
  })(EscrowState2 || {});
4398
4709
  var MIN_ESCROW_AMOUNT = 5e6;
4399
4710
  var MAX_DISPUTE_REASON_BYTES = 200;
4711
+ var MAX_PROOF_URI_BYTES = 128;
4400
4712
  var ONCHAIN_REFUND_GRACE_SECONDS3 = 900;
4401
4713
  var ONCHAIN_TIMEOUT_SECONDS3 = 86400;
4402
4714
  var CLOCK_SKEW_SECONDS3 = 60;
@@ -4434,6 +4746,27 @@ var ESCROW_INSTRUCTIONS3 = {
4434
4746
  arbitration_release: spec3([118, 157, 141, 26, 104, 117, 94, 229], 4, "ARBITRATION_RELEASE"),
4435
4747
  arbitration_refund: spec3([255, 194, 84, 248, 185, 249, 120, 122], 4, "ARBITRATION_REFUND")
4436
4748
  };
4749
+ var NON_ESCROW_INSTRUCTIONS3 = {
4750
+ initialize_platform: Uint8Array.from([119, 201, 101, 45, 75, 122, 89, 3]),
4751
+ initialize_admin_config: Uint8Array.from([133, 214, 35, 2, 50, 232, 95, 164]),
4752
+ close_platform: Uint8Array.from([27, 145, 216, 122, 13, 15, 46, 201]),
4753
+ update_platform: Uint8Array.from([46, 78, 138, 189, 47, 163, 120, 85]),
4754
+ set_admin_authority: Uint8Array.from([72, 49, 37, 167, 149, 98, 49, 174]),
4755
+ migrate_escrow_v1_to_v2: Uint8Array.from([70, 76, 99, 21, 154, 50, 111, 221])
4756
+ };
4757
+ var RETIRED_INSTRUCTIONS3 = {
4758
+ claim_open_task: Uint8Array.from([31, 61, 16, 69, 194, 74, 72, 148])
4759
+ };
4760
+ var ANCHOR_IDL_INSTRUCTION_TAG3 = Uint8Array.from([
4761
+ 64,
4762
+ 244,
4763
+ 188,
4764
+ 120,
4765
+ 167,
4766
+ 233,
4767
+ 105,
4768
+ 10
4769
+ ]);
4437
4770
 
4438
4771
  // ../shared/dist/solana.js
4439
4772
  var import_web310 = require("@solana/web3.js");
@@ -4467,8 +4800,17 @@ function refinePublicKey(value, ctx) {
4467
4800
  ctx.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: PUBLIC_KEY_ISSUE });
4468
4801
  }
4469
4802
  var listEscrowsSchema = {
4470
- state: import_zod.z.nativeEnum(EscrowState2).optional().describe("Return only escrows in this lifecycle state"),
4471
- assignedTo: import_zod.z.string().superRefine(refinePublicKey).optional().describe("Base-58 wallet; return only escrows assigned to this worker"),
4803
+ // Two enum instances, not one shared: a schema reused inside one tool's input is advertised as a
4804
+ // `$ref`, which some MCP clients do not resolve.
4805
+ state: import_zod.z.union([import_zod.z.nativeEnum(EscrowState2), import_zod.z.array(import_zod.z.nativeEnum(EscrowState2)).min(1)]).optional().describe(
4806
+ "Return only escrows in this state, or in any state of a non-empty list; CREATED is never served"
4807
+ ),
4808
+ worker: import_zod.z.string().superRefine(refinePublicKey).optional().describe(
4809
+ "Base-58 wallet; return every escrow assigned to this worker, in any served state. Claim a FUNDED escrow assigned to you before doing its work: until the claim the buyer may cancel it and take the deposit back, so work done before the claim can go unpaid."
4810
+ ),
4811
+ assignedTo: import_zod.z.string().superRefine(refinePublicKey).optional().describe(
4812
+ "Base-58 wallet; the legacy form of worker: return only this worker's escrows in FUNDED, IN_PROGRESS or SUBMITTED. Claim a FUNDED escrow assigned to you before doing its work: until the claim the buyer may cancel it and take the deposit back, so work done before the claim can go unpaid."
4813
+ ),
4472
4814
  limit: import_zod.z.number().int().positive().max(100).optional().describe("Page size, 1-100; the API returns 20 when omitted"),
4473
4815
  offset: import_zod.z.number().int().nonnegative().optional().describe("Number of escrows to skip"),
4474
4816
  mine: import_zod.z.boolean().optional().describe("true: only escrows this server's wallet created (it is the buyer)")
@@ -4498,16 +4840,19 @@ var createEscrowSchema = {
4498
4840
  deadlineUnix: import_zod.z.number().int().describe(
4499
4841
  "Unix timestamp (seconds) when the escrow deadline expires. Must be \u2265 now+60s and \u2264 now+30 days."
4500
4842
  ),
4501
- assignedWorker: import_zod.z.string().superRefine(refinePublicKey).describe("Base-58 pubkey of the assigned worker")
4843
+ assignedWorker: import_zod.z.string().superRefine(refinePublicKey).describe("Base-58 pubkey of the assigned worker"),
4844
+ specLink: import_zod.z.string().optional().describe(
4845
+ "An https: link where the buyer serves the TaskSpec, for the worker to read and check against the escrow's spec hash. Public: every escrow read serves it."
4846
+ )
4502
4847
  };
4503
4848
  var claimTaskSchema = {
4504
4849
  address: import_zod.z.string().superRefine(refinePublicKey).describe("Base-58 escrow PDA address")
4505
4850
  };
4506
4851
  var submitDeliverableSchema = {
4507
4852
  address: import_zod.z.string().superRefine(refinePublicKey).describe("Base-58 escrow PDA address"),
4508
- contentHash: import_zod.z.string().describe("SHA-256 hex digest of the deliverable"),
4853
+ contentHash: import_zod.z.string().describe("SHA-256 hex digest of the deliverable; at most 64 bytes, which a hex digest fills"),
4509
4854
  proofUri: import_zod.z.string().optional().describe(
4510
- "Optional URL (ipfs://, ar:// or https://) where the buyer can retrieve the deliverable"
4855
+ `Optional http(s), ipfs or ar URL, at most ${String(MAX_PROOF_URI_BYTES)} UTF-8 bytes, where the buyer can retrieve the deliverable`
4511
4856
  )
4512
4857
  };
4513
4858
  var releasePaymentSchema = {
@@ -4553,6 +4898,7 @@ function makeReadHandlers(api, options = {}) {
4553
4898
  const result = await api.listEscrows({
4554
4899
  ...maker !== void 0 && { maker },
4555
4900
  ...args.state !== void 0 && { state: args.state },
4901
+ ...args.worker !== void 0 && { worker: args.worker },
4556
4902
  ...args.assignedTo !== void 0 && { assignedTo: args.assignedTo },
4557
4903
  ...args.limit !== void 0 && { limit: args.limit },
4558
4904
  ...args.offset !== void 0 && { offset: args.offset }
@@ -4760,7 +5106,8 @@ function makeWriteHandlers(escro, options = {}) {
4760
5106
  taskSpec: args.taskSpec,
4761
5107
  amountUsdc: args.amountUsdc,
4762
5108
  deadlineUnix: args.deadlineUnix,
4763
- assignedWorker: args.assignedWorker
5109
+ assignedWorker: args.assignedWorker,
5110
+ ...args.specLink !== void 0 && { specLink: args.specLink }
4764
5111
  });
4765
5112
  return ok(result);
4766
5113
  } catch (err) {