@interfold/sdk 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -3,8 +3,8 @@ import { C as ContractAddresses, E as E3RequestParams, a as E3, F as FailureReas
3
3
  export { c as CommitteeSize, v as validateCommitteeSize } from './types-Cwx_flfX.js';
4
4
  import { ThresholdBfvParamsPresetName, BfvParams, EncryptedValueAndPublicInputs, VerifiableEncryptionResult } from './crypto/index.js';
5
5
  export { ThresholdBfvParamsPresetNames, computeCiphertextCommitment, computePublicKeyCommitment, encryptNumber, encryptNumberAndGenInputs, encryptNumberAndGenProof, encryptVector, encryptVectorAndGenInputs, encryptVectorAndGenProof, generateProof, generatePublicKey, getThresholdBfvParamsSet } from './crypto/index.js';
6
- import { AllEventTypes, EventCallback } from './events/index.js';
7
- export { CiphernodeAddedData, CiphernodeRemovedData, CiphertextOutputPublishedData, CommitteeFinalizedData, CommitteePublishedData, CommitteeRequestedData, E3ActivatedData, E3RequestedData, EventFilter, EventListener, EventListenerConfig, EventListenerOptions, InterfoldEvent, InterfoldEventData, InterfoldEventType, PlaintextOutputPublishedData, RegistryEventData, RegistryEventType, SDKEventEmitter } from './events/index.js';
6
+ import { AllEventTypes, EventCallback, RandomnessProviderEventType, RandomnessProviderEventCallback } from './events/index.js';
7
+ export { CiphernodeAddedData, CiphernodeRemovedData, CiphertextOutputPublishedData, CommitteeFinalizedData, CommitteePublishedData, CommitteeRandomnessRequestedData, CommitteeRequestedData, E3ActivatedData, E3RequestedData, EventFilter, EventListener, EventListenerConfig, EventListenerOptions, InterfoldEvent, InterfoldEventData, InterfoldEventType, PlaintextOutputPublishedData, RandomnessCircuitBreakerTrippedData, RandomnessFulfilledData, RandomnessProviderEvent, RegistryEventData, RegistryEventType, SDKEventEmitter } from './events/index.js';
8
8
  export { ContractClient, ContractClientConfig } from './contracts/index.js';
9
9
  import '@aztec/bb.js';
10
10
 
@@ -54,6 +54,9 @@ declare class InterfoldSDK {
54
54
  estimateGas(functionName: string, args: readonly unknown[], contractAddress: `0x${string}`, abi: Abi, value?: bigint): Promise<bigint>;
55
55
  waitForTransaction(hash: Hash): Promise<unknown>;
56
56
  onInterfoldEvent<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): Promise<void>;
57
+ onRandomnessProviderEvent<T extends RandomnessProviderEventType>(provider: `0x${string}`, eventType: T, callback: RandomnessProviderEventCallback<T>, fromBlock?: bigint): Promise<void>;
58
+ offRandomnessProviderEvent<T extends RandomnessProviderEventType>(provider: `0x${string}`, eventType: T, callback: RandomnessProviderEventCallback<T>): void;
59
+ getHistoricalRandomnessProviderEvents(provider: `0x${string}`, eventType: RandomnessProviderEventType, fromBlock?: bigint, toBlock?: bigint): Promise<Log[]>;
57
60
  off<T extends AllEventTypes>(eventType: T, callback: EventCallback<T>): void;
58
61
  once<T extends AllEventTypes>(type: T, callback: EventCallback<T>): Promise<void>;
59
62
  getHistoricalEvents(eventType: AllEventTypes, fromBlock?: bigint, toBlock?: bigint): Promise<Log[]>;
@@ -134,4 +137,4 @@ declare function calculateInputWindow(publicClient: PublicClient, duration?: num
134
137
  */
135
138
  declare function decodePlaintextOutput(plaintextOutput: string): number | null;
136
139
 
137
- export { AllEventTypes, BfvParams, type ComputeProviderParams, ContractAddresses, DEFAULT_COMPUTE_PROVIDER_PARAMS, DEFAULT_E3_CONFIG, DEFAULT_THRESHOLD_BFV_PARAMS_PRESET_NAME, E3, E3RequestParams, E3Stage, EncryptedValueAndPublicInputs, EventCallback, FailureReason, InterfoldSDK, type SDKConfig, SDKError, ThresholdBfvParamsPresetName, VerifiableEncryptionResult, calculateInputWindow, decodePlaintextOutput, encodeBfvParams, encodeComputeProviderParams, encodeCustomParams, formatBigInt, formatEventName, generateEventId, getCurrentTimestamp, isValidAddress, isValidHash, parseBigInt, parseEventData, sleep };
140
+ export { AllEventTypes, BfvParams, type ComputeProviderParams, ContractAddresses, DEFAULT_COMPUTE_PROVIDER_PARAMS, DEFAULT_E3_CONFIG, DEFAULT_THRESHOLD_BFV_PARAMS_PRESET_NAME, E3, E3RequestParams, E3Stage, EncryptedValueAndPublicInputs, EventCallback, FailureReason, InterfoldSDK, RandomnessProviderEventCallback, RandomnessProviderEventType, type SDKConfig, SDKError, ThresholdBfvParamsPresetName, VerifiableEncryptionResult, calculateInputWindow, decodePlaintextOutput, encodeBfvParams, encodeComputeProviderParams, encodeCustomParams, formatBigInt, formatEventName, generateEventId, getCurrentTimestamp, isValidAddress, isValidHash, parseBigInt, parseEventData, sleep };
package/dist/index.js CHANGED
@@ -465,7 +465,7 @@ var ContractClient = class _ContractClient {
465
465
  };
466
466
 
467
467
  // src/events/event-listener.ts
468
- import { CiphernodeRegistryOwnable__factory as CiphernodeRegistryOwnable__factory2, Interfold__factory as Interfold__factory2 } from "@interfold/contracts/types";
468
+ import { CiphernodeRegistryOwnable__factory as CiphernodeRegistryOwnable__factory2, Interfold__factory as Interfold__factory2, IRandomnessProvider__factory } from "@interfold/contracts/types";
469
469
 
470
470
  // src/events/types.ts
471
471
  var InterfoldEventType = /* @__PURE__ */ ((InterfoldEventType2) => {
@@ -483,6 +483,8 @@ var InterfoldEventType = /* @__PURE__ */ ((InterfoldEventType2) => {
483
483
  })(InterfoldEventType || {});
484
484
  var RegistryEventType = /* @__PURE__ */ ((RegistryEventType2) => {
485
485
  RegistryEventType2["COMMITTEE_REQUESTED"] = "CommitteeRequested";
486
+ RegistryEventType2["COMMITTEE_RANDOMNESS_REQUESTED"] = "CommitteeRandomnessRequested";
487
+ RegistryEventType2["RANDOMNESS_CIRCUIT_BREAKER_TRIPPED"] = "RandomnessCircuitBreakerTripped";
486
488
  RegistryEventType2["COMMITTEE_PUBLISHED"] = "CommitteePublished";
487
489
  RegistryEventType2["COMMITTEE_FINALIZED"] = "SortitionCommitteeFinalized";
488
490
  RegistryEventType2["INTERFOLD_SET"] = "InterfoldSet";
@@ -490,11 +492,20 @@ var RegistryEventType = /* @__PURE__ */ ((RegistryEventType2) => {
490
492
  RegistryEventType2["INITIALIZED"] = "Initialized";
491
493
  return RegistryEventType2;
492
494
  })(RegistryEventType || {});
495
+ var RandomnessProviderEventType = /* @__PURE__ */ ((RandomnessProviderEventType2) => {
496
+ RandomnessProviderEventType2["RANDOMNESS_FULFILLED"] = "RandomnessFulfilled";
497
+ return RandomnessProviderEventType2;
498
+ })(RandomnessProviderEventType || {});
493
499
 
494
500
  // src/events/event-listener.ts
495
501
  var EventListener = class _EventListener {
502
+ static DEFAULT_HISTORICAL_BLOCK_RANGE = 10000n;
503
+ static MAX_REMEMBERED_LOGS = 1e4;
496
504
  listeners = /* @__PURE__ */ new Map();
497
505
  activeWatchers = /* @__PURE__ */ new Map();
506
+ watcherStartBlocks = /* @__PURE__ */ new Map();
507
+ randomnessProviderListeners = /* @__PURE__ */ new Map();
508
+ seenLiveLogs = /* @__PURE__ */ new Map();
498
509
  isPolling = false;
499
510
  lastBlockNumber = BigInt(0);
500
511
  publicClient;
@@ -511,6 +522,8 @@ var EventListener = class _EventListener {
511
522
  // runtime; those default to the Interfold contract.
512
523
  static REGISTRY_ONLY_EVENTS = /* @__PURE__ */ new Set([
513
524
  "CommitteeRequested" /* COMMITTEE_REQUESTED */,
525
+ "CommitteeRandomnessRequested" /* COMMITTEE_RANDOMNESS_REQUESTED */,
526
+ "RandomnessCircuitBreakerTripped" /* RANDOMNESS_CIRCUIT_BREAKER_TRIPPED */,
514
527
  "CommitteePublished" /* COMMITTEE_PUBLISHED */,
515
528
  "SortitionCommitteeFinalized" /* COMMITTEE_FINALIZED */,
516
529
  "InterfoldSet" /* INTERFOLD_SET */
@@ -526,6 +539,93 @@ var EventListener = class _EventListener {
526
539
  const { address, abi } = this.resolveContract(eventType);
527
540
  return this.watchContractEvent(address, eventType, abi, callback);
528
541
  }
542
+ async onRandomnessProviderEvent(provider, eventType, callback, fromBlock) {
543
+ const listenerKey = `${provider.toLowerCase()}:${eventType}`;
544
+ const watcherKey = `randomness-provider:${listenerKey}`;
545
+ const requestedStartBlock = fromBlock ?? this.config.fromBlock;
546
+ let callbacks = this.randomnessProviderListeners.get(listenerKey);
547
+ if (!callbacks) {
548
+ callbacks = /* @__PURE__ */ new Set();
549
+ this.randomnessProviderListeners.set(listenerKey, callbacks);
550
+ }
551
+ if (this.activeWatchers.has(watcherKey)) {
552
+ const activeStartBlock = this.watcherStartBlocks.get(watcherKey);
553
+ if (fromBlock !== void 0 && requestedStartBlock !== activeStartBlock) {
554
+ throw new SDKError(
555
+ `Randomness provider watcher for ${eventType} on ${provider} already starts at ${activeStartBlock ?? "latest"}; requested ${requestedStartBlock ?? "latest"}`,
556
+ "INVALID_EVENT_CONFIG"
557
+ );
558
+ }
559
+ callbacks.add(callback);
560
+ return;
561
+ }
562
+ callbacks.add(callback);
563
+ try {
564
+ const unwatch = this.publicClient.watchContractEvent({
565
+ address: provider,
566
+ abi: IRandomnessProvider__factory.abi,
567
+ eventName: eventType,
568
+ fromBlock: requestedStartBlock,
569
+ onLogs: (logs) => {
570
+ for (const log of logs) {
571
+ if (!this.rememberLiveLog(log)) continue;
572
+ const event = {
573
+ type: eventType,
574
+ data: log.args,
575
+ provider,
576
+ log,
577
+ timestamp: /* @__PURE__ */ new Date(),
578
+ blockNumber: log.blockNumber ?? 0n,
579
+ transactionHash: log.transactionHash ?? "0x"
580
+ };
581
+ const currentCallbacks = this.randomnessProviderListeners.get(listenerKey);
582
+ currentCallbacks?.forEach((currentCallback) => {
583
+ try {
584
+ const result = currentCallback(event);
585
+ if (result) {
586
+ void result.catch((error) => {
587
+ console.error(`Error in randomness provider callback for ${eventType}:`, error);
588
+ });
589
+ }
590
+ } catch (error) {
591
+ console.error(`Error in randomness provider callback for ${eventType}:`, error);
592
+ }
593
+ });
594
+ }
595
+ }
596
+ });
597
+ this.activeWatchers.set(watcherKey, unwatch);
598
+ this.watcherStartBlocks.set(watcherKey, requestedStartBlock);
599
+ } catch (error) {
600
+ callbacks.delete(callback);
601
+ if (callbacks.size === 0) this.randomnessProviderListeners.delete(listenerKey);
602
+ throw new SDKError(`Failed to watch randomness provider event ${eventType} on ${provider}: ${error}`, "WATCH_EVENT_FAILED");
603
+ }
604
+ }
605
+ offRandomnessProviderEvent(provider, eventType, callback) {
606
+ const listenerKey = `${provider.toLowerCase()}:${eventType}`;
607
+ const callbacks = this.randomnessProviderListeners.get(listenerKey);
608
+ callbacks?.delete(callback);
609
+ if (callbacks && callbacks.size === 0) {
610
+ this.randomnessProviderListeners.delete(listenerKey);
611
+ const watcherKey = `randomness-provider:${listenerKey}`;
612
+ const unwatch = this.activeWatchers.get(watcherKey);
613
+ if (unwatch) unwatch();
614
+ this.activeWatchers.delete(watcherKey);
615
+ this.watcherStartBlocks.delete(watcherKey);
616
+ }
617
+ }
618
+ async getHistoricalRandomnessProviderEvents(provider, eventType, fromBlock, toBlock) {
619
+ const start = fromBlock ?? this.config.fromBlock;
620
+ if (start === void 0) {
621
+ throw new SDKError("Randomness provider history requires fromBlock or EventListenerConfig.fromBlock", "INVALID_EVENT_CONFIG");
622
+ }
623
+ try {
624
+ return await this.getHistoricalContractEvents(provider, IRandomnessProvider__factory.abi, eventType, start, toBlock);
625
+ } catch (error) {
626
+ throw new SDKError(`Failed to get randomness provider events from ${provider}: ${error}`, "HISTORICAL_EVENTS_FAILED");
627
+ }
628
+ }
529
629
  async once(type, callback) {
530
630
  const handler = (event) => {
531
631
  this.off(type, handler);
@@ -554,6 +654,7 @@ var EventListener = class _EventListener {
554
654
  for (let i = 0; i < logs.length; i++) {
555
655
  const log = logs[i];
556
656
  if (!log) break;
657
+ if (!emitter.rememberLiveLog(log)) continue;
557
658
  const event = {
558
659
  type: eventType,
559
660
  data: log.args,
@@ -607,13 +708,7 @@ var EventListener = class _EventListener {
607
708
  async getHistoricalEvents(eventType, fromBlock, toBlock) {
608
709
  const { address, abi } = this.resolveContract(eventType);
609
710
  try {
610
- return await this.publicClient.getContractEvents({
611
- address,
612
- abi,
613
- eventName: eventType,
614
- fromBlock: fromBlock ?? this.config.fromBlock,
615
- toBlock: toBlock ?? this.config.toBlock
616
- });
711
+ return await this.getHistoricalContractEvents(address, abi, eventType, fromBlock, toBlock);
617
712
  } catch (error) {
618
713
  throw new SDKError(`Failed to get historical events: ${error}`, "HISTORICAL_EVENTS_FAILED");
619
714
  }
@@ -672,7 +767,65 @@ var EventListener = class _EventListener {
672
767
  }
673
768
  });
674
769
  this.activeWatchers.clear();
770
+ this.watcherStartBlocks.clear();
675
771
  this.listeners.clear();
772
+ this.randomnessProviderListeners.clear();
773
+ this.seenLiveLogs.clear();
774
+ }
775
+ logIdentity(log) {
776
+ if (log.blockHash && log.transactionHash && log.logIndex !== null && log.logIndex !== void 0) {
777
+ return `${log.blockHash}:${log.transactionHash}:${log.logIndex}:${Boolean(log.removed)}`;
778
+ }
779
+ return void 0;
780
+ }
781
+ rememberLiveLog(log) {
782
+ const identity = this.logIdentity(log);
783
+ if (!identity) return true;
784
+ if (this.seenLiveLogs.has(identity)) return false;
785
+ this.seenLiveLogs.set(identity, true);
786
+ if (this.seenLiveLogs.size > _EventListener.MAX_REMEMBERED_LOGS) {
787
+ const oldest = this.seenLiveLogs.keys().next().value;
788
+ if (oldest !== void 0) this.seenLiveLogs.delete(oldest);
789
+ }
790
+ return true;
791
+ }
792
+ async getHistoricalContractEvents(address, abi, eventName, fromBlock, toBlock) {
793
+ const start = fromBlock ?? this.config.fromBlock;
794
+ const configuredEnd = toBlock ?? this.config.toBlock;
795
+ if (start === void 0) {
796
+ return await this.publicClient.getContractEvents({
797
+ address,
798
+ abi,
799
+ eventName,
800
+ toBlock: configuredEnd
801
+ });
802
+ }
803
+ const end = configuredEnd ?? await this.publicClient.getBlockNumber({ cacheTime: 0 });
804
+ if (end < start) return [];
805
+ const range = this.config.historicalBlockRange ?? _EventListener.DEFAULT_HISTORICAL_BLOCK_RANGE;
806
+ if (range <= 0n) throw new SDKError("Historical block range must be greater than zero", "INVALID_EVENT_CONFIG");
807
+ const logs = [];
808
+ const seen = /* @__PURE__ */ new Set();
809
+ for (let cursor = start; cursor <= end; cursor += range) {
810
+ const chunkEnd = cursor + range - 1n < end ? cursor + range - 1n : end;
811
+ const chunk = await this.publicClient.getContractEvents({
812
+ address,
813
+ abi,
814
+ eventName,
815
+ fromBlock: cursor,
816
+ toBlock: chunkEnd
817
+ });
818
+ for (const log of chunk) {
819
+ const identity = this.logIdentity(log);
820
+ if (identity && seen.has(identity)) continue;
821
+ if (identity) {
822
+ seen.add(identity);
823
+ this.rememberLiveLog(log);
824
+ }
825
+ logs.push(log);
826
+ }
827
+ }
828
+ return logs;
676
829
  }
677
830
  async pollForEvents() {
678
831
  while (this.isPolling) {
@@ -1046,6 +1199,15 @@ var InterfoldSDK = class _InterfoldSDK {
1046
1199
  async onInterfoldEvent(eventType, callback) {
1047
1200
  return this.eventListener.onInterfoldEvent(eventType, callback);
1048
1201
  }
1202
+ async onRandomnessProviderEvent(provider, eventType, callback, fromBlock) {
1203
+ return this.eventListener.onRandomnessProviderEvent(provider, eventType, callback, fromBlock);
1204
+ }
1205
+ offRandomnessProviderEvent(provider, eventType, callback) {
1206
+ this.eventListener.offRandomnessProviderEvent(provider, eventType, callback);
1207
+ }
1208
+ async getHistoricalRandomnessProviderEvents(provider, eventType, fromBlock, toBlock) {
1209
+ return this.eventListener.getHistoricalRandomnessProviderEvents(provider, eventType, fromBlock, toBlock);
1210
+ }
1049
1211
  off(eventType, callback) {
1050
1212
  this.eventListener.off(eventType, callback);
1051
1213
  }
@@ -1104,6 +1266,7 @@ export {
1104
1266
  FailureReason,
1105
1267
  InterfoldEventType,
1106
1268
  InterfoldSDK,
1269
+ RandomnessProviderEventType,
1107
1270
  RegistryEventType,
1108
1271
  SDKError,
1109
1272
  ThresholdBfvParamsPresetNames,