@monolythium/core-sdk 0.3.9 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  var blake3_js = require('@noble/hashes/blake3.js');
4
+ var sha3_js = require('@noble/hashes/sha3.js');
4
5
  var mlKem_js = require('@noble/post-quantum/ml-kem.js');
5
6
  var chacha_js = require('@noble/ciphers/chacha.js');
6
- var sha3_js = require('@noble/hashes/sha3.js');
7
7
  var utils_js = require('@noble/hashes/utils.js');
8
8
  var mlDsa_js = require('@noble/post-quantum/ml-dsa.js');
9
9
  var bls12381_js = require('@noble/curves/bls12-381.js');
@@ -361,6 +361,10 @@ var PRECOMPILE_ADDRESSES = {
361
361
  ORACLE: "0x0000000000000000000000000000000000001009",
362
362
  /** Distributed delegation primitive — gateable. */
363
363
  DELEGATION: "0x000000000000000000000000000000000000100A",
364
+ /** Operator-fee router — skims an operator surcharge on routed CLOB ops; gateable. */
365
+ OPERATOR_ROUTER: "0x000000000000000000000000000000000000100B",
366
+ /** GPU prover market — gateable, genesis-disabled (foundation milestone flip). */
367
+ PROVER_MARKET: "0x000000000000000000000000000000000000100C",
364
368
  /** One-time emergency-key registry — non-gateable. */
365
369
  EMERGENCY_KEY: "0x0000000000000000000000000000000000001100",
366
370
  /** VRF precompile. */
@@ -390,6 +394,8 @@ var PRECOMPILE_ADDRESSES = {
390
394
  /** Hierarchical name registry — gateable. */
391
395
  NAME_REGISTRY: "0x000000000000000000000000000000000000110E"
392
396
  };
397
+ var OPERATOR_ROUTER_ADDRESS = PRECOMPILE_ADDRESSES.OPERATOR_ROUTER;
398
+ var PROTOCOL_MAX_OPERATOR_FEE_BPS = 100;
393
399
 
394
400
  // src/node-registry.ts
395
401
  var NODE_REGISTRY_CAPABILITIES = {
@@ -401,8 +407,12 @@ var NODE_REGISTRY_CAPABILITIES = {
401
407
  SERVES_LIGHT_CLIENT: 32,
402
408
  SERVES_ORACLE_WRITER: 64,
403
409
  SERVES_BRIDGE_RELAY: 128,
404
- SERVES_PUBLIC_API: 256
410
+ SERVES_PUBLIC_API: 256,
411
+ /** GPU prover — may bid on + serve the GPU prover market (MB-4, bit 9). */
412
+ SERVES_GPU_PROVE: 512
405
413
  };
414
+ var DIVERSITY_SCORE_MAX = 1e4;
415
+ var MULTISIG_ADDRESS_DERIVATION_DOMAIN = "MONO_MULTISIG_BLAKE3_20_V1";
406
416
  var NODE_REGISTRY_CAPABILITY_MASK = 65535;
407
417
  var NODE_REGISTRY_PUBLIC_SERVICE_MASK = NODE_REGISTRY_CAPABILITIES.SERVES_RPC | NODE_REGISTRY_CAPABILITIES.SERVES_INDEXER | NODE_REGISTRY_CAPABILITIES.SERVES_ARCHIVE | NODE_REGISTRY_CAPABILITIES.SERVES_WEBSOCKET | NODE_REGISTRY_CAPABILITIES.SERVES_PUBLIC_API;
408
418
  var SERVICE_PROBE_STATUS = {
@@ -413,8 +423,15 @@ var SERVICE_PROBE_STATUS = {
413
423
  };
414
424
  var NODE_REGISTRY_SELECTORS = {
415
425
  reportServiceProbe: "0xeee31bba",
416
- getServiceProbe: "0x1fcbfbce"
426
+ getServiceProbe: "0x1fcbfbce",
427
+ /** `setNetworkMetadata(bytes32,uint16,bytes3,bytes)` — owner-callable (PF-6). */
428
+ setNetworkMetadata: "0x" + selectorHex("setNetworkMetadata(bytes32,uint16,bytes3,bytes)"),
429
+ /** `getOperatorNetworkMetadata(bytes32)` view (PF-6). */
430
+ getOperatorNetworkMetadata: "0x" + selectorHex("getOperatorNetworkMetadata(bytes32)"),
431
+ /** `getClusterDiversity(uint32)` view (PF-6). */
432
+ getClusterDiversity: "0x" + selectorHex("getClusterDiversity(uint32)")
417
433
  };
434
+ var CLUSTER_FORMED_EVENT_SIG = "ClusterFormed(uint32,uint64,address,bytes)";
418
435
  var NodeRegistryError = class extends Error {
419
436
  constructor(message) {
420
437
  super(message);
@@ -469,6 +486,112 @@ function encodeReportServiceProbeCalldata(args) {
469
486
  )
470
487
  );
471
488
  }
489
+ function nodeHostingClassFromByte(b) {
490
+ if (b === 0) return "bareMetal";
491
+ if (b === 1) return "coLocation";
492
+ return "cloud";
493
+ }
494
+ function nodeHostingClassToByte(c) {
495
+ switch (c) {
496
+ case "bareMetal":
497
+ return 0;
498
+ case "coLocation":
499
+ return 1;
500
+ default:
501
+ return 2;
502
+ }
503
+ }
504
+ function decodeOperatorNetworkMetadata(returnData) {
505
+ const bytes = expectLength2(toBytes(returnData), 5 * 32, "operatorNetworkMetadata");
506
+ return {
507
+ asn: bytes[30] << 8 | bytes[31],
508
+ // bytes3 is left-aligned in the head word.
509
+ geoRegion: bytesToHex(bytes.slice(64, 67)),
510
+ hostingClass: nodeHostingClassFromByte(bytes[95]),
511
+ ipAddressHash: bytesToHex(bytes.slice(96, 128)),
512
+ pcrDigest: bytesToHex(bytes.slice(128, 160))
513
+ };
514
+ }
515
+ function decodeClusterDiversity(returnData) {
516
+ const bytes = expectLength2(toBytes(returnData), 4 * 32, "clusterDiversity");
517
+ const word = (i) => bytes[i * 32 + 30] << 8 | bytes[i * 32 + 31];
518
+ return {
519
+ score: word(0),
520
+ asnVariance: word(1),
521
+ geoVariance: word(2),
522
+ hostingSpread: word(3)
523
+ };
524
+ }
525
+ function decodeClusterFormedEvent(topics, data) {
526
+ if (topics.length !== 3) {
527
+ throw new NodeRegistryError(`ClusterFormed expects 3 topics, got ${topics.length}`);
528
+ }
529
+ const body = toBytes(data);
530
+ if (body.length < 96) {
531
+ throw new NodeRegistryError("ClusterFormed data shorter than head + roster length");
532
+ }
533
+ const clusterIdTopic = expectLength2(toBytes(topics[1]), 32, "clusterId topic");
534
+ const epochTopic = expectLength2(toBytes(topics[2]), 32, "effectiveEpoch topic");
535
+ const clusterId = u32FromWord(clusterIdTopic);
536
+ const effectiveEpoch = u64FromWord(epochTopic);
537
+ const anchorAddress = bytesToHex(body.slice(12, 32));
538
+ const rosterLen = Number(u64FromWord(body.slice(64, 96)));
539
+ const rosterEnd = 96 + rosterLen;
540
+ if (body.length < rosterEnd) {
541
+ throw new NodeRegistryError("ClusterFormed roster payload truncated");
542
+ }
543
+ return {
544
+ clusterId,
545
+ effectiveEpoch,
546
+ anchorAddress,
547
+ operatorRoster: bytesToHex(body.slice(96, rosterEnd))
548
+ };
549
+ }
550
+ function deriveClusterAnchorAddress(roster, threshold) {
551
+ if (!Number.isInteger(threshold) || threshold < 0 || threshold > 65535) {
552
+ throw new NodeRegistryError("threshold must be a uint16");
553
+ }
554
+ const members = roster.map((m, i) => expectLength2(toBytes(m), 48, `roster[${i}]`));
555
+ members.sort(compareBytes);
556
+ const parts = [
557
+ new TextEncoder().encode(MULTISIG_ADDRESS_DERIVATION_DOMAIN),
558
+ Uint8Array.from([threshold >> 8 & 255, threshold & 255])
559
+ ];
560
+ for (const member of members) {
561
+ parts.push(u64BeBytes(BigInt(member.length)));
562
+ parts.push(member);
563
+ }
564
+ return bytesToHex(blake3_js.blake3(concatBytes(...parts)).slice(0, 20));
565
+ }
566
+ function selectorHex(sig) {
567
+ return [...sha3_js.keccak_256(new TextEncoder().encode(sig)).slice(0, 4)].map((b) => b.toString(16).padStart(2, "0")).join("");
568
+ }
569
+ function u32FromWord(word) {
570
+ return (word[28] << 24 | word[29] << 16 | word[30] << 8 | word[31]) >>> 0;
571
+ }
572
+ function u64FromWord(word) {
573
+ let v = 0n;
574
+ for (let i = 24; i < 32; i++) {
575
+ v = v << 8n | BigInt(word[i]);
576
+ }
577
+ return v;
578
+ }
579
+ function u64BeBytes(value) {
580
+ const out = new Uint8Array(8);
581
+ let n = value;
582
+ for (let i = 7; i >= 0; i--) {
583
+ out[i] = Number(n & 0xffn);
584
+ n >>= 8n;
585
+ }
586
+ return out;
587
+ }
588
+ function compareBytes(a, b) {
589
+ const len = Math.min(a.length, b.length);
590
+ for (let i = 0; i < len; i++) {
591
+ if (a[i] !== b[i]) return a[i] - b[i];
592
+ }
593
+ return a.length - b.length;
594
+ }
472
595
  function bitCount(value) {
473
596
  let n = value >>> 0;
474
597
  let count = 0;
@@ -2744,6 +2867,121 @@ var RpcClient = class _RpcClient {
2744
2867
  async lythClusters(page = 0, limit = 25) {
2745
2868
  return normalizeClusterDirectoryPage(await this.call("lyth_clusters", [page, limit]));
2746
2869
  }
2870
+ // --- PF-4 / PF-6 / MB-6 / MB-4 / MB-2 + operator-router read wrappers ----
2871
+ //
2872
+ // Reconciled against the FINAL mono-core RPC surface (master 2eff9fed):
2873
+ // every method name + response shape below matches the chain's `lyth_*`
2874
+ // dispatch + impls exactly (camelCase keys, 0x-hex uint256 amounts,
2875
+ // bech32m addresses). The three indexer-backed methods —
2876
+ // `lyth_oracleSigners`, `lyth_listProofRequests`, `lyth_proverMarketStatus`
2877
+ // — return a graceful `{ status: "indexer_unavailable", … }` envelope
2878
+ // when the node runs without its indexer projection.
2879
+ /** PF-4 — `lyth_getSpendingPolicy`: the §18.8 spending-policy view for a sub-account. */
2880
+ async lythGetSpendingPolicy(subAccount) {
2881
+ return this.call("lyth_getSpendingPolicy", [sdkTypedAddress(subAccount, "user", "subAccount")]);
2882
+ }
2883
+ /** PF-6 — `lyth_getClusterDiversity`: diversity score + asn/geo/hosting breakdown. */
2884
+ async lythGetClusterDiversity(clusterId) {
2885
+ return this.call("lyth_getClusterDiversity", [clusterId]);
2886
+ }
2887
+ /**
2888
+ * PF-6 — `lyth_getOperatorNetworkMetadata`: ASN/geo/hosting-class/IP/PCR
2889
+ * for a peer. `operatorId` is the 32-byte operator/peer id as `0x…` hex
2890
+ * (the form `lyth_operatorInfo` returns).
2891
+ */
2892
+ async lythGetOperatorNetworkMetadata(operatorId) {
2893
+ return this.call("lyth_getOperatorNetworkMetadata", [operatorId]);
2894
+ }
2895
+ /**
2896
+ * MB-6 — `lyth_oracleSigners`: the global oracle writer roster (folded
2897
+ * from `OracleWriterAdded` / `OracleWriterRemoved`). Returns the
2898
+ * `{ status: "indexer_unavailable", writers: [] }` fallback when the
2899
+ * node runs without the oracle writer-roster indexer projection.
2900
+ */
2901
+ async lythOracleSigners() {
2902
+ return this.call("lyth_oracleSigners", []);
2903
+ }
2904
+ /** MB-6 — `lyth_oracleWriters`: the allowed writer set for a feed. */
2905
+ async lythOracleWriters(feedId) {
2906
+ return this.call("lyth_oracleWriters", [feedId]);
2907
+ }
2908
+ /** MB-6 — `lyth_oracleLatestPrice`: the latest finalized median for a feed. */
2909
+ async lythOracleLatestPrice(feedId) {
2910
+ return this.call("lyth_oracleLatestPrice", [feedId]);
2911
+ }
2912
+ /** MB-6 — `lyth_oracleFeedConfig`: a feed's decimals / min-signers / circuit-breaker config. */
2913
+ async lythOracleFeedConfig(feedId) {
2914
+ return this.call("lyth_oracleFeedConfig", [feedId]);
2915
+ }
2916
+ /** MB-4 — `lyth_getProofRequest`: a single GPU prover-market proof request. */
2917
+ async lythGetProofRequest(requestId) {
2918
+ return this.call("lyth_getProofRequest", [requestId]);
2919
+ }
2920
+ /**
2921
+ * MB-4 — `lyth_listProofRequests`: open/recent prover-market proof
2922
+ * requests. Params are `[stateFilter?, limit?]` (the chain's order),
2923
+ * where `stateFilter` is one of `open|assigned|settled|slashed|expired`.
2924
+ * Returns the `{ status: "indexer_unavailable", requests: [] }` fallback
2925
+ * when the node runs without the prover-market indexer projection.
2926
+ */
2927
+ async lythListProofRequests(stateFilter, limit) {
2928
+ const params = [];
2929
+ if (stateFilter != null || limit != null) params.push(stateFilter ?? null);
2930
+ if (limit != null) params.push(limit);
2931
+ return this.call("lyth_listProofRequests", params);
2932
+ }
2933
+ /** MB-4 — `lyth_getProverBids`: the fee bids placed on one proof request. */
2934
+ async lythGetProverBids(requestId) {
2935
+ return this.call("lyth_getProverBids", [requestId]);
2936
+ }
2937
+ /**
2938
+ * MB-4 — `lyth_proverMarketStatus`: prover-market summary. `feeFloor` is
2939
+ * always present (on-chain genesis singleton); the aggregate counts are
2940
+ * `null` on the `{ status: "indexer_unavailable" }` fallback path.
2941
+ */
2942
+ async lythProverMarketStatus() {
2943
+ return this.call("lyth_proverMarketStatus", []);
2944
+ }
2945
+ /**
2946
+ * Operator-router — `lyth_operatorRouterConfig`: the router's static
2947
+ * posture (`0x100B` address, the protocol fee ceiling, and whether the
2948
+ * gateable router precompile is currently milestone-activated).
2949
+ */
2950
+ async lythOperatorRouterConfig() {
2951
+ return this.call("lyth_operatorRouterConfig", []);
2952
+ }
2953
+ /**
2954
+ * Operator-router — `lyth_operatorFeeConfig`: one operator's fee
2955
+ * registration (recipient, fee bps, enabled flag, registered-at block).
2956
+ * `operator` is a `mono` bech32m user address.
2957
+ */
2958
+ async lythOperatorFeeConfig(operator) {
2959
+ return this.call("lyth_operatorFeeConfig", [sdkTypedAddress(operator, "user", "operator")]);
2960
+ }
2961
+ /**
2962
+ * MB-2 — `lyth_bridgeHealth`: a paged set of bridge-record health
2963
+ * envelopes. Each record carries the circuit-breaker posture
2964
+ * (`defaultDrainCapPerWindow`, `defaultDrainWindowBlocks`, `paused`,
2965
+ * `pausedAtBlock`, `resumeCooldownBlocks`). Params are `[cursor?, limit?]`
2966
+ * (the chain pages the global bridge set; there is no single-bridge form).
2967
+ */
2968
+ async lythBridgeHealth(cursor, limit) {
2969
+ const params = [];
2970
+ if (cursor != null || limit != null) params.push(cursor ?? null);
2971
+ if (limit != null) params.push(limit);
2972
+ return this.call("lyth_bridgeHealth", params);
2973
+ }
2974
+ /**
2975
+ * MB-2 — `lyth_bridgeDrainStatus`: the live per-route circuit-breaker
2976
+ * drain bucket for one `(bridgeId, wrappedAsset)` route. `bridgeId` is a
2977
+ * 32-byte `0x…` hex id; `wrappedAsset` is a `mono` bech32m user address.
2978
+ */
2979
+ async lythBridgeDrainStatus(bridgeId, wrappedAsset) {
2980
+ return this.call("lyth_bridgeDrainStatus", [
2981
+ bridgeId,
2982
+ sdkTypedAddress(wrappedAsset, "user", "wrappedAsset")
2983
+ ]);
2984
+ }
2747
2985
  /**
2748
2986
  * `lyth_submitPendingChange` — operator-onboarding transport for the
2749
2987
  * pending-change ledger. Server validates the envelope shape.
@@ -4160,6 +4398,13 @@ function isBridgeCooldownZeroRevert(data) {
4160
4398
  function isBridgeFinalityZeroRevert(data) {
4161
4399
  return bytesToHex4(toBytes2(data)).toLowerCase() === BRIDGE_REVERT_TAGS.bridgeFinalityZero;
4162
4400
  }
4401
+ function bridgeDrainRemaining(capPerWindow, drained) {
4402
+ const cap = BigInt(capPerWindow);
4403
+ if (cap === 0n) return null;
4404
+ const used = BigInt(drained);
4405
+ const left = cap > used ? cap - used : 0n;
4406
+ return left.toString(10);
4407
+ }
4163
4408
  function assessBridgeRoute(route) {
4164
4409
  const blockedReasons = [];
4165
4410
  const warnings = [];
@@ -6387,6 +6632,410 @@ function assertWholeNumber(field2, value) {
6387
6632
  }
6388
6633
  }
6389
6634
 
6635
+ // src/tx-fee.ts
6636
+ var REGISTRY_DEFAULT_EXECUTION_UNIT_LIMIT = 250000n;
6637
+ var TRANSFER_DEFAULT_EXECUTION_UNIT_LIMIT = 100000n;
6638
+ var MIN_EXECUTION_UNIT_PRICE_LYTHOSHI = 2000n;
6639
+ var EXECUTION_UNIT_PRICE_SAFETY_MULTIPLIER = 3n;
6640
+ function asBigint(value, label) {
6641
+ try {
6642
+ return typeof value === "bigint" ? value : BigInt(value);
6643
+ } catch {
6644
+ throw new Error(`${label} is not an integer: ${String(value)}`);
6645
+ }
6646
+ }
6647
+ function clampPriorityTip(priorityTipLythoshi, maxExecutionUnitPriceLythoshi) {
6648
+ const tip = asBigint(priorityTipLythoshi, "priorityTipLythoshi");
6649
+ const cap = asBigint(maxExecutionUnitPriceLythoshi, "maxExecutionUnitPriceLythoshi");
6650
+ if (tip < 0n) throw new Error("priorityTipLythoshi must be non-negative");
6651
+ return tip > cap ? cap : tip;
6652
+ }
6653
+ async function resolveMaxExecutionUnitPrice(client, options = {}) {
6654
+ const floor = options.minPriceLythoshi ?? MIN_EXECUTION_UNIT_PRICE_LYTHOSHI;
6655
+ const multiplier = options.safetyMultiplier ?? EXECUTION_UNIT_PRICE_SAFETY_MULTIPLIER;
6656
+ const quote = await client.lythExecutionUnitPrice();
6657
+ let unitPrice;
6658
+ try {
6659
+ unitPrice = BigInt(quote.executionUnitPriceLythoshi);
6660
+ } catch {
6661
+ throw SdkError.malformed(
6662
+ `lyth_executionUnitPrice returned a non-integer executionUnitPriceLythoshi: ${quote.executionUnitPriceLythoshi}`
6663
+ );
6664
+ }
6665
+ const base = unitPrice > floor ? unitPrice : floor;
6666
+ return base * multiplier;
6667
+ }
6668
+ async function resolveExecutionFee(client, options = {}) {
6669
+ const maxFeePerGas = await resolveMaxExecutionUnitPrice(client, {
6670
+ minPriceLythoshi: options.minPriceLythoshi,
6671
+ safetyMultiplier: options.safetyMultiplier
6672
+ });
6673
+ const tip = options.priorityTipLythoshi === void 0 ? maxFeePerGas : clampPriorityTip(options.priorityTipLythoshi, maxFeePerGas);
6674
+ return {
6675
+ maxFeePerGas,
6676
+ maxPriorityFeePerGas: tip,
6677
+ gasLimit: options.executionUnitLimit ?? TRANSFER_DEFAULT_EXECUTION_UNIT_LIMIT
6678
+ };
6679
+ }
6680
+ async function resolveRegistryExecutionFee(client, options = {}) {
6681
+ return resolveExecutionFee(client, {
6682
+ ...options,
6683
+ executionUnitLimit: options.executionUnitLimit ?? REGISTRY_DEFAULT_EXECUTION_UNIT_LIMIT
6684
+ });
6685
+ }
6686
+ var ORACLE_EVENT_SIGS = {
6687
+ oracleRoundFinalized: "OracleRoundFinalized(bytes32,uint64,uint256,uint64,uint32)",
6688
+ observationSubmitted: "ObservationSubmitted(bytes32,uint64,address,uint256,uint64)",
6689
+ feedAdded: "FeedAdded(bytes32,uint8,uint16,uint32,uint32)",
6690
+ feedUpdated: "FeedUpdated(bytes32,uint8,uint16,uint32,uint32)",
6691
+ oracleFraudSlashed: "OracleFraudSlashed(bytes32,uint64,address,bytes32)",
6692
+ oracleAdminUpdated: "OracleAdminUpdated(address)",
6693
+ oracleWriterAdded: "OracleWriterAdded(address,address)",
6694
+ oracleWriterRemoved: "OracleWriterRemoved(address,address)"
6695
+ };
6696
+ var OracleEventError = class extends Error {
6697
+ constructor(message) {
6698
+ super(message);
6699
+ this.name = "OracleEventError";
6700
+ }
6701
+ };
6702
+ function oracleAddressHex() {
6703
+ return PRECOMPILE_ADDRESSES.ORACLE.toLowerCase();
6704
+ }
6705
+ function decodeOracleEvent(topics, data) {
6706
+ if (topics.length === 0) {
6707
+ throw new OracleEventError("event record has no topics");
6708
+ }
6709
+ const topic0 = bytesToHex6(expectLength4(toBytes3(topics[0]), 32, "topic0"));
6710
+ const body = toBytes3(data);
6711
+ if (topic0 === topicHex(ORACLE_EVENT_SIGS.oracleRoundFinalized)) {
6712
+ checkArity("OracleRoundFinalized", 3, topics.length);
6713
+ checkData("OracleRoundFinalized", 3 * 32, body.length);
6714
+ return {
6715
+ kind: "roundFinalized",
6716
+ feedId: hex32(topics[1]),
6717
+ roundId: u64FromTopic(topics[2]),
6718
+ computedMedian: u256Decimal(body.subarray(0, 32)),
6719
+ finalizedAtBlock: u64FromWord2(body.subarray(32, 64)),
6720
+ observationsLen: u32FromWord2(body.subarray(64, 96))
6721
+ };
6722
+ }
6723
+ if (topic0 === topicHex(ORACLE_EVENT_SIGS.observationSubmitted)) {
6724
+ checkArity("ObservationSubmitted", 4, topics.length);
6725
+ checkData("ObservationSubmitted", 2 * 32, body.length);
6726
+ return {
6727
+ kind: "observationSubmitted",
6728
+ feedId: hex32(topics[1]),
6729
+ roundId: u64FromTopic(topics[2]),
6730
+ writer: addressFromTopic(topics[3]),
6731
+ value: u256Decimal(body.subarray(0, 32)),
6732
+ observedAt: u64FromWord2(body.subarray(32, 64))
6733
+ };
6734
+ }
6735
+ if (topic0 === topicHex(ORACLE_EVENT_SIGS.oracleFraudSlashed)) {
6736
+ checkArity("OracleFraudSlashed", 4, topics.length);
6737
+ checkData("OracleFraudSlashed", 32, body.length);
6738
+ return {
6739
+ kind: "fraudSlashed",
6740
+ feedId: hex32(topics[1]),
6741
+ roundId: u64FromTopic(topics[2]),
6742
+ writer: addressFromTopic(topics[3]),
6743
+ evidenceHash: bytesToHex6(body.subarray(0, 32))
6744
+ };
6745
+ }
6746
+ if (topic0 === topicHex(ORACLE_EVENT_SIGS.feedAdded)) {
6747
+ checkArity("FeedAdded", 2, topics.length);
6748
+ checkData("FeedAdded", 4 * 32, body.length);
6749
+ return { kind: "feedAdded", ...decodeFeedFields(topics[1], body) };
6750
+ }
6751
+ if (topic0 === topicHex(ORACLE_EVENT_SIGS.feedUpdated)) {
6752
+ checkArity("FeedUpdated", 2, topics.length);
6753
+ checkData("FeedUpdated", 4 * 32, body.length);
6754
+ return { kind: "feedUpdated", ...decodeFeedFields(topics[1], body) };
6755
+ }
6756
+ if (topic0 === topicHex(ORACLE_EVENT_SIGS.oracleAdminUpdated)) {
6757
+ checkArity("OracleAdminUpdated", 2, topics.length);
6758
+ checkData("OracleAdminUpdated", 0, body.length);
6759
+ return { kind: "adminUpdated", admin: addressFromTopic(topics[1]) };
6760
+ }
6761
+ if (topic0 === topicHex(ORACLE_EVENT_SIGS.oracleWriterAdded)) {
6762
+ checkArity("OracleWriterAdded", 3, topics.length);
6763
+ checkData("OracleWriterAdded", 0, body.length);
6764
+ return {
6765
+ kind: "writerAdded",
6766
+ admin: addressFromTopic(topics[1]),
6767
+ writer: addressFromTopic(topics[2])
6768
+ };
6769
+ }
6770
+ if (topic0 === topicHex(ORACLE_EVENT_SIGS.oracleWriterRemoved)) {
6771
+ checkArity("OracleWriterRemoved", 3, topics.length);
6772
+ checkData("OracleWriterRemoved", 0, body.length);
6773
+ return {
6774
+ kind: "writerRemoved",
6775
+ admin: addressFromTopic(topics[1]),
6776
+ writer: addressFromTopic(topics[2])
6777
+ };
6778
+ }
6779
+ throw new OracleEventError("unknown oracle event topic0");
6780
+ }
6781
+ function decodeFeedFields(feedTopic, body) {
6782
+ return {
6783
+ feedId: hex32(feedTopic),
6784
+ decimals: body[31],
6785
+ minSigners: body[62] << 8 | body[63],
6786
+ circuitBreakerBps: u32FromWord2(body.subarray(64, 96)),
6787
+ allowedWritersLen: u32FromWord2(body.subarray(96, 128))
6788
+ };
6789
+ }
6790
+ function topicHex(sig) {
6791
+ return bytesToHex6(sha3_js.keccak_256(new TextEncoder().encode(sig)));
6792
+ }
6793
+ function checkArity(event, expected, found) {
6794
+ if (found !== expected) {
6795
+ throw new OracleEventError(`${event} expected ${expected} topics, found ${found}`);
6796
+ }
6797
+ }
6798
+ function checkData(event, expected, found) {
6799
+ if (found !== expected) {
6800
+ throw new OracleEventError(`${event} expected ${expected} data bytes, found ${found}`);
6801
+ }
6802
+ }
6803
+ function hex32(topic) {
6804
+ return bytesToHex6(expectLength4(toBytes3(topic), 32, "feedId topic"));
6805
+ }
6806
+ function addressFromTopic(topic) {
6807
+ return bytesToHex6(expectLength4(toBytes3(topic), 32, "address topic").subarray(12, 32));
6808
+ }
6809
+ function u64FromTopic(topic) {
6810
+ return u64FromWord2(expectLength4(toBytes3(topic), 32, "u64 topic"));
6811
+ }
6812
+ function u64FromWord2(word) {
6813
+ let v = 0n;
6814
+ for (let i = 24; i < 32; i++) v = v << 8n | BigInt(word[i]);
6815
+ return v;
6816
+ }
6817
+ function u32FromWord2(word) {
6818
+ return (word[28] << 24 | word[29] << 16 | word[30] << 8 | word[31]) >>> 0;
6819
+ }
6820
+ function u256Decimal(word) {
6821
+ let v = 0n;
6822
+ for (const b of word) v = v << 8n | BigInt(b);
6823
+ return v.toString(10);
6824
+ }
6825
+ function toBytes3(value) {
6826
+ if (typeof value === "string") return hexToBytes5(value);
6827
+ return value instanceof Uint8Array ? value : Uint8Array.from(value);
6828
+ }
6829
+ function hexToBytes5(hex) {
6830
+ const b = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
6831
+ if (b.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(b)) {
6832
+ throw new OracleEventError("invalid hex bytes");
6833
+ }
6834
+ const out = new Uint8Array(b.length / 2);
6835
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(b.slice(i * 2, i * 2 + 2), 16);
6836
+ return out;
6837
+ }
6838
+ function bytesToHex6(bytes) {
6839
+ return `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
6840
+ }
6841
+ function expectLength4(value, len, name) {
6842
+ if (value.length !== len) {
6843
+ throw new OracleEventError(`${name} must be ${len} bytes, got ${value.length}`);
6844
+ }
6845
+ return value;
6846
+ }
6847
+ var PROVER_MARKET_ADDRESS = PRECOMPILE_ADDRESSES.PROVER_MARKET;
6848
+ var SERVES_GPU_PROVE = 512;
6849
+ var PROVER_MARKET_SELECTORS = {
6850
+ createRequest: "0x" + selectorHex2("createRequest(bytes)"),
6851
+ submitBid: "0x" + selectorHex2("submitBid(bytes)"),
6852
+ closeRequest: "0x" + selectorHex2("closeRequest(bytes)"),
6853
+ submitProof: "0x" + selectorHex2("submitProof(bytes)"),
6854
+ settle: "0x" + selectorHex2("settle(bytes)"),
6855
+ slash: "0x" + selectorHex2("slash(bytes)")
6856
+ };
6857
+ var PROVER_MARKET_EVENT_SIGS = {
6858
+ proofRequested: "ProofRequested(bytes32,address,bytes32,uint128,uint64)",
6859
+ bidSubmitted: "BidSubmitted(bytes32,address,uint128)",
6860
+ requestAssigned: "RequestAssigned(bytes32,address,uint128)",
6861
+ proofSettled: "ProofSettled(bytes32,address,uint128,uint128)",
6862
+ proverSlashed: "ProverSlashed(bytes32,address,uint16,bytes32)",
6863
+ requestExpired: "RequestExpired(bytes32,address,uint128)"
6864
+ };
6865
+ var PROVER_SLASH_REASON_NON_DELIVERY = 1024;
6866
+ var PROVER_SLASH_REASON_BAD_PROOF = 1025;
6867
+ var PROVER_MARKET_REQUEST_DOMAIN = "prover_market.request.v1";
6868
+ var PROVER_MARKET_BID_DOMAIN = "prover_market.bid.v1";
6869
+ var PROVER_MARKET_SUBMIT_DOMAIN = "prover_market.submit.v1";
6870
+ function proverMarketStateFromByte(b) {
6871
+ switch (b) {
6872
+ case 0:
6873
+ return "open";
6874
+ case 1:
6875
+ return "assigned";
6876
+ case 2:
6877
+ return "settled";
6878
+ case 3:
6879
+ return "slashed";
6880
+ case 4:
6881
+ return "expired";
6882
+ default:
6883
+ return null;
6884
+ }
6885
+ }
6886
+ var ProverMarketError = class extends Error {
6887
+ constructor(message) {
6888
+ super(message);
6889
+ this.name = "ProverMarketError";
6890
+ }
6891
+ };
6892
+ function requestSighash(vkeyHash, inputsHash, maxFee, deadline, nonce) {
6893
+ return bytesToHex7(
6894
+ sha3_js.keccak_256(
6895
+ concatBytes5(
6896
+ new TextEncoder().encode(PROVER_MARKET_REQUEST_DOMAIN),
6897
+ expectLength5(toBytes4(vkeyHash), 32, "vkeyHash"),
6898
+ expectLength5(toBytes4(inputsHash), 32, "inputsHash"),
6899
+ u128Bytes(maxFee, "maxFee"),
6900
+ u64Bytes(deadline, "deadline"),
6901
+ u64Bytes(nonce, "nonce")
6902
+ )
6903
+ )
6904
+ );
6905
+ }
6906
+ function bidSighash(requestId, fee) {
6907
+ return bytesToHex7(
6908
+ sha3_js.keccak_256(
6909
+ concatBytes5(
6910
+ new TextEncoder().encode(PROVER_MARKET_BID_DOMAIN),
6911
+ expectLength5(toBytes4(requestId), 32, "requestId"),
6912
+ u128Bytes(fee, "fee")
6913
+ )
6914
+ )
6915
+ );
6916
+ }
6917
+ function submitSighash(requestId, proofHash) {
6918
+ return bytesToHex7(
6919
+ sha3_js.keccak_256(
6920
+ concatBytes5(
6921
+ new TextEncoder().encode(PROVER_MARKET_SUBMIT_DOMAIN),
6922
+ expectLength5(toBytes4(requestId), 32, "requestId"),
6923
+ expectLength5(toBytes4(proofHash), 32, "proofHash")
6924
+ )
6925
+ )
6926
+ );
6927
+ }
6928
+ function encodeCreateRequestCanonical(args) {
6929
+ const buyer = expectLength5(toBytes4(args.buyer), 20, "buyer");
6930
+ const buyerPubkey = toBytes4(args.buyerPubkey);
6931
+ const sig = toBytes4(args.sig);
6932
+ if (buyerPubkey.length === 0 || buyerPubkey.length > 65535) {
6933
+ throw new ProverMarketError("buyerPubkey length out of range (1..=65535)");
6934
+ }
6935
+ if (sig.length === 0 || sig.length > 65535) {
6936
+ throw new ProverMarketError("sig length out of range (1..=65535)");
6937
+ }
6938
+ return bytesToHex7(
6939
+ concatBytes5(
6940
+ buyer,
6941
+ u16Bytes(buyerPubkey.length),
6942
+ buyerPubkey,
6943
+ expectLength5(toBytes4(args.vkeyHash), 32, "vkeyHash"),
6944
+ expectLength5(toBytes4(args.inputsHash), 32, "inputsHash"),
6945
+ u128Bytes(args.maxFee, "maxFee"),
6946
+ u64Bytes(args.deadline, "deadline"),
6947
+ u64Bytes(args.nonce, "nonce"),
6948
+ u16Bytes(sig.length),
6949
+ sig
6950
+ )
6951
+ );
6952
+ }
6953
+ function encodeCreateRequestCalldata(args) {
6954
+ const canonical = toBytes4(encodeCreateRequestCanonical(args));
6955
+ const offset = new Uint8Array(32);
6956
+ offset[31] = 32;
6957
+ const lenWord = new Uint8Array(32);
6958
+ const len = canonical.length;
6959
+ lenWord[28] = len >>> 24 & 255;
6960
+ lenWord[29] = len >>> 16 & 255;
6961
+ lenWord[30] = len >>> 8 & 255;
6962
+ lenWord[31] = len & 255;
6963
+ const pad = (32 - len % 32) % 32;
6964
+ return bytesToHex7(
6965
+ concatBytes5(hexToBytes6(PROVER_MARKET_SELECTORS.createRequest), offset, lenWord, canonical, new Uint8Array(pad))
6966
+ );
6967
+ }
6968
+ function selectorHex2(sig) {
6969
+ return [...sha3_js.keccak_256(new TextEncoder().encode(sig)).slice(0, 4)].map((b) => b.toString(16).padStart(2, "0")).join("");
6970
+ }
6971
+ function toBytes4(value) {
6972
+ if (typeof value === "string") return hexToBytes6(value);
6973
+ return value instanceof Uint8Array ? value : Uint8Array.from(value);
6974
+ }
6975
+ function hexToBytes6(hex) {
6976
+ const b = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
6977
+ if (b.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(b)) {
6978
+ throw new ProverMarketError("invalid hex bytes");
6979
+ }
6980
+ const out = new Uint8Array(b.length / 2);
6981
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(b.slice(i * 2, i * 2 + 2), 16);
6982
+ return out;
6983
+ }
6984
+ function bytesToHex7(bytes) {
6985
+ return `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
6986
+ }
6987
+ function concatBytes5(...parts) {
6988
+ const out = new Uint8Array(parts.reduce((acc, p) => acc + p.length, 0));
6989
+ let offset = 0;
6990
+ for (const part of parts) {
6991
+ out.set(part, offset);
6992
+ offset += part.length;
6993
+ }
6994
+ return out;
6995
+ }
6996
+ function expectLength5(value, len, name) {
6997
+ if (value.length !== len) {
6998
+ throw new ProverMarketError(`${name} must be ${len} bytes, got ${value.length}`);
6999
+ }
7000
+ return value;
7001
+ }
7002
+ function toBigint2(value, name) {
7003
+ let n;
7004
+ if (typeof value === "bigint") n = value;
7005
+ else if (typeof value === "number") {
7006
+ if (!Number.isSafeInteger(value)) throw new ProverMarketError(`${name} must be a safe integer`);
7007
+ n = BigInt(value);
7008
+ } else if (/^(0|[1-9][0-9]*|0x[0-9a-fA-F]+)$/.test(value)) n = BigInt(value);
7009
+ else throw new ProverMarketError(`${name} must be a non-negative integer`);
7010
+ if (n < 0n) throw new ProverMarketError(`${name} must be non-negative`);
7011
+ return n;
7012
+ }
7013
+ function u16Bytes(value) {
7014
+ if (!Number.isInteger(value) || value < 0 || value > 65535) {
7015
+ throw new ProverMarketError("u16 value out of range");
7016
+ }
7017
+ return Uint8Array.from([value >> 8 & 255, value & 255]);
7018
+ }
7019
+ function u64Bytes(value, name) {
7020
+ const n = toBigint2(value, name);
7021
+ if (n > 0xffffffffffffffffn) throw new ProverMarketError(`${name} exceeds uint64`);
7022
+ return bigintBytes(n, 8);
7023
+ }
7024
+ function u128Bytes(value, name) {
7025
+ const n = toBigint2(value, name);
7026
+ if (n > (1n << 128n) - 1n) throw new ProverMarketError(`${name} exceeds uint128`);
7027
+ return bigintBytes(n, 16);
7028
+ }
7029
+ function bigintBytes(value, len) {
7030
+ const out = new Uint8Array(len);
7031
+ let n = value;
7032
+ for (let i = len - 1; i >= 0; i--) {
7033
+ out[i] = Number(n & 0xffn);
7034
+ n >>= 8n;
7035
+ }
7036
+ return out;
7037
+ }
7038
+
6390
7039
  // src/delegation.ts
6391
7040
  var DELEGATION_SELECTORS = {
6392
7041
  delegate: "0x662337de",
@@ -6412,34 +7061,34 @@ function delegationAddressHex() {
6412
7061
  return PRECOMPILE_ADDRESSES.DELEGATION.toLowerCase();
6413
7062
  }
6414
7063
  function encodeCompleteRedemptionCalldata(index) {
6415
- return bytesToHex6(
6416
- concatBytes5(
6417
- hexToBytes5(DELEGATION_SELECTORS.completeRedemption),
7064
+ return bytesToHex8(
7065
+ concatBytes6(
7066
+ hexToBytes7(DELEGATION_SELECTORS.completeRedemption),
6418
7067
  uint64Word2(index, "index")
6419
7068
  )
6420
7069
  );
6421
7070
  }
6422
7071
  function encodeDelegateCalldata(cluster, weightBps) {
6423
- return bytesToHex6(
6424
- concatBytes5(
6425
- hexToBytes5(DELEGATION_SELECTORS.delegate),
7072
+ return bytesToHex8(
7073
+ concatBytes6(
7074
+ hexToBytes7(DELEGATION_SELECTORS.delegate),
6426
7075
  uint32Word2(cluster, "cluster"),
6427
7076
  uint16Word(weightBps, "weightBps")
6428
7077
  )
6429
7078
  );
6430
7079
  }
6431
7080
  function encodeUndelegateCalldata(cluster) {
6432
- return bytesToHex6(
6433
- concatBytes5(
6434
- hexToBytes5(DELEGATION_SELECTORS.undelegate),
7081
+ return bytesToHex8(
7082
+ concatBytes6(
7083
+ hexToBytes7(DELEGATION_SELECTORS.undelegate),
6435
7084
  uint32Word2(cluster, "cluster")
6436
7085
  )
6437
7086
  );
6438
7087
  }
6439
7088
  function encodeRedelegateCalldata(fromCluster, toCluster, weightBps) {
6440
- return bytesToHex6(
6441
- concatBytes5(
6442
- hexToBytes5(DELEGATION_SELECTORS.redelegate),
7089
+ return bytesToHex8(
7090
+ concatBytes6(
7091
+ hexToBytes7(DELEGATION_SELECTORS.redelegate),
6443
7092
  uint32Word2(fromCluster, "fromCluster"),
6444
7093
  uint32Word2(toCluster, "toCluster"),
6445
7094
  uint16Word(weightBps, "weightBps")
@@ -6452,15 +7101,15 @@ function encodeClaimCalldata() {
6452
7101
  function encodeSetAutoCompoundCalldata(enabled) {
6453
7102
  const flag = new Uint8Array(32);
6454
7103
  flag[31] = enabled ? 1 : 0;
6455
- return bytesToHex6(
6456
- concatBytes5(hexToBytes5(DELEGATION_SELECTORS.setAutoCompound), flag)
7104
+ return bytesToHex8(
7105
+ concatBytes6(hexToBytes7(DELEGATION_SELECTORS.setAutoCompound), flag)
6457
7106
  );
6458
7107
  }
6459
7108
  function isRedemptionPrincipalUnavailableRevert(data) {
6460
- return bytesToHex6(toBytes3(data)).toLowerCase() === DELEGATION_REVERT_TAGS.redemptionPrincipalUnavailable;
7109
+ return bytesToHex8(toBytes5(data)).toLowerCase() === DELEGATION_REVERT_TAGS.redemptionPrincipalUnavailable;
6461
7110
  }
6462
7111
  function uint64Word2(value, name) {
6463
- const n = toBigint2(value, name);
7112
+ const n = toBigint3(value, name);
6464
7113
  if (n < 0n || n > 0xffffffffffffffffn) {
6465
7114
  throw new DelegationPrecompileError(`${name} must fit uint64`);
6466
7115
  }
@@ -6473,7 +7122,7 @@ function uint64Word2(value, name) {
6473
7122
  return out;
6474
7123
  }
6475
7124
  function uint32Word2(value, name) {
6476
- const n = toBigint2(value, name);
7125
+ const n = toBigint3(value, name);
6477
7126
  if (n < 0n || n > 0xffffffffn) {
6478
7127
  throw new DelegationPrecompileError(`${name} must fit uint32`);
6479
7128
  }
@@ -6486,7 +7135,7 @@ function uint32Word2(value, name) {
6486
7135
  return out;
6487
7136
  }
6488
7137
  function uint16Word(value, name) {
6489
- const n = toBigint2(value, name);
7138
+ const n = toBigint3(value, name);
6490
7139
  if (n < 0n || n > 0xffffn) {
6491
7140
  throw new DelegationPrecompileError(`${name} must fit uint16`);
6492
7141
  }
@@ -6498,7 +7147,7 @@ function uint16Word(value, name) {
6498
7147
  }
6499
7148
  return out;
6500
7149
  }
6501
- function toBigint2(value, name) {
7150
+ function toBigint3(value, name) {
6502
7151
  if (typeof value === "bigint") return value;
6503
7152
  if (typeof value === "number") {
6504
7153
  if (!Number.isInteger(value) || !Number.isSafeInteger(value)) {
@@ -6511,13 +7160,13 @@ function toBigint2(value, name) {
6511
7160
  }
6512
7161
  return BigInt(value);
6513
7162
  }
6514
- function toBytes3(value) {
7163
+ function toBytes5(value) {
6515
7164
  if (typeof value === "string") {
6516
- return hexToBytes5(value);
7165
+ return hexToBytes7(value);
6517
7166
  }
6518
7167
  return value instanceof Uint8Array ? value : Uint8Array.from(value);
6519
7168
  }
6520
- function hexToBytes5(hex) {
7169
+ function hexToBytes7(hex) {
6521
7170
  const body = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
6522
7171
  if (body.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(body)) {
6523
7172
  throw new DelegationPrecompileError("invalid hex bytes");
@@ -6528,10 +7177,10 @@ function hexToBytes5(hex) {
6528
7177
  }
6529
7178
  return out;
6530
7179
  }
6531
- function bytesToHex6(bytes) {
7180
+ function bytesToHex8(bytes) {
6532
7181
  return `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
6533
7182
  }
6534
- function concatBytes5(...parts) {
7183
+ function concatBytes6(...parts) {
6535
7184
  const out = new Uint8Array(parts.reduce((acc, p) => acc + p.length, 0));
6536
7185
  let offset = 0;
6537
7186
  for (const part of parts) {
@@ -6546,9 +7195,11 @@ var SET_POLICY_CLAIM_DOMAIN_TAG = "lyth.spending-policy.claim.v1";
6546
7195
  var ML_DSA_65_PUBLIC_KEY_LEN2 = 1952;
6547
7196
  var ML_DSA_65_SIGNATURE_LEN2 = 3309;
6548
7197
  var SPENDING_POLICY_SELECTORS = {
6549
- setPolicy: "0xd6a518b2",
6550
- setPolicyClaim: "0x08d78f9c",
6551
- claimPolicyByAddress: "0xc2397fe9",
7198
+ // WP §18.8 widened the setPolicy* sighash strings to 11 words, so their
7199
+ // selectors changed; enable/disable/recordSpend are unchanged.
7200
+ setPolicy: "0x8da1a765",
7201
+ setPolicyClaim: "0x35531f6c",
7202
+ claimPolicyByAddress: "0x0c21376c",
6552
7203
  enable: "0x5bfa1b68",
6553
7204
  disable: "0xe6c09edf",
6554
7205
  recordSpend: "0xdca04292"
@@ -6565,7 +7216,7 @@ function spendingPolicyAddressHex() {
6565
7216
  function composeClaimBoundMessage(chainId, args, opts) {
6566
7217
  const precompileAddress = toRawAddressBytes(opts?.precompileAddress ?? PRECOMPILE_ADDRESSES.SPENDING_POLICY);
6567
7218
  const normalized = normalizeArgs(args);
6568
- return concatBytes6(
7219
+ return concatBytes7(
6569
7220
  new TextEncoder().encode(SET_POLICY_CLAIM_DOMAIN_TAG),
6570
7221
  uint64Bytes(chainId, "chainId"),
6571
7222
  precompileAddress,
@@ -6575,22 +7226,30 @@ function composeClaimBoundMessage(chainId, args, opts) {
6575
7226
  uint128Bytes(normalized.perTxCapLythoshi, "perTxCapLythoshi"),
6576
7227
  normalized.allowRoot,
6577
7228
  normalized.denyRoot,
7229
+ // WP §18.8 dimensions, in wire order: weekly cap (be16), monthly cap
7230
+ // (be16), category allow-root (32), packed time window (32),
7231
+ // policy expiry (be8). These slot in before the expected-version word.
7232
+ uint128Bytes(normalized.weeklyCapLythoshi, "weeklyCapLythoshi"),
7233
+ uint128Bytes(normalized.monthlyCapLythoshi, "monthlyCapLythoshi"),
7234
+ normalized.categoryAllowRoot,
7235
+ normalized.timeWindow,
7236
+ uint64Bytes(normalized.policyExpiry, "policyExpiry"),
6578
7237
  uint64Bytes(opts?.expectedPolicyVersion ?? 0n, "expectedPolicyVersion")
6579
7238
  );
6580
7239
  }
6581
7240
  function encodeSetPolicyCalldata(args) {
6582
7241
  const normalized = normalizeArgs(args);
6583
- return bytesToHex7(
6584
- concatBytes6(
6585
- hexToBytes6(SPENDING_POLICY_SELECTORS.setPolicy),
7242
+ return bytesToHex9(
7243
+ concatBytes7(
7244
+ hexToBytes8(SPENDING_POLICY_SELECTORS.setPolicy),
6586
7245
  encodePolicyWords(normalized)
6587
7246
  )
6588
7247
  );
6589
7248
  }
6590
7249
  function encodeSetPolicyClaimCalldata(args, subAccountPubkey, subAccountSig) {
6591
7250
  const normalized = normalizeArgs(args);
6592
- const pubkey = toBytes4(subAccountPubkey);
6593
- const sig = toBytes4(subAccountSig);
7251
+ const pubkey = toBytes6(subAccountPubkey);
7252
+ const sig = toBytes6(subAccountSig);
6594
7253
  if (pubkey.length !== ML_DSA_65_PUBLIC_KEY_LEN2) {
6595
7254
  throw new SpendingPolicyError(
6596
7255
  `subAccountPubkey must be ${ML_DSA_65_PUBLIC_KEY_LEN2} bytes, got ${pubkey.length}`
@@ -6601,9 +7260,9 @@ function encodeSetPolicyClaimCalldata(args, subAccountPubkey, subAccountSig) {
6601
7260
  `subAccountSig must be ${ML_DSA_65_SIGNATURE_LEN2} bytes, got ${sig.length}`
6602
7261
  );
6603
7262
  }
6604
- return bytesToHex7(
6605
- concatBytes6(
6606
- hexToBytes6(SPENDING_POLICY_SELECTORS.setPolicyClaim),
7263
+ return bytesToHex9(
7264
+ concatBytes7(
7265
+ hexToBytes8(SPENDING_POLICY_SELECTORS.setPolicyClaim),
6607
7266
  encodePolicyWords(normalized),
6608
7267
  pubkey,
6609
7268
  sig
@@ -6612,15 +7271,15 @@ function encodeSetPolicyClaimCalldata(args, subAccountPubkey, subAccountSig) {
6612
7271
  }
6613
7272
  function encodeClaimPolicyByAddressCalldata(args, subAccountSig) {
6614
7273
  const normalized = normalizeArgs(args);
6615
- const sig = toBytes4(subAccountSig);
7274
+ const sig = toBytes6(subAccountSig);
6616
7275
  if (sig.length !== ML_DSA_65_SIGNATURE_LEN2) {
6617
7276
  throw new SpendingPolicyError(
6618
7277
  `subAccountSig must be ${ML_DSA_65_SIGNATURE_LEN2} bytes, got ${sig.length}`
6619
7278
  );
6620
7279
  }
6621
- return bytesToHex7(
6622
- concatBytes6(
6623
- hexToBytes6(SPENDING_POLICY_SELECTORS.claimPolicyByAddress),
7280
+ return bytesToHex9(
7281
+ concatBytes7(
7282
+ hexToBytes8(SPENDING_POLICY_SELECTORS.claimPolicyByAddress),
6624
7283
  encodePolicyWords(normalized),
6625
7284
  sig
6626
7285
  )
@@ -6632,34 +7291,70 @@ function encodeEnableCalldata(subAccount) {
6632
7291
  function encodeDisableCalldata(subAccount) {
6633
7292
  return encodeSingleAddressCall(SPENDING_POLICY_SELECTORS.disable, subAccount, "subAccount");
6634
7293
  }
7294
+ var ZERO_WORD = new Uint8Array(32);
6635
7295
  function normalizeArgs(args) {
6636
7296
  return {
6637
7297
  subAccount: toUserAddressBytes(args.subAccount, "subAccount"),
6638
7298
  principal: toUserAddressBytes(args.principal, "principal"),
6639
- dailyCapLythoshi: toBigint3(args.dailyCapLythoshi, "dailyCapLythoshi"),
6640
- perTxCapLythoshi: toBigint3(args.perTxCapLythoshi, "perTxCapLythoshi"),
6641
- allowRoot: expectLength4(toBytes4(args.allowRoot), 32, "allowRoot"),
6642
- denyRoot: expectLength4(toBytes4(args.denyRoot), 32, "denyRoot")
7299
+ dailyCapLythoshi: toBigint4(args.dailyCapLythoshi, "dailyCapLythoshi"),
7300
+ perTxCapLythoshi: toBigint4(args.perTxCapLythoshi, "perTxCapLythoshi"),
7301
+ allowRoot: expectLength6(toBytes6(args.allowRoot), 32, "allowRoot"),
7302
+ denyRoot: expectLength6(toBytes6(args.denyRoot), 32, "denyRoot"),
7303
+ weeklyCapLythoshi: toBigint4(args.weeklyCapLythoshi ?? 0n, "weeklyCapLythoshi"),
7304
+ monthlyCapLythoshi: toBigint4(args.monthlyCapLythoshi ?? 0n, "monthlyCapLythoshi"),
7305
+ categoryAllowRoot: args.categoryAllowRoot == null ? ZERO_WORD : expectLength6(toBytes6(args.categoryAllowRoot), 32, "categoryAllowRoot"),
7306
+ timeWindow: args.timeWindow == null ? ZERO_WORD : expectLength6(toBytes6(args.timeWindow), 32, "timeWindow"),
7307
+ policyExpiry: toBigint4(args.policyExpiry ?? 0n, "policyExpiry")
6643
7308
  };
6644
7309
  }
6645
7310
  function encodePolicyWords(args) {
6646
- return concatBytes6(
7311
+ return concatBytes7(
6647
7312
  encodeAddressWord(args.subAccount),
6648
7313
  encodeAddressWord(args.principal),
6649
7314
  encodeUint128Word(args.dailyCapLythoshi),
6650
7315
  encodeUint128Word(args.perTxCapLythoshi),
6651
7316
  args.allowRoot,
6652
- args.denyRoot
7317
+ args.denyRoot,
7318
+ // WP §18.8 trailing 5 words: weekly cap, monthly cap, category
7319
+ // allow-root, packed time window, policy expiry.
7320
+ encodeUint128Word(args.weeklyCapLythoshi),
7321
+ encodeUint128Word(args.monthlyCapLythoshi),
7322
+ args.categoryAllowRoot,
7323
+ args.timeWindow,
7324
+ encodeUint64Word(args.policyExpiry)
6653
7325
  );
6654
7326
  }
7327
+ function packTimeWindow(enabled, startHour, endHour) {
7328
+ const out = new Uint8Array(32);
7329
+ if (!enabled) return out;
7330
+ out[29] = 1;
7331
+ out[30] = clampHour(startHour);
7332
+ out[31] = clampHour(endHour);
7333
+ return out;
7334
+ }
7335
+ function decodeTimeWindow(word) {
7336
+ const bytes = expectLength6(toBytes6(word), 32, "timeWindow");
7337
+ if (bytes.every((b) => b === 0)) return null;
7338
+ if (bytes[29] === 0) return null;
7339
+ return [Math.min(bytes[30], 23), Math.min(bytes[31], 23)];
7340
+ }
7341
+ function clampHour(hour) {
7342
+ if (!Number.isInteger(hour) || hour < 0) {
7343
+ throw new SpendingPolicyError("time-window hour must be a non-negative integer");
7344
+ }
7345
+ return Math.min(hour, 23);
7346
+ }
7347
+ function encodeUint64Word(value) {
7348
+ return concatBytes7(new Uint8Array(24), uint64Bytes(value, "policyExpiry"));
7349
+ }
6655
7350
  function encodeSingleAddressCall(selector, address, name) {
6656
- return bytesToHex7(concatBytes6(hexToBytes6(selector), encodeAddressWord(toUserAddressBytes(address, name))));
7351
+ return bytesToHex9(concatBytes7(hexToBytes8(selector), encodeAddressWord(toUserAddressBytes(address, name))));
6657
7352
  }
6658
7353
  function encodeAddressWord(address) {
6659
- return concatBytes6(new Uint8Array(12), address);
7354
+ return concatBytes7(new Uint8Array(12), address);
6660
7355
  }
6661
7356
  function encodeUint128Word(value) {
6662
- return concatBytes6(new Uint8Array(16), uint128Bytes(value, "uint128"));
7357
+ return concatBytes7(new Uint8Array(16), uint128Bytes(value, "uint128"));
6663
7358
  }
6664
7359
  function toUserAddressBytes(value, name) {
6665
7360
  if (typeof value !== "string") {
@@ -6679,15 +7374,15 @@ function toRawAddressBytes(value) {
6679
7374
  if (typeof value === "string") {
6680
7375
  return hexToAddressBytes(value);
6681
7376
  }
6682
- return expectLength4(value instanceof Uint8Array ? value : Uint8Array.from(value), 20, "address");
7377
+ return expectLength6(value instanceof Uint8Array ? value : Uint8Array.from(value), 20, "address");
6683
7378
  }
6684
- function toBytes4(value) {
7379
+ function toBytes6(value) {
6685
7380
  if (typeof value === "string") {
6686
- return hexToBytes6(value);
7381
+ return hexToBytes8(value);
6687
7382
  }
6688
7383
  return value instanceof Uint8Array ? value : Uint8Array.from(value);
6689
7384
  }
6690
- function hexToBytes6(hex) {
7385
+ function hexToBytes8(hex) {
6691
7386
  const body = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
6692
7387
  if (body.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(body)) {
6693
7388
  throw new SpendingPolicyError("invalid hex bytes");
@@ -6698,10 +7393,10 @@ function hexToBytes6(hex) {
6698
7393
  }
6699
7394
  return out;
6700
7395
  }
6701
- function bytesToHex7(bytes) {
7396
+ function bytesToHex9(bytes) {
6702
7397
  return `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
6703
7398
  }
6704
- function concatBytes6(...parts) {
7399
+ function concatBytes7(...parts) {
6705
7400
  const out = new Uint8Array(parts.reduce((acc, p) => acc + p.length, 0));
6706
7401
  let offset = 0;
6707
7402
  for (const part of parts) {
@@ -6710,13 +7405,13 @@ function concatBytes6(...parts) {
6710
7405
  }
6711
7406
  return out;
6712
7407
  }
6713
- function expectLength4(value, len, name) {
7408
+ function expectLength6(value, len, name) {
6714
7409
  if (value.length !== len) {
6715
7410
  throw new SpendingPolicyError(`${name} must be ${len} bytes`);
6716
7411
  }
6717
7412
  return value;
6718
7413
  }
6719
- function toBigint3(value, name) {
7414
+ function toBigint4(value, name) {
6720
7415
  const n = typeof value === "bigint" ? value : BigInt(value);
6721
7416
  if (n < 0n) {
6722
7417
  throw new SpendingPolicyError(`${name} must be non-negative`);
@@ -6724,19 +7419,19 @@ function toBigint3(value, name) {
6724
7419
  return n;
6725
7420
  }
6726
7421
  function uint64Bytes(value, name) {
6727
- const n = toBigint3(value, name);
7422
+ const n = toBigint4(value, name);
6728
7423
  if (n > 0xffffffffffffffffn) {
6729
7424
  throw new SpendingPolicyError(`${name} exceeds uint64`);
6730
7425
  }
6731
- return bigintBytes(n, 8);
7426
+ return bigintBytes2(n, 8);
6732
7427
  }
6733
7428
  function uint128Bytes(value, name) {
6734
7429
  if (value > 0xffffffffffffffffffffffffffffffffn) {
6735
7430
  throw new SpendingPolicyError(`${name} exceeds uint128`);
6736
7431
  }
6737
- return bigintBytes(value, 16);
7432
+ return bigintBytes2(value, 16);
6738
7433
  }
6739
- function bigintBytes(value, len) {
7434
+ function bigintBytes2(value, len) {
6740
7435
  const out = new Uint8Array(len);
6741
7436
  let n = value;
6742
7437
  for (let i = len - 1; i >= 0; i--) {
@@ -6763,15 +7458,15 @@ function pubkeyRegistryAddressHex() {
6763
7458
  return PRECOMPILE_ADDRESSES.PUBKEY_REGISTRY.toLowerCase();
6764
7459
  }
6765
7460
  function encodeRegisterPubkeyCalldata(pubkey) {
6766
- const bytes = toBytes5(pubkey);
7461
+ const bytes = toBytes7(pubkey);
6767
7462
  if (bytes.length !== PUBKEY_REGISTRY_ML_DSA_65_PUBLIC_KEY_LEN) {
6768
7463
  throw new PubkeyRegistryError(
6769
7464
  `pubkey must be ${PUBKEY_REGISTRY_ML_DSA_65_PUBLIC_KEY_LEN} bytes, got ${bytes.length}`
6770
7465
  );
6771
7466
  }
6772
- return bytesToHex8(
6773
- concatBytes7(
6774
- hexToBytes7(PUBKEY_REGISTRY_SELECTORS.registerPubkey),
7467
+ return bytesToHex10(
7468
+ concatBytes8(
7469
+ hexToBytes9(PUBKEY_REGISTRY_SELECTORS.registerPubkey),
6775
7470
  uint256Word(32n),
6776
7471
  uint256Word(BigInt(bytes.length)),
6777
7472
  bytes
@@ -6785,7 +7480,7 @@ function encodeHasPubkeyCalldata(address) {
6785
7480
  return encodeSingleAddressCall2(PUBKEY_REGISTRY_SELECTORS.hasPubkey, address);
6786
7481
  }
6787
7482
  function decodeLookupPubkeyReturn(data) {
6788
- const bytes = toBytes5(data);
7483
+ const bytes = toBytes7(data);
6789
7484
  if (bytes.length < 96) {
6790
7485
  throw new PubkeyRegistryError("lookup return must be at least 96 bytes");
6791
7486
  }
@@ -6810,7 +7505,7 @@ function decodeLookupPubkeyReturn(data) {
6810
7505
  };
6811
7506
  }
6812
7507
  function decodeHasPubkeyReturn(data) {
6813
- const bytes = toBytes5(data);
7508
+ const bytes = toBytes7(data);
6814
7509
  if (bytes.length !== 32) {
6815
7510
  throw new PubkeyRegistryError("hasPubkey return must be 32 bytes");
6816
7511
  }
@@ -6824,10 +7519,10 @@ function decodeHasPubkeyReturn(data) {
6824
7519
  throw new PubkeyRegistryError("hasPubkey bool must be 0 or 1");
6825
7520
  }
6826
7521
  function encodeSingleAddressCall2(selector, address) {
6827
- return bytesToHex8(concatBytes7(hexToBytes7(selector), addressWord(toAddressBytes(address))));
7522
+ return bytesToHex10(concatBytes8(hexToBytes9(selector), addressWord(toAddressBytes(address))));
6828
7523
  }
6829
7524
  function addressWord(address) {
6830
- return concatBytes7(new Uint8Array(12), address);
7525
+ return concatBytes8(new Uint8Array(12), address);
6831
7526
  }
6832
7527
  function toAddressBytes(value) {
6833
7528
  if (typeof value !== "string") {
@@ -6843,13 +7538,13 @@ function toAddressBytes(value) {
6843
7538
  throw new PubkeyRegistryError(`address must be a typed mono bech32m address${detail}`);
6844
7539
  }
6845
7540
  }
6846
- function toBytes5(value) {
7541
+ function toBytes7(value) {
6847
7542
  if (typeof value === "string") {
6848
- return hexToBytes7(value);
7543
+ return hexToBytes9(value);
6849
7544
  }
6850
7545
  return value instanceof Uint8Array ? value : Uint8Array.from(value);
6851
7546
  }
6852
- function hexToBytes7(hex) {
7547
+ function hexToBytes9(hex) {
6853
7548
  const body = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
6854
7549
  if (body.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(body)) {
6855
7550
  throw new PubkeyRegistryError("invalid hex bytes");
@@ -6860,10 +7555,10 @@ function hexToBytes7(hex) {
6860
7555
  }
6861
7556
  return out;
6862
7557
  }
6863
- function bytesToHex8(bytes) {
7558
+ function bytesToHex10(bytes) {
6864
7559
  return `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
6865
7560
  }
6866
- function concatBytes7(...parts) {
7561
+ function concatBytes8(...parts) {
6867
7562
  const out = new Uint8Array(parts.reduce((acc, p) => acc + p.length, 0));
6868
7563
  let offset = 0;
6869
7564
  for (const part of parts) {
@@ -6932,6 +7627,39 @@ var CLOB_SELECTORS = {
6932
7627
  /** `setLotSize(bytes32,bytes32,uint256)` — foundation-authorized per-market grid tune. */
6933
7628
  setLotSize: "0x9909be80"
6934
7629
  };
7630
+ var OPERATOR_ROUTER_SIGS = {
7631
+ /** `registerOperator(address recipient, uint16 feeBps)`. */
7632
+ registerOperator: "registerOperator(address,uint16)",
7633
+ /** `updateOperator(address recipient, uint16 feeBps)`. */
7634
+ updateOperator: "updateOperator(address,uint16)",
7635
+ /** `disableOperator(address operator)` — foundation-authorized. */
7636
+ disableOperator: "disableOperator(address)",
7637
+ /**
7638
+ * `placeLimitOrderVia(address operator, bytes32 base, bytes32 quote,
7639
+ * uint8 side, uint256 price, uint256 amount, uint64 expiresAtBlock)`
7640
+ * → `bytes32 orderId`.
7641
+ *
7642
+ * Skims the operator fee (quote token, `user -> recipient`) then
7643
+ * re-enters the CLOB `placeLimitOrder` op with `caller = user`, so the
7644
+ * resting order is owned + escrowed + cancellable by the user,
7645
+ * identical to a direct CLOB placement.
7646
+ */
7647
+ placeLimitOrderVia: "placeLimitOrderVia(address,bytes32,bytes32,uint8,uint256,uint256,uint64)"
7648
+ };
7649
+ var OPERATOR_ROUTER_SELECTORS = {
7650
+ registerOperator: operatorRouterSelectorHex(OPERATOR_ROUTER_SIGS.registerOperator),
7651
+ updateOperator: operatorRouterSelectorHex(OPERATOR_ROUTER_SIGS.updateOperator),
7652
+ disableOperator: operatorRouterSelectorHex(OPERATOR_ROUTER_SIGS.disableOperator),
7653
+ placeLimitOrderVia: operatorRouterSelectorHex(OPERATOR_ROUTER_SIGS.placeLimitOrderVia)
7654
+ };
7655
+ var OPERATOR_ROUTER_EVENT_SIGS = {
7656
+ operatorFeeCharged: "OperatorFeeCharged(address,address,bytes32,address,bytes32,uint256,bytes32)",
7657
+ operatorRegistered: "OperatorRegistered(address,address,uint16)",
7658
+ operatorUpdated: "OperatorUpdated(address,address,uint16,bool)"
7659
+ };
7660
+ function operatorRouterSelectorHex(sig) {
7661
+ return "0x" + [...sha3_js.keccak_256(new TextEncoder().encode(sig)).slice(0, 4)].map((b) => b.toString(16).padStart(2, "0")).join("");
7662
+ }
6935
7663
  var MarketActionError = class extends Error {
6936
7664
  constructor(message) {
6937
7665
  super(message);
@@ -7310,6 +8038,92 @@ function buildCancelSpotOrderPlan(args) {
7310
8038
  mempoolClass: MempoolClass.CLOBOp
7311
8039
  };
7312
8040
  }
8041
+ function encodePlaceLimitOrderViaCalldata(args) {
8042
+ const operator = normalizeNativeMarketAddress(args.operator, "operator");
8043
+ if (operator.kind !== "user") {
8044
+ throw new MarketActionError("operator must be a 'mono' user address");
8045
+ }
8046
+ const side = normalizeSide(args.side);
8047
+ const price = positiveDecimal(args.price, "price");
8048
+ const amount = positiveDecimal(args.amount, "amount");
8049
+ const expiresAtBlock = uint64(args.expiresAtBlock ?? 0n, "expiresAtBlock");
8050
+ return bytesToHex2(
8051
+ concatBytes2(
8052
+ hexToBytes2(OPERATOR_ROUTER_SELECTORS.placeLimitOrderVia, "placeLimitOrderVia selector"),
8053
+ addressWord2(operator.bytes),
8054
+ bytes32FromHex(args.base, "base"),
8055
+ bytes32FromHex(args.quote, "quote"),
8056
+ uint8Word2(side),
8057
+ uint256Word2(price, "price"),
8058
+ uint256Word2(amount, "amount"),
8059
+ uint64Word3(expiresAtBlock, "expiresAtBlock")
8060
+ )
8061
+ );
8062
+ }
8063
+ function quoteOperatorFee(args, feeBps) {
8064
+ if (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > PROTOCOL_MAX_OPERATOR_FEE_BPS) {
8065
+ throw new MarketActionError(
8066
+ `feeBps must be an integer in 0..=${PROTOCOL_MAX_OPERATOR_FEE_BPS}`
8067
+ );
8068
+ }
8069
+ const operator = normalizeNativeMarketAddress(args.operator, "operator");
8070
+ if (operator.kind !== "user") {
8071
+ throw new MarketActionError("operator must be a 'mono' user address");
8072
+ }
8073
+ const price = positiveDecimal(args.price, "price");
8074
+ const amount = positiveDecimal(args.amount, "amount");
8075
+ const quoteBasis = price * amount;
8076
+ const feeAmount = quoteBasis * BigInt(feeBps) / 10000n;
8077
+ return {
8078
+ operator: args.operator,
8079
+ feeBps,
8080
+ quoteBasis: quoteBasis.toString(10),
8081
+ feeAmount: feeAmount.toString(10)
8082
+ };
8083
+ }
8084
+ function buildPlaceLimitOrderViaPlan(args, feeBps) {
8085
+ return {
8086
+ method: "eth_sendTransaction",
8087
+ params: [
8088
+ {
8089
+ to: PRECOMPILE_ADDRESSES.OPERATOR_ROUTER,
8090
+ value: "0x0",
8091
+ data: encodePlaceLimitOrderViaCalldata(args)
8092
+ }
8093
+ ],
8094
+ mempoolClass: MempoolClass.CLOBOp,
8095
+ operatorFee: quoteOperatorFee(args, feeBps)
8096
+ };
8097
+ }
8098
+ function decodeOperatorFeeChargedEvent(topics, data) {
8099
+ if (topics.length !== 4) {
8100
+ throw new MarketActionError(
8101
+ `OperatorFeeCharged expects 4 topics, got ${topics.length}`
8102
+ );
8103
+ }
8104
+ const topic0 = bytesToHex2(expectWordLen(toEventBytes(topics[0]), "topic0"));
8105
+ const expected = bytesToHex2(
8106
+ sha3_js.keccak_256(new TextEncoder().encode(OPERATOR_ROUTER_EVENT_SIGS.operatorFeeCharged))
8107
+ );
8108
+ if (topic0 !== expected) {
8109
+ throw new MarketActionError("topic0 is not OperatorFeeCharged");
8110
+ }
8111
+ const body = toEventBytes(data);
8112
+ if (body.length !== 4 * 32) {
8113
+ throw new MarketActionError(
8114
+ `OperatorFeeCharged expects 128 data bytes, got ${body.length}`
8115
+ );
8116
+ }
8117
+ return {
8118
+ operator: addressFromEventTopic(topics[1]),
8119
+ user: addressFromEventTopic(topics[2]),
8120
+ marketId: bytesToHex2(expectWordLen(toEventBytes(topics[3]), "marketId")),
8121
+ recipient: bytesToHex2(body.subarray(12, 32)),
8122
+ quoteToken: bytesToHex2(body.subarray(32, 64)),
8123
+ feeAmount: u256DecimalWord(body.subarray(64, 96)),
8124
+ clobOrderId: bytesToHex2(body.subarray(96, 128))
8125
+ };
8126
+ }
7313
8127
  function buildNativeCallForwarderArtifact(requestBytes) {
7314
8128
  const size = uint64(requestBytes, "requestBytes");
7315
8129
  if (size === 0n) {
@@ -7565,6 +8379,32 @@ function uint256Word2(value, name) {
7565
8379
  }
7566
8380
  return out;
7567
8381
  }
8382
+ function addressWord2(addr) {
8383
+ if (addr.length !== 20) {
8384
+ throw new MarketActionError("address must be 20 bytes");
8385
+ }
8386
+ const out = new Uint8Array(32);
8387
+ out.set(addr, 12);
8388
+ return out;
8389
+ }
8390
+ function toEventBytes(value) {
8391
+ if (typeof value === "string") return hexToBytes2(value, "event word");
8392
+ return value instanceof Uint8Array ? value : Uint8Array.from(value);
8393
+ }
8394
+ function expectWordLen(value, name) {
8395
+ if (value.length !== 32) {
8396
+ throw new MarketActionError(`${name} must be 32 bytes, got ${value.length}`);
8397
+ }
8398
+ return value;
8399
+ }
8400
+ function addressFromEventTopic(topic) {
8401
+ return bytesToHex2(expectWordLen(toEventBytes(topic), "address topic").subarray(12, 32));
8402
+ }
8403
+ function u256DecimalWord(word) {
8404
+ let v = 0n;
8405
+ for (const b of word) v = v << 8n | BigInt(b);
8406
+ return v.toString(10);
8407
+ }
7568
8408
  function spotLimitOrderInto(w, args, prefix) {
7569
8409
  w.rawBytes(bytes32FromHex(args.marketId, `${prefix}marketId`));
7570
8410
  monoAddressInto(w, args.owner, `${prefix}owner`);
@@ -8098,13 +8938,17 @@ exports.CHAIN_REGISTRY = CHAIN_REGISTRY;
8098
8938
  exports.CHAIN_REGISTRY_RAW_BASE = CHAIN_REGISTRY_RAW_BASE;
8099
8939
  exports.CLOB_MARKET_ID_DOMAIN_TAG = CLOB_MARKET_ID_DOMAIN_TAG;
8100
8940
  exports.CLOB_SELECTORS = CLOB_SELECTORS;
8941
+ exports.CLUSTER_FORMED_EVENT_SIG = CLUSTER_FORMED_EVENT_SIG;
8101
8942
  exports.DELEGATION_REVERT_TAGS = DELEGATION_REVERT_TAGS;
8102
8943
  exports.DELEGATION_SELECTORS = DELEGATION_SELECTORS;
8944
+ exports.DIVERSITY_SCORE_MAX = DIVERSITY_SCORE_MAX;
8103
8945
  exports.DelegationPrecompileError = DelegationPrecompileError;
8946
+ exports.EXECUTION_UNIT_PRICE_SAFETY_MULTIPLIER = EXECUTION_UNIT_PRICE_SAFETY_MULTIPLIER;
8104
8947
  exports.LYTHOSHI_PER_LYTH = LYTHOSHI_PER_LYTH;
8105
8948
  exports.LYTH_DECIMALS = LYTH_DECIMALS;
8106
8949
  exports.MAX_NATIVE_CALL_FORWARDER_REQUEST_BYTES = MAX_NATIVE_CALL_FORWARDER_REQUEST_BYTES;
8107
8950
  exports.MAX_NATIVE_RECEIPT_EVENTS = MAX_NATIVE_RECEIPT_EVENTS;
8951
+ exports.MIN_EXECUTION_UNIT_PRICE_LYTHOSHI = MIN_EXECUTION_UNIT_PRICE_LYTHOSHI;
8108
8952
  exports.ML_DSA_65_PUBLIC_KEY_LEN = ML_DSA_65_PUBLIC_KEY_LEN2;
8109
8953
  exports.ML_DSA_65_SIGNATURE_LEN = ML_DSA_65_SIGNATURE_LEN2;
8110
8954
  exports.MONOLYTHIUM_NETWORKS = MONOLYTHIUM_NETWORKS;
@@ -8122,6 +8966,7 @@ exports.MRV_PROFILE_MONO_RV32IM_V1 = MRV_PROFILE_MONO_RV32IM_V1;
8122
8966
  exports.MRV_STRUCTURED_FEE_FIELDS = MRV_STRUCTURED_FEE_FIELDS;
8123
8967
  exports.MRV_TX_EXTENSION_KIND = MRV_TX_EXTENSION_KIND;
8124
8968
  exports.MRV_TX_EXTENSION_V1 = MRV_TX_EXTENSION_V1;
8969
+ exports.MULTISIG_ADDRESS_DERIVATION_DOMAIN = MULTISIG_ADDRESS_DERIVATION_DOMAIN;
8125
8970
  exports.MarketActionError = MarketActionError;
8126
8971
  exports.MrvValidationError = MrvValidationError;
8127
8972
  exports.NATIVE_AGENT_MODULE_ADDRESS = NATIVE_AGENT_MODULE_ADDRESS;
@@ -8152,18 +8997,37 @@ exports.NO_EVM_RECEIPT_PROOF_TYPE = NO_EVM_RECEIPT_PROOF_TYPE;
8152
8997
  exports.NO_EVM_RECEIPT_ROOT_ALGORITHM = NO_EVM_RECEIPT_ROOT_ALGORITHM;
8153
8998
  exports.NoEvmReceiptProofError = NoEvmReceiptProofError;
8154
8999
  exports.NodeRegistryError = NodeRegistryError;
9000
+ exports.OPERATOR_ROUTER_ADDRESS = OPERATOR_ROUTER_ADDRESS;
9001
+ exports.OPERATOR_ROUTER_EVENT_SIGS = OPERATOR_ROUTER_EVENT_SIGS;
9002
+ exports.OPERATOR_ROUTER_SELECTORS = OPERATOR_ROUTER_SELECTORS;
9003
+ exports.OPERATOR_ROUTER_SIGS = OPERATOR_ROUTER_SIGS;
9004
+ exports.ORACLE_EVENT_SIGS = ORACLE_EVENT_SIGS;
9005
+ exports.OracleEventError = OracleEventError;
8155
9006
  exports.PRECOMPILE_ADDRESSES = PRECOMPILE_ADDRESSES;
9007
+ exports.PROTOCOL_MAX_OPERATOR_FEE_BPS = PROTOCOL_MAX_OPERATOR_FEE_BPS;
9008
+ exports.PROVER_MARKET_ADDRESS = PROVER_MARKET_ADDRESS;
9009
+ exports.PROVER_MARKET_BID_DOMAIN = PROVER_MARKET_BID_DOMAIN;
9010
+ exports.PROVER_MARKET_EVENT_SIGS = PROVER_MARKET_EVENT_SIGS;
9011
+ exports.PROVER_MARKET_REQUEST_DOMAIN = PROVER_MARKET_REQUEST_DOMAIN;
9012
+ exports.PROVER_MARKET_SELECTORS = PROVER_MARKET_SELECTORS;
9013
+ exports.PROVER_MARKET_SUBMIT_DOMAIN = PROVER_MARKET_SUBMIT_DOMAIN;
9014
+ exports.PROVER_SLASH_REASON_BAD_PROOF = PROVER_SLASH_REASON_BAD_PROOF;
9015
+ exports.PROVER_SLASH_REASON_NON_DELIVERY = PROVER_SLASH_REASON_NON_DELIVERY;
8156
9016
  exports.PUBKEY_REGISTRY_ML_DSA_65_PUBLIC_KEY_LEN = PUBKEY_REGISTRY_ML_DSA_65_PUBLIC_KEY_LEN;
8157
9017
  exports.PUBKEY_REGISTRY_SELECTORS = PUBKEY_REGISTRY_SELECTORS;
9018
+ exports.ProverMarketError = ProverMarketError;
8158
9019
  exports.PubkeyRegistryError = PubkeyRegistryError;
9020
+ exports.REGISTRY_DEFAULT_EXECUTION_UNIT_LIMIT = REGISTRY_DEFAULT_EXECUTION_UNIT_LIMIT;
8159
9021
  exports.RESERVED_ADDRESS_HRPS = RESERVED_ADDRESS_HRPS;
8160
9022
  exports.RpcClient = RpcClient;
9023
+ exports.SERVES_GPU_PROVE = SERVES_GPU_PROVE;
8161
9024
  exports.SERVICE_PROBE_STATUS = SERVICE_PROBE_STATUS;
8162
9025
  exports.SET_POLICY_CLAIM_DOMAIN_TAG = SET_POLICY_CLAIM_DOMAIN_TAG;
8163
9026
  exports.SPENDING_POLICY_SELECTORS = SPENDING_POLICY_SELECTORS;
8164
9027
  exports.SdkError = SdkError;
8165
9028
  exports.SpendingPolicyError = SpendingPolicyError;
8166
9029
  exports.TESTNET_69420 = TESTNET_69420;
9030
+ exports.TRANSFER_DEFAULT_EXECUTION_UNIT_LIMIT = TRANSFER_DEFAULT_EXECUTION_UNIT_LIMIT;
8167
9031
  exports.V1_BRIDGE_ALLOWED_FEE_TOKEN = V1_BRIDGE_ALLOWED_FEE_TOKEN;
8168
9032
  exports.V1_BRIDGE_ALLOWED_PROTOCOL = V1_BRIDGE_ALLOWED_PROTOCOL;
8169
9033
  exports.addressBytesToHex = addressBytesToHex;
@@ -8181,7 +9045,9 @@ exports.assertNativeMarketOrderBookStreamPayload = assertNativeMarketOrderBookSt
8181
9045
  exports.assessBridgeRoute = assessBridgeRoute;
8182
9046
  exports.bech32ToAddress = bech32ToAddress;
8183
9047
  exports.bech32ToAddressBytes = bech32ToAddressBytes;
9048
+ exports.bidSighash = bidSighash;
8184
9049
  exports.bridgeAddressHex = bridgeAddressHex;
9050
+ exports.bridgeDrainRemaining = bridgeDrainRemaining;
8185
9051
  exports.bridgeQuoteSubmitReadiness = bridgeQuoteSubmitReadiness;
8186
9052
  exports.bridgeRoutesReadiness = bridgeRoutesReadiness;
8187
9053
  exports.bridgeTransferCandidates = bridgeTransferCandidates;
@@ -8227,12 +9093,14 @@ exports.buildNativeSpotSettleLimitOrderForwarderInput = buildNativeSpotSettleLim
8227
9093
  exports.buildNativeSpotSettleLimitOrderModuleCall = buildNativeSpotSettleLimitOrderModuleCall;
8228
9094
  exports.buildNativeSpotSettleRoutedLimitOrderForwarderInput = buildNativeSpotSettleRoutedLimitOrderForwarderInput;
8229
9095
  exports.buildNativeSpotSettleRoutedLimitOrderModuleCall = buildNativeSpotSettleRoutedLimitOrderModuleCall;
9096
+ exports.buildPlaceLimitOrderViaPlan = buildPlaceLimitOrderViaPlan;
8230
9097
  exports.buildPlaceSpotLimitOrderPlan = buildPlaceSpotLimitOrderPlan;
8231
9098
  exports.buildPlaceSpotMarketOrderExPlan = buildPlaceSpotMarketOrderExPlan;
8232
9099
  exports.buildPlaceSpotMarketOrderPlan = buildPlaceSpotMarketOrderPlan;
8233
9100
  exports.checkMrvFeeDisplayConformance = checkMrvFeeDisplayConformance;
8234
9101
  exports.checkMrvStructuredFeeConformance = checkMrvStructuredFeeConformance;
8235
9102
  exports.checkNativeDevkitCompatibility = checkNativeDevkitCompatibility;
9103
+ exports.clampPriorityTip = clampPriorityTip;
8236
9104
  exports.clobAddressHex = clobAddressHex;
8237
9105
  exports.compareNativeDevVersions = compareNativeDevVersions;
8238
9106
  exports.composeClaimBoundMessage = composeClaimBoundMessage;
@@ -8242,15 +9110,22 @@ exports.computeNoEvmReceiptsRoot = computeNoEvmReceiptsRoot;
8242
9110
  exports.computeNoEvmRoundFinalityMessage = computeNoEvmRoundFinalityMessage;
8243
9111
  exports.computeNoEvmTargetReceiptHash = computeNoEvmTargetReceiptHash;
8244
9112
  exports.consumeNativeEvents = consumeNativeEvents;
9113
+ exports.decodeClusterDiversity = decodeClusterDiversity;
9114
+ exports.decodeClusterFormedEvent = decodeClusterFormedEvent;
8245
9115
  exports.decodeHasPubkeyReturn = decodeHasPubkeyReturn;
8246
9116
  exports.decodeLookupPubkeyReturn = decodeLookupPubkeyReturn;
8247
9117
  exports.decodeNativeAgentStateResponse = decodeNativeAgentStateResponse;
8248
9118
  exports.decodeNativeMarketOrderBookDeltasResponse = decodeNativeMarketOrderBookDeltasResponse;
8249
9119
  exports.decodeNativeReceiptResponse = decodeNativeReceiptResponse;
8250
9120
  exports.decodeNoEvmReceiptTranscript = decodeNoEvmReceiptTranscript;
9121
+ exports.decodeOperatorFeeChargedEvent = decodeOperatorFeeChargedEvent;
9122
+ exports.decodeOperatorNetworkMetadata = decodeOperatorNetworkMetadata;
9123
+ exports.decodeOracleEvent = decodeOracleEvent;
9124
+ exports.decodeTimeWindow = decodeTimeWindow;
8251
9125
  exports.decodeTxFeedResponse = decodeTxFeedResponse;
8252
9126
  exports.delegationAddressHex = delegationAddressHex;
8253
9127
  exports.deriveClobMarketId = deriveClobMarketId;
9128
+ exports.deriveClusterAnchorAddress = deriveClusterAnchorAddress;
8254
9129
  exports.deriveMrvContractAddress = deriveMrvContractAddress;
8255
9130
  exports.deriveNativeSpotMarketId = deriveNativeSpotMarketId;
8256
9131
  exports.deriveNativeSpotOrderId = deriveNativeSpotOrderId;
@@ -8259,6 +9134,8 @@ exports.encodeCancelOrderCalldata = encodeCancelOrderCalldata;
8259
9134
  exports.encodeClaimCalldata = encodeClaimCalldata;
8260
9135
  exports.encodeClaimPolicyByAddressCalldata = encodeClaimPolicyByAddressCalldata;
8261
9136
  exports.encodeCompleteRedemptionCalldata = encodeCompleteRedemptionCalldata;
9137
+ exports.encodeCreateRequestCalldata = encodeCreateRequestCalldata;
9138
+ exports.encodeCreateRequestCanonical = encodeCreateRequestCanonical;
8262
9139
  exports.encodeDelegateCalldata = encodeDelegateCalldata;
8263
9140
  exports.encodeDisableCalldata = encodeDisableCalldata;
8264
9141
  exports.encodeEnableCalldata = encodeEnableCalldata;
@@ -8312,6 +9189,7 @@ exports.encodeNativeSpotLimitOrderCall = encodeNativeSpotLimitOrderCall;
8312
9189
  exports.encodeNativeSpotSettleLimitOrderCall = encodeNativeSpotSettleLimitOrderCall;
8313
9190
  exports.encodeNativeSpotSettleRoutedLimitOrderCall = encodeNativeSpotSettleRoutedLimitOrderCall;
8314
9191
  exports.encodePlaceLimitOrderCalldata = encodePlaceLimitOrderCalldata;
9192
+ exports.encodePlaceLimitOrderViaCalldata = encodePlaceLimitOrderViaCalldata;
8315
9193
  exports.encodePlaceMarketOrderCalldata = encodePlaceMarketOrderCalldata;
8316
9194
  exports.encodePlaceMarketOrderExCalldata = encodePlaceMarketOrderExCalldata;
8317
9195
  exports.encodeRedelegateCalldata = encodeRedelegateCalldata;
@@ -8364,9 +9242,13 @@ exports.nativeMarketEventsFromHistory = nativeMarketEventsFromHistory;
8364
9242
  exports.nativeMarketEventsFromReceipt = nativeMarketEventsFromReceipt;
8365
9243
  exports.nativeMarketStateFilterParams = nativeMarketStateFilterParams;
8366
9244
  exports.noEvmReceiptTrustPolicyFromChainInfo = noEvmReceiptTrustPolicyFromChainInfo;
9245
+ exports.nodeHostingClassFromByte = nodeHostingClassFromByte;
9246
+ exports.nodeHostingClassToByte = nodeHostingClassToByte;
8367
9247
  exports.nodeRegistryAddressHex = nodeRegistryAddressHex;
8368
9248
  exports.normalizeAddressHex = normalizeAddressHex;
8369
9249
  exports.normalizeBridgeRouteCatalogue = normalizeBridgeRouteCatalogue;
9250
+ exports.oracleAddressHex = oracleAddressHex;
9251
+ exports.packTimeWindow = packTimeWindow;
8370
9252
  exports.parseAddress = parseAddress;
8371
9253
  exports.parseBridgeRouteCatalogueJson = parseBridgeRouteCatalogueJson;
8372
9254
  exports.parseChainRegistryToml = parseChainRegistryToml;
@@ -8374,9 +9256,15 @@ exports.parseLythToLythoshi = parseLythToLythoshi;
8374
9256
  exports.parseNativeDecodedEvent = parseNativeDecodedEvent;
8375
9257
  exports.parseQuantity = parseQuantity;
8376
9258
  exports.parseQuantityBig = parseQuantityBig;
9259
+ exports.proverMarketStateFromByte = proverMarketStateFromByte;
8377
9260
  exports.pubkeyRegistryAddressHex = pubkeyRegistryAddressHex;
9261
+ exports.quoteOperatorFee = quoteOperatorFee;
8378
9262
  exports.rankBridgeRoutes = rankBridgeRoutes;
9263
+ exports.requestSighash = requestSighash;
8379
9264
  exports.requireTypedAddress = requireTypedAddress;
9265
+ exports.resolveExecutionFee = resolveExecutionFee;
9266
+ exports.resolveMaxExecutionUnitPrice = resolveMaxExecutionUnitPrice;
9267
+ exports.resolveRegistryExecutionFee = resolveRegistryExecutionFee;
8380
9268
  exports.resolveStudioHostStatus = resolveStudioHostStatus;
8381
9269
  exports.selectBridgeTransferRoute = selectBridgeTransferRoute;
8382
9270
  exports.serviceProbeStatusLabel = serviceProbeStatusLabel;
@@ -8384,6 +9272,7 @@ exports.spendingPolicyAddressHex = spendingPolicyAddressHex;
8384
9272
  exports.submitMrvCallNativeTx = submitMrvCallNativeTx;
8385
9273
  exports.submitMrvDeployNativeTx = submitMrvDeployNativeTx;
8386
9274
  exports.submitMrvDeployPayloadNativeTx = submitMrvDeployPayloadNativeTx;
9275
+ exports.submitSighash = submitSighash;
8387
9276
  exports.typedBech32ToAddress = typedBech32ToAddress;
8388
9277
  exports.validateAddress = validateAddress;
8389
9278
  exports.validateBridgeRouteCatalogue = validateBridgeRouteCatalogue;