@interfold/sdk 0.12.1 → 0.14.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
@@ -67,6 +67,15 @@ var DEFAULT_E3_CONFIG = {
67
67
  payment_amount: "0"
68
68
  // 0 ETH in wei
69
69
  };
70
+ function cryptoConfigIdForParamSet(paramSet) {
71
+ if (paramSet === 0) {
72
+ return "0x04f3677e73b0f5066d6caf5cbd92e3fb2e38338edaf5cfc971ab28f7b684da78";
73
+ }
74
+ if (paramSet === 1) {
75
+ return "0xd9c86e581f8291ffb5b63595600e8d096ed30b16e2e0a6634a76c22b1f58fb4e";
76
+ }
77
+ throw new SDKError(`Unsupported BFV parameter set: ${paramSet}`, "UNSUPPORTED_CRYPTO_CONFIG");
78
+ }
70
79
  function encodeBfvParams(params) {
71
80
  const { degree, plaintextModulus, moduli, error1Variance } = params;
72
81
  if (error1Variance === void 0) {
@@ -277,11 +286,7 @@ var ContractClient = class _ContractClient {
277
286
  }
278
287
  const committeeSize = validateCommitteeSize(params.committeeSize);
279
288
  const maxFee = params.maxFee ?? await this.getE3Quote(params);
280
- const expectedCryptoConfigId = await this.publicClient.readContract({
281
- address: this.contracts.interfold,
282
- abi: Interfold__factory.abi,
283
- functionName: "activeCryptoConfigId"
284
- });
289
+ const expectedCryptoConfigId = cryptoConfigIdForParamSet(params.paramSet);
285
290
  const { request } = await this.publicClient.simulateContract({
286
291
  address: this.contracts.interfold,
287
292
  abi: Interfold__factory.abi,
@@ -366,11 +371,7 @@ var ContractClient = class _ContractClient {
366
371
  async getE3Quote(requestParams) {
367
372
  try {
368
373
  const committeeSize = validateCommitteeSize(requestParams.committeeSize);
369
- const expectedCryptoConfigId = await this.publicClient.readContract({
370
- address: this.contracts.interfold,
371
- abi: Interfold__factory.abi,
372
- functionName: "activeCryptoConfigId"
373
- });
374
+ const expectedCryptoConfigId = cryptoConfigIdForParamSet(requestParams.paramSet);
374
375
  return this.publicClient.readContract({
375
376
  address: this.contracts.interfold,
376
377
  abi: Interfold__factory.abi,
@@ -465,7 +466,7 @@ var ContractClient = class _ContractClient {
465
466
  };
466
467
 
467
468
  // src/events/event-listener.ts
468
- import { CiphernodeRegistryOwnable__factory as CiphernodeRegistryOwnable__factory2, Interfold__factory as Interfold__factory2 } from "@interfold/contracts/types";
469
+ import { CiphernodeRegistryOwnable__factory as CiphernodeRegistryOwnable__factory2, Interfold__factory as Interfold__factory2, IRandomnessProvider__factory } from "@interfold/contracts/types";
469
470
 
470
471
  // src/events/types.ts
471
472
  var InterfoldEventType = /* @__PURE__ */ ((InterfoldEventType2) => {
@@ -483,6 +484,8 @@ var InterfoldEventType = /* @__PURE__ */ ((InterfoldEventType2) => {
483
484
  })(InterfoldEventType || {});
484
485
  var RegistryEventType = /* @__PURE__ */ ((RegistryEventType2) => {
485
486
  RegistryEventType2["COMMITTEE_REQUESTED"] = "CommitteeRequested";
487
+ RegistryEventType2["COMMITTEE_RANDOMNESS_REQUESTED"] = "CommitteeRandomnessRequested";
488
+ RegistryEventType2["RANDOMNESS_CIRCUIT_BREAKER_TRIPPED"] = "RandomnessCircuitBreakerTripped";
486
489
  RegistryEventType2["COMMITTEE_PUBLISHED"] = "CommitteePublished";
487
490
  RegistryEventType2["COMMITTEE_FINALIZED"] = "SortitionCommitteeFinalized";
488
491
  RegistryEventType2["INTERFOLD_SET"] = "InterfoldSet";
@@ -490,11 +493,20 @@ var RegistryEventType = /* @__PURE__ */ ((RegistryEventType2) => {
490
493
  RegistryEventType2["INITIALIZED"] = "Initialized";
491
494
  return RegistryEventType2;
492
495
  })(RegistryEventType || {});
496
+ var RandomnessProviderEventType = /* @__PURE__ */ ((RandomnessProviderEventType2) => {
497
+ RandomnessProviderEventType2["RANDOMNESS_FULFILLED"] = "RandomnessFulfilled";
498
+ return RandomnessProviderEventType2;
499
+ })(RandomnessProviderEventType || {});
493
500
 
494
501
  // src/events/event-listener.ts
495
502
  var EventListener = class _EventListener {
503
+ static DEFAULT_HISTORICAL_BLOCK_RANGE = 10000n;
504
+ static MAX_REMEMBERED_LOGS = 1e4;
496
505
  listeners = /* @__PURE__ */ new Map();
497
506
  activeWatchers = /* @__PURE__ */ new Map();
507
+ watcherStartBlocks = /* @__PURE__ */ new Map();
508
+ randomnessProviderListeners = /* @__PURE__ */ new Map();
509
+ seenLiveLogs = /* @__PURE__ */ new Map();
498
510
  isPolling = false;
499
511
  lastBlockNumber = BigInt(0);
500
512
  publicClient;
@@ -511,6 +523,8 @@ var EventListener = class _EventListener {
511
523
  // runtime; those default to the Interfold contract.
512
524
  static REGISTRY_ONLY_EVENTS = /* @__PURE__ */ new Set([
513
525
  "CommitteeRequested" /* COMMITTEE_REQUESTED */,
526
+ "CommitteeRandomnessRequested" /* COMMITTEE_RANDOMNESS_REQUESTED */,
527
+ "RandomnessCircuitBreakerTripped" /* RANDOMNESS_CIRCUIT_BREAKER_TRIPPED */,
514
528
  "CommitteePublished" /* COMMITTEE_PUBLISHED */,
515
529
  "SortitionCommitteeFinalized" /* COMMITTEE_FINALIZED */,
516
530
  "InterfoldSet" /* INTERFOLD_SET */
@@ -526,6 +540,93 @@ var EventListener = class _EventListener {
526
540
  const { address, abi } = this.resolveContract(eventType);
527
541
  return this.watchContractEvent(address, eventType, abi, callback);
528
542
  }
543
+ async onRandomnessProviderEvent(provider, eventType, callback, fromBlock) {
544
+ const listenerKey = `${provider.toLowerCase()}:${eventType}`;
545
+ const watcherKey = `randomness-provider:${listenerKey}`;
546
+ const requestedStartBlock = fromBlock ?? this.config.fromBlock;
547
+ let callbacks = this.randomnessProviderListeners.get(listenerKey);
548
+ if (!callbacks) {
549
+ callbacks = /* @__PURE__ */ new Set();
550
+ this.randomnessProviderListeners.set(listenerKey, callbacks);
551
+ }
552
+ if (this.activeWatchers.has(watcherKey)) {
553
+ const activeStartBlock = this.watcherStartBlocks.get(watcherKey);
554
+ if (fromBlock !== void 0 && requestedStartBlock !== activeStartBlock) {
555
+ throw new SDKError(
556
+ `Randomness provider watcher for ${eventType} on ${provider} already starts at ${activeStartBlock ?? "latest"}; requested ${requestedStartBlock ?? "latest"}`,
557
+ "INVALID_EVENT_CONFIG"
558
+ );
559
+ }
560
+ callbacks.add(callback);
561
+ return;
562
+ }
563
+ callbacks.add(callback);
564
+ try {
565
+ const unwatch = this.publicClient.watchContractEvent({
566
+ address: provider,
567
+ abi: IRandomnessProvider__factory.abi,
568
+ eventName: eventType,
569
+ fromBlock: requestedStartBlock,
570
+ onLogs: (logs) => {
571
+ for (const log of logs) {
572
+ if (!this.rememberLiveLog(log)) continue;
573
+ const event = {
574
+ type: eventType,
575
+ data: log.args,
576
+ provider,
577
+ log,
578
+ timestamp: /* @__PURE__ */ new Date(),
579
+ blockNumber: log.blockNumber ?? 0n,
580
+ transactionHash: log.transactionHash ?? "0x"
581
+ };
582
+ const currentCallbacks = this.randomnessProviderListeners.get(listenerKey);
583
+ currentCallbacks?.forEach((currentCallback) => {
584
+ try {
585
+ const result = currentCallback(event);
586
+ if (result) {
587
+ void result.catch((error) => {
588
+ console.error(`Error in randomness provider callback for ${eventType}:`, error);
589
+ });
590
+ }
591
+ } catch (error) {
592
+ console.error(`Error in randomness provider callback for ${eventType}:`, error);
593
+ }
594
+ });
595
+ }
596
+ }
597
+ });
598
+ this.activeWatchers.set(watcherKey, unwatch);
599
+ this.watcherStartBlocks.set(watcherKey, requestedStartBlock);
600
+ } catch (error) {
601
+ callbacks.delete(callback);
602
+ if (callbacks.size === 0) this.randomnessProviderListeners.delete(listenerKey);
603
+ throw new SDKError(`Failed to watch randomness provider event ${eventType} on ${provider}: ${error}`, "WATCH_EVENT_FAILED");
604
+ }
605
+ }
606
+ offRandomnessProviderEvent(provider, eventType, callback) {
607
+ const listenerKey = `${provider.toLowerCase()}:${eventType}`;
608
+ const callbacks = this.randomnessProviderListeners.get(listenerKey);
609
+ callbacks?.delete(callback);
610
+ if (callbacks && callbacks.size === 0) {
611
+ this.randomnessProviderListeners.delete(listenerKey);
612
+ const watcherKey = `randomness-provider:${listenerKey}`;
613
+ const unwatch = this.activeWatchers.get(watcherKey);
614
+ if (unwatch) unwatch();
615
+ this.activeWatchers.delete(watcherKey);
616
+ this.watcherStartBlocks.delete(watcherKey);
617
+ }
618
+ }
619
+ async getHistoricalRandomnessProviderEvents(provider, eventType, fromBlock, toBlock) {
620
+ const start = fromBlock ?? this.config.fromBlock;
621
+ if (start === void 0) {
622
+ throw new SDKError("Randomness provider history requires fromBlock or EventListenerConfig.fromBlock", "INVALID_EVENT_CONFIG");
623
+ }
624
+ try {
625
+ return await this.getHistoricalContractEvents(provider, IRandomnessProvider__factory.abi, eventType, start, toBlock);
626
+ } catch (error) {
627
+ throw new SDKError(`Failed to get randomness provider events from ${provider}: ${error}`, "HISTORICAL_EVENTS_FAILED");
628
+ }
629
+ }
529
630
  async once(type, callback) {
530
631
  const handler = (event) => {
531
632
  this.off(type, handler);
@@ -554,6 +655,7 @@ var EventListener = class _EventListener {
554
655
  for (let i = 0; i < logs.length; i++) {
555
656
  const log = logs[i];
556
657
  if (!log) break;
658
+ if (!emitter.rememberLiveLog(log)) continue;
557
659
  const event = {
558
660
  type: eventType,
559
661
  data: log.args,
@@ -607,13 +709,7 @@ var EventListener = class _EventListener {
607
709
  async getHistoricalEvents(eventType, fromBlock, toBlock) {
608
710
  const { address, abi } = this.resolveContract(eventType);
609
711
  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
- });
712
+ return await this.getHistoricalContractEvents(address, abi, eventType, fromBlock, toBlock);
617
713
  } catch (error) {
618
714
  throw new SDKError(`Failed to get historical events: ${error}`, "HISTORICAL_EVENTS_FAILED");
619
715
  }
@@ -672,7 +768,65 @@ var EventListener = class _EventListener {
672
768
  }
673
769
  });
674
770
  this.activeWatchers.clear();
771
+ this.watcherStartBlocks.clear();
675
772
  this.listeners.clear();
773
+ this.randomnessProviderListeners.clear();
774
+ this.seenLiveLogs.clear();
775
+ }
776
+ logIdentity(log) {
777
+ if (log.blockHash && log.transactionHash && log.logIndex !== null && log.logIndex !== void 0) {
778
+ return `${log.blockHash}:${log.transactionHash}:${log.logIndex}:${Boolean(log.removed)}`;
779
+ }
780
+ return void 0;
781
+ }
782
+ rememberLiveLog(log) {
783
+ const identity = this.logIdentity(log);
784
+ if (!identity) return true;
785
+ if (this.seenLiveLogs.has(identity)) return false;
786
+ this.seenLiveLogs.set(identity, true);
787
+ if (this.seenLiveLogs.size > _EventListener.MAX_REMEMBERED_LOGS) {
788
+ const oldest = this.seenLiveLogs.keys().next().value;
789
+ if (oldest !== void 0) this.seenLiveLogs.delete(oldest);
790
+ }
791
+ return true;
792
+ }
793
+ async getHistoricalContractEvents(address, abi, eventName, fromBlock, toBlock) {
794
+ const start = fromBlock ?? this.config.fromBlock;
795
+ const configuredEnd = toBlock ?? this.config.toBlock;
796
+ if (start === void 0) {
797
+ return await this.publicClient.getContractEvents({
798
+ address,
799
+ abi,
800
+ eventName,
801
+ toBlock: configuredEnd
802
+ });
803
+ }
804
+ const end = configuredEnd ?? await this.publicClient.getBlockNumber({ cacheTime: 0 });
805
+ if (end < start) return [];
806
+ const range = this.config.historicalBlockRange ?? _EventListener.DEFAULT_HISTORICAL_BLOCK_RANGE;
807
+ if (range <= 0n) throw new SDKError("Historical block range must be greater than zero", "INVALID_EVENT_CONFIG");
808
+ const logs = [];
809
+ const seen = /* @__PURE__ */ new Set();
810
+ for (let cursor = start; cursor <= end; cursor += range) {
811
+ const chunkEnd = cursor + range - 1n < end ? cursor + range - 1n : end;
812
+ const chunk = await this.publicClient.getContractEvents({
813
+ address,
814
+ abi,
815
+ eventName,
816
+ fromBlock: cursor,
817
+ toBlock: chunkEnd
818
+ });
819
+ for (const log of chunk) {
820
+ const identity = this.logIdentity(log);
821
+ if (identity && seen.has(identity)) continue;
822
+ if (identity) {
823
+ seen.add(identity);
824
+ this.rememberLiveLog(log);
825
+ }
826
+ logs.push(log);
827
+ }
828
+ }
829
+ return logs;
676
830
  }
677
831
  async pollForEvents() {
678
832
  while (this.isPolling) {
@@ -1046,6 +1200,15 @@ var InterfoldSDK = class _InterfoldSDK {
1046
1200
  async onInterfoldEvent(eventType, callback) {
1047
1201
  return this.eventListener.onInterfoldEvent(eventType, callback);
1048
1202
  }
1203
+ async onRandomnessProviderEvent(provider, eventType, callback, fromBlock) {
1204
+ return this.eventListener.onRandomnessProviderEvent(provider, eventType, callback, fromBlock);
1205
+ }
1206
+ offRandomnessProviderEvent(provider, eventType, callback) {
1207
+ this.eventListener.offRandomnessProviderEvent(provider, eventType, callback);
1208
+ }
1209
+ async getHistoricalRandomnessProviderEvents(provider, eventType, fromBlock, toBlock) {
1210
+ return this.eventListener.getHistoricalRandomnessProviderEvents(provider, eventType, fromBlock, toBlock);
1211
+ }
1049
1212
  off(eventType, callback) {
1050
1213
  this.eventListener.off(eventType, callback);
1051
1214
  }
@@ -1104,6 +1267,7 @@ export {
1104
1267
  FailureReason,
1105
1268
  InterfoldEventType,
1106
1269
  InterfoldSDK,
1270
+ RandomnessProviderEventType,
1107
1271
  RegistryEventType,
1108
1272
  SDKError,
1109
1273
  ThresholdBfvParamsPresetNames,