@0xpolygonid/js-sdk 1.31.1 → 1.31.3

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.
Files changed (30) hide show
  1. package/dist/browser/esm/index.js +773 -321
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +773 -319
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/credentials/status/on-chain-revocation.js +3 -10
  6. package/dist/node/cjs/identity/identity-wallet.js +17 -4
  7. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +0 -1
  8. package/dist/node/cjs/storage/blockchain/state.js +120 -3
  9. package/dist/node/cjs/storage/memory/cache-lru.js +25 -0
  10. package/dist/node/cjs/storage/memory/index.js +1 -0
  11. package/dist/node/cjs/storage/shared/identity-storage.js +7 -0
  12. package/dist/node/cjs/verifiable/constants.js +6 -1
  13. package/dist/node/esm/credentials/status/on-chain-revocation.js +4 -11
  14. package/dist/node/esm/identity/identity-wallet.js +17 -4
  15. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +0 -1
  16. package/dist/node/esm/storage/blockchain/state.js +120 -3
  17. package/dist/node/esm/storage/memory/cache-lru.js +18 -0
  18. package/dist/node/esm/storage/memory/index.js +1 -0
  19. package/dist/node/esm/storage/shared/identity-storage.js +7 -0
  20. package/dist/node/esm/verifiable/constants.js +5 -0
  21. package/dist/types/credentials/status/on-chain-revocation.d.ts +6 -2
  22. package/dist/types/identity/identity-wallet.d.ts +18 -3
  23. package/dist/types/storage/blockchain/state.d.ts +65 -1
  24. package/dist/types/storage/entities/identity.d.ts +1 -0
  25. package/dist/types/storage/interfaces/identity.d.ts +8 -1
  26. package/dist/types/storage/memory/cache-lru.d.ts +10 -0
  27. package/dist/types/storage/memory/index.d.ts +1 -0
  28. package/dist/types/storage/shared/identity-storage.d.ts +5 -0
  29. package/dist/types/verifiable/constants.d.ts +5 -0
  30. package/package.json +3 -2
@@ -11399,6 +11399,7 @@ var PolygonIdSdk = (function (exports) {
11399
11399
  ID_WALLET_CORE_CLAIM_IS_NOT_SET: 'core claim is not set in credential proofs',
11400
11400
  ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND: 'profile or identity not found',
11401
11401
  ID_WALLET_PROFILE_ALREADY_EXISTS: 'profile with given nonce or verifier already exists',
11402
+ ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS: 'profile with given verifier and tags already exists',
11402
11403
  ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF: 'issuer auth credential must have proof',
11403
11404
  ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF: 'mtp is required for auth bjj key to issue new credentials',
11404
11405
  // proof service
@@ -11580,6 +11581,10 @@ var PolygonIdSdk = (function (exports) {
11580
11581
  (function (DisplayMethodType) {
11581
11582
  DisplayMethodType["Iden3BasicDisplayMethodV1"] = "Iden3BasicDisplayMethodV1";
11582
11583
  })(exports.DisplayMethodType || (exports.DisplayMethodType = {}));
11584
+ /**
11585
+ * Default cache max size for in-memory cache
11586
+ */
11587
+ const DEFAULT_CACHE_MAX_SIZE = 10000;
11583
11588
 
11584
11589
  /**
11585
11590
  * Iden3SparseMerkleProof is a iden3 protocol merkle tree proof
@@ -70843,186 +70848,471 @@ var PolygonIdSdk = (function (exports) {
70843
70848
  };
70844
70849
  };
70845
70850
 
70846
- const defaultEthConnectionConfig = {
70847
- url: 'http://localhost:8545',
70848
- defaultGasLimit: 600000,
70849
- minGasPrice: '0',
70850
- maxGasPrice: '100000000000',
70851
- confirmationBlockCount: 5,
70852
- confirmationTimeout: 600000,
70853
- contractAddress: '',
70854
- receiptTimeout: 600000,
70855
- rpcResponseTimeout: 5000,
70856
- waitReceiptCycleTime: 30000,
70857
- waitBlockCycleTime: 3000
70851
+ /**
70852
+ * Type of MerkleTree
70853
+ *
70854
+ * @enum {number}
70855
+ */
70856
+ exports.MerkleTreeType = void 0;
70857
+ (function (MerkleTreeType) {
70858
+ // Claims is merkle tree type for claims tree
70859
+ MerkleTreeType[MerkleTreeType["Claims"] = 0] = "Claims";
70860
+ // Revocations is merkle tree type for revocations tree
70861
+ MerkleTreeType[MerkleTreeType["Revocations"] = 1] = "Revocations";
70862
+ // Roots is merkle tree type for roots tree
70863
+ MerkleTreeType[MerkleTreeType["Roots"] = 2] = "Roots";
70864
+ })(exports.MerkleTreeType || (exports.MerkleTreeType = {}));
70865
+
70866
+ const MERKLE_TREE_TYPES = [
70867
+ exports.MerkleTreeType.Claims,
70868
+ exports.MerkleTreeType.Revocations,
70869
+ exports.MerkleTreeType.Roots
70870
+ ];
70871
+ const createMerkleTreeMetaInfo = (identifier) => {
70872
+ const treesMeta = [];
70873
+ for (let index = 0; index < MERKLE_TREE_TYPES.length; index++) {
70874
+ const mType = MERKLE_TREE_TYPES[index];
70875
+ const treeId = `${identifier}+${mType}`;
70876
+ treesMeta.push({ treeId, identifier, type: mType });
70877
+ }
70878
+ return treesMeta;
70858
70879
  };
70880
+
70859
70881
  /**
70860
70882
  *
70861
70883
  *
70862
70884
  * @public
70863
- * @class EthStateStorage
70864
- * @implements implements IStateStorage interface
70885
+ * @class InMemoryMerkleTreeStorage
70886
+ * @implements implements IMerkleTreeStorage interface
70865
70887
  */
70866
- class EthStateStorage {
70888
+ class InMemoryMerkleTreeStorage {
70867
70889
  /**
70868
- * Creates an instance of EthStateStorage.
70869
- * @param {EthConnectionConfig} [ethConfig=defaultEthConnectionConfig]
70890
+ * Creates an instance of InMemoryMerkleTreeStorage.
70891
+ * @param {number} _mtDepth
70870
70892
  */
70871
- constructor(ethConfig) {
70872
- this.ethConfig = ethConfig;
70873
- const config = Array.isArray(ethConfig) ? ethConfig[0] : ethConfig;
70874
- this.provider = new JsonRpcProvider(config.url);
70875
- this.stateContract = new Contract(config.contractAddress, abi$3, this.provider);
70876
- this._transactionService = new TransactionService(this.getRpcProvider());
70893
+ constructor(_mtDepth) {
70894
+ this.mtDepth = _mtDepth;
70895
+ this._data = {};
70877
70896
  }
70878
- /** {@inheritdoc IStateStorage.getLatestStateById} */
70879
- async getLatestStateById(id) {
70880
- const { stateContract } = this.getStateContractAndProviderForId(id);
70881
- const rawData = await stateContract.getStateInfoById(id);
70882
- const stateInfo = {
70883
- id: BigInt(rawData[0]),
70884
- state: BigInt(rawData[1]),
70885
- replacedByState: BigInt(rawData[2]),
70886
- createdAtTimestamp: BigInt(rawData[3]),
70887
- replacedAtTimestamp: BigInt(rawData[4]),
70888
- createdAtBlock: BigInt(rawData[5]),
70889
- replacedAtBlock: BigInt(rawData[6])
70890
- };
70891
- return stateInfo;
70897
+ /** create trees in the memory*/
70898
+ async createIdentityMerkleTrees(identifier) {
70899
+ if (!identifier) {
70900
+ identifier = `${v4()}`;
70901
+ }
70902
+ if (this._data[identifier]) {
70903
+ throw new Error(`Present merkle tree meta information in the store for current identifier ${identifier}`);
70904
+ }
70905
+ this._data[identifier] = [];
70906
+ const treesMeta = [];
70907
+ MERKLE_TREE_TYPES.forEach((t) => {
70908
+ const treeId = identifier.concat('+' + t.toString());
70909
+ const tree = new Merkletree(new InMemoryDB(str2Bytes(treeId)), true, this.mtDepth);
70910
+ const metaInfo = { treeId, identifier: identifier, type: t };
70911
+ this._data[identifier].push({ tree, metaInfo });
70912
+ treesMeta.push(metaInfo);
70913
+ });
70914
+ return treesMeta;
70892
70915
  }
70893
- /** {@inheritdoc IStateStorage.getStateInfoByIdAndState} */
70894
- async getStateInfoByIdAndState(id, state) {
70895
- const { stateContract } = this.getStateContractAndProviderForId(id);
70896
- const rawData = await stateContract.getStateInfoByIdAndState(id, state);
70897
- const stateInfo = {
70898
- id: BigInt(rawData[0]),
70899
- state: BigInt(rawData[1]),
70900
- replacedByState: BigInt(rawData[2]),
70901
- createdAtTimestamp: BigInt(rawData[3]),
70902
- replacedAtTimestamp: BigInt(rawData[4]),
70903
- createdAtBlock: BigInt(rawData[5]),
70904
- replacedAtBlock: BigInt(rawData[6])
70905
- };
70906
- return stateInfo;
70916
+ /** get trees meta info from the memory */
70917
+ async getIdentityMerkleTreesInfo(identifier) {
70918
+ return this._data[identifier].map((treeWithInfo) => treeWithInfo.metaInfo);
70907
70919
  }
70908
- /** {@inheritdoc IStateStorage.publishState} */
70909
- async publishState(proof, signer) {
70910
- const stateTransitionPubSig = new StateTransitionPubSignals();
70911
- stateTransitionPubSig.pubSignalsUnmarshal(byteEncoder$1.encode(JSON.stringify(proof.pub_signals)));
70912
- const { userId, oldUserState, newUserState, isOldStateGenesis } = stateTransitionPubSig;
70913
- const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
70914
- const contract = stateContract.connect(signer);
70915
- const preparedZkpProof = prepareZkpProof(proof.proof);
70916
- const payload = [
70917
- userId.bigInt().toString(),
70918
- oldUserState.bigInt().toString(),
70919
- newUserState.bigInt().toString(),
70920
- isOldStateGenesis,
70921
- preparedZkpProof.a,
70922
- preparedZkpProof.b,
70923
- preparedZkpProof.c
70924
- ];
70925
- const feeData = await provider.getFeeData();
70926
- const maxFeePerGas = defaultEthConnectionConfig.maxFeePerGas
70927
- ? BigInt(defaultEthConnectionConfig.maxFeePerGas)
70928
- : feeData.maxFeePerGas;
70929
- const maxPriorityFeePerGas = defaultEthConnectionConfig.maxPriorityFeePerGas
70930
- ? BigInt(defaultEthConnectionConfig.maxPriorityFeePerGas)
70931
- : feeData.maxPriorityFeePerGas;
70932
- const gasLimit = await contract.transitState.estimateGas(...payload);
70933
- const txData = await contract.transitState.populateTransaction(...payload);
70934
- const request = {
70935
- to: txData.to,
70936
- data: txData.data,
70937
- gasLimit,
70938
- maxFeePerGas,
70939
- maxPriorityFeePerGas
70940
- };
70941
- const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
70942
- return txnHash;
70920
+ /** get merkle tree by identifier and type from memory */
70921
+ async getMerkleTreeByIdentifierAndType(identifier, mtType) {
70922
+ const treeWithMeta = this._data[identifier].find((treeWithInfo) => treeWithInfo.metaInfo.type == mtType);
70923
+ if (!treeWithMeta) {
70924
+ throw new Error(`Merkle tree not found for identifier ${identifier} and type ${mtType}`);
70925
+ }
70926
+ return treeWithMeta.tree;
70943
70927
  }
70944
- /** {@inheritdoc IStateStorage.publishStateGeneric} */
70945
- async publishStateGeneric(signer, userStateTransitionInfo) {
70946
- const { userId, oldUserState, newUserState, isOldStateGenesis, methodId, methodParams } = userStateTransitionInfo;
70947
- const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
70948
- const contract = stateContract.connect(signer);
70949
- const feeData = await provider.getFeeData();
70950
- const maxFeePerGas = defaultEthConnectionConfig.maxFeePerGas
70951
- ? BigInt(defaultEthConnectionConfig.maxFeePerGas)
70952
- : feeData.maxFeePerGas;
70953
- const maxPriorityFeePerGas = defaultEthConnectionConfig.maxPriorityFeePerGas
70954
- ? BigInt(defaultEthConnectionConfig.maxPriorityFeePerGas)
70955
- : feeData.maxPriorityFeePerGas;
70956
- const payload = [
70957
- userId.bigInt().toString(),
70958
- oldUserState.bigInt().toString(),
70959
- newUserState.bigInt().toString(),
70960
- isOldStateGenesis,
70961
- methodId,
70962
- methodParams //'0x'
70963
- ];
70964
- const gasLimit = await contract.transitStateGeneric.estimateGas(...payload);
70965
- const txData = await contract.transitStateGeneric.populateTransaction(...payload);
70966
- const request = {
70967
- to: txData.to,
70968
- data: txData.data,
70969
- gasLimit,
70970
- maxFeePerGas,
70971
- maxPriorityFeePerGas
70972
- };
70973
- const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
70974
- return txnHash;
70928
+ /** adds entry to merkle tree in the memory */
70929
+ async addToMerkleTree(identifier, mtType, hindex, hvalue) {
70930
+ for (let index = 0; index < this._data[identifier].length; index++) {
70931
+ if (this._data[identifier][index].metaInfo.type === mtType) {
70932
+ await this._data[identifier][index].tree.add(hindex, hvalue);
70933
+ }
70934
+ }
70975
70935
  }
70976
- /** {@inheritdoc IStateStorage.getGISTProof} */
70977
- async getGISTProof(id) {
70978
- const { stateContract } = this.getStateContractAndProviderForId(id);
70979
- const data = await stateContract.getGISTProof(id);
70980
- return {
70981
- root: BigInt(data.root.toString()),
70982
- existence: data.existence,
70983
- siblings: data.siblings?.map((sibling) => BigInt(sibling.toString())),
70984
- index: BigInt(data.index.toString()),
70985
- value: BigInt(data.value.toString()),
70986
- auxExistence: data.auxExistence,
70987
- auxIndex: BigInt(data.auxIndex.toString()),
70988
- auxValue: BigInt(data.auxValue.toString())
70989
- };
70936
+ /** bind merkle tree identifier in memory */
70937
+ async bindMerkleTreeToNewIdentifier(oldIdentifier, newIdentifier) {
70938
+ this._data[newIdentifier] = [...this._data[oldIdentifier]];
70939
+ delete this._data[oldIdentifier];
70940
+ this._data[newIdentifier].forEach((treeWithMeta) => {
70941
+ treeWithMeta.metaInfo.identifier = newIdentifier;
70942
+ });
70990
70943
  }
70991
- /** {@inheritdoc IStateStorage.getGISTRootInfo} */
70992
- async getGISTRootInfo(root, id) {
70993
- const { stateContract } = this.getStateContractAndProviderForId(id);
70994
- const data = await stateContract.getGISTRootInfo(root);
70995
- return {
70996
- root: BigInt(data.root.toString()),
70997
- replacedByRoot: BigInt(data.replacedByRoot.toString()),
70998
- createdAtTimestamp: BigInt(data.createdAtTimestamp.toString()),
70999
- replacedAtTimestamp: BigInt(data.replacedAtTimestamp.toString()),
71000
- createdAtBlock: BigInt(data.createdAtBlock.toString()),
71001
- replacedAtBlock: BigInt(data.replacedAtBlock.toString())
71002
- };
70944
+ }
70945
+
70946
+ /**
70947
+ * Storage Errors definition
70948
+ *
70949
+ * @enum {number}
70950
+ */
70951
+ var StorageErrors;
70952
+ (function (StorageErrors) {
70953
+ StorageErrors["ItemNotFound"] = "item not found";
70954
+ })(StorageErrors || (StorageErrors = {}));
70955
+
70956
+ /* eslint-disable @typescript-eslint/no-explicit-any */
70957
+ /**
70958
+ * Generic Memory Data Source
70959
+ *
70960
+ * @public
70961
+ * @class InMemoryDataSource - class
70962
+ * @template Type
70963
+ */
70964
+ class InMemoryDataSource {
70965
+ constructor() {
70966
+ this._data = [];
71003
70967
  }
71004
- /** {@inheritdoc IStateStorage.getRpcProvider} */
71005
- getRpcProvider() {
71006
- return this.provider;
70968
+ /** saves in the memory */
70969
+ async save(key, value, keyName = 'id') {
70970
+ const itemIndex = this._data.findIndex((i) => i[keyName] === key);
70971
+ if (itemIndex === -1) {
70972
+ this._data.push(value);
70973
+ }
70974
+ else {
70975
+ this._data[itemIndex] = value;
70976
+ }
71007
70977
  }
71008
- getStateContractAndProviderForId(id) {
71009
- const idTyped = Id.fromBigInt(id);
71010
- const chainId = getChainId(DID.blockchainFromId(idTyped), DID.networkIdFromId(idTyped));
71011
- const config = this.networkByChainId(chainId);
71012
- const provider = new JsonRpcProvider(config.url);
71013
- const stateContract = new Contract(config.contractAddress, abi$3, provider);
71014
- return { stateContract, provider };
70978
+ /** gets value from from the memory */
70979
+ async get(key, keyName = 'id') {
70980
+ return this._data.find((t) => t[keyName] === key);
71015
70981
  }
71016
- networkByChainId(chainId) {
71017
- const config = Array.isArray(this.ethConfig) ? this.ethConfig : [this.ethConfig];
71018
- const network = config.find((c) => c.chainId === chainId);
71019
- if (!network) {
71020
- throw new Error(`chainId "${chainId}" not supported`);
70982
+ /** loads from value from the memory */
70983
+ async load() {
70984
+ return this._data;
70985
+ }
70986
+ /** deletes from value from the memory */
70987
+ async delete(key, keyName = 'id') {
70988
+ const newData = this._data.filter((i) => i[keyName] !== key);
70989
+ if (newData.length === this._data.length) {
70990
+ throw new Error(`${StorageErrors.ItemNotFound} to delete: ${key}`);
71021
70991
  }
71022
- return network;
70992
+ this._data = newData;
71023
70993
  }
71024
70994
  }
71025
70995
 
70996
+ class QuickLRU extends Map {
70997
+ #size = 0;
70998
+ #cache = new Map();
70999
+ #oldCache = new Map();
71000
+ #maxSize;
71001
+ #maxAge;
71002
+ #onEviction;
71003
+
71004
+ constructor(options = {}) {
71005
+ super();
71006
+
71007
+ if (!(options.maxSize && options.maxSize > 0)) {
71008
+ throw new TypeError('`maxSize` must be a number greater than 0');
71009
+ }
71010
+
71011
+ if (typeof options.maxAge === 'number' && options.maxAge === 0) {
71012
+ throw new TypeError('`maxAge` must be a number greater than 0');
71013
+ }
71014
+
71015
+ this.#maxSize = options.maxSize;
71016
+ this.#maxAge = options.maxAge || Number.POSITIVE_INFINITY;
71017
+ this.#onEviction = options.onEviction;
71018
+ }
71019
+
71020
+ // For tests.
71021
+ get __oldCache() {
71022
+ return this.#oldCache;
71023
+ }
71024
+
71025
+ #emitEvictions(cache) {
71026
+ if (typeof this.#onEviction !== 'function') {
71027
+ return;
71028
+ }
71029
+
71030
+ for (const [key, item] of cache) {
71031
+ this.#onEviction(key, item.value);
71032
+ }
71033
+ }
71034
+
71035
+ #deleteIfExpired(key, item) {
71036
+ if (typeof item.expiry === 'number' && item.expiry <= Date.now()) {
71037
+ if (typeof this.#onEviction === 'function') {
71038
+ this.#onEviction(key, item.value);
71039
+ }
71040
+
71041
+ return this.delete(key);
71042
+ }
71043
+
71044
+ return false;
71045
+ }
71046
+
71047
+ #getOrDeleteIfExpired(key, item) {
71048
+ const deleted = this.#deleteIfExpired(key, item);
71049
+ if (deleted === false) {
71050
+ return item.value;
71051
+ }
71052
+ }
71053
+
71054
+ #getItemValue(key, item) {
71055
+ return item.expiry ? this.#getOrDeleteIfExpired(key, item) : item.value;
71056
+ }
71057
+
71058
+ #peek(key, cache) {
71059
+ const item = cache.get(key);
71060
+
71061
+ return this.#getItemValue(key, item);
71062
+ }
71063
+
71064
+ #set(key, value) {
71065
+ this.#cache.set(key, value);
71066
+ this.#size++;
71067
+
71068
+ if (this.#size >= this.#maxSize) {
71069
+ this.#size = 0;
71070
+ this.#emitEvictions(this.#oldCache);
71071
+ this.#oldCache = this.#cache;
71072
+ this.#cache = new Map();
71073
+ }
71074
+ }
71075
+
71076
+ #moveToRecent(key, item) {
71077
+ this.#oldCache.delete(key);
71078
+ this.#set(key, item);
71079
+ }
71080
+
71081
+ * #entriesAscending() {
71082
+ for (const item of this.#oldCache) {
71083
+ const [key, value] = item;
71084
+ if (!this.#cache.has(key)) {
71085
+ const deleted = this.#deleteIfExpired(key, value);
71086
+ if (deleted === false) {
71087
+ yield item;
71088
+ }
71089
+ }
71090
+ }
71091
+
71092
+ for (const item of this.#cache) {
71093
+ const [key, value] = item;
71094
+ const deleted = this.#deleteIfExpired(key, value);
71095
+ if (deleted === false) {
71096
+ yield item;
71097
+ }
71098
+ }
71099
+ }
71100
+
71101
+ get(key) {
71102
+ if (this.#cache.has(key)) {
71103
+ const item = this.#cache.get(key);
71104
+ return this.#getItemValue(key, item);
71105
+ }
71106
+
71107
+ if (this.#oldCache.has(key)) {
71108
+ const item = this.#oldCache.get(key);
71109
+ if (this.#deleteIfExpired(key, item) === false) {
71110
+ this.#moveToRecent(key, item);
71111
+ return item.value;
71112
+ }
71113
+ }
71114
+ }
71115
+
71116
+ set(key, value, {maxAge = this.#maxAge} = {}) {
71117
+ const expiry = typeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY
71118
+ ? (Date.now() + maxAge)
71119
+ : undefined;
71120
+
71121
+ if (this.#cache.has(key)) {
71122
+ this.#cache.set(key, {
71123
+ value,
71124
+ expiry,
71125
+ });
71126
+ } else {
71127
+ this.#set(key, {value, expiry});
71128
+ }
71129
+
71130
+ return this;
71131
+ }
71132
+
71133
+ has(key) {
71134
+ if (this.#cache.has(key)) {
71135
+ return !this.#deleteIfExpired(key, this.#cache.get(key));
71136
+ }
71137
+
71138
+ if (this.#oldCache.has(key)) {
71139
+ return !this.#deleteIfExpired(key, this.#oldCache.get(key));
71140
+ }
71141
+
71142
+ return false;
71143
+ }
71144
+
71145
+ peek(key) {
71146
+ if (this.#cache.has(key)) {
71147
+ return this.#peek(key, this.#cache);
71148
+ }
71149
+
71150
+ if (this.#oldCache.has(key)) {
71151
+ return this.#peek(key, this.#oldCache);
71152
+ }
71153
+ }
71154
+
71155
+ delete(key) {
71156
+ const deleted = this.#cache.delete(key);
71157
+ if (deleted) {
71158
+ this.#size--;
71159
+ }
71160
+
71161
+ return this.#oldCache.delete(key) || deleted;
71162
+ }
71163
+
71164
+ clear() {
71165
+ this.#cache.clear();
71166
+ this.#oldCache.clear();
71167
+ this.#size = 0;
71168
+ }
71169
+
71170
+ resize(newSize) {
71171
+ if (!(newSize && newSize > 0)) {
71172
+ throw new TypeError('`maxSize` must be a number greater than 0');
71173
+ }
71174
+
71175
+ const items = [...this.#entriesAscending()];
71176
+ const removeCount = items.length - newSize;
71177
+ if (removeCount < 0) {
71178
+ this.#cache = new Map(items);
71179
+ this.#oldCache = new Map();
71180
+ this.#size = items.length;
71181
+ } else {
71182
+ if (removeCount > 0) {
71183
+ this.#emitEvictions(items.slice(0, removeCount));
71184
+ }
71185
+
71186
+ this.#oldCache = new Map(items.slice(removeCount));
71187
+ this.#cache = new Map();
71188
+ this.#size = 0;
71189
+ }
71190
+
71191
+ this.#maxSize = newSize;
71192
+ }
71193
+
71194
+ * keys() {
71195
+ for (const [key] of this) {
71196
+ yield key;
71197
+ }
71198
+ }
71199
+
71200
+ * values() {
71201
+ for (const [, value] of this) {
71202
+ yield value;
71203
+ }
71204
+ }
71205
+
71206
+ * [Symbol.iterator]() {
71207
+ for (const item of this.#cache) {
71208
+ const [key, value] = item;
71209
+ const deleted = this.#deleteIfExpired(key, value);
71210
+ if (deleted === false) {
71211
+ yield [key, value.value];
71212
+ }
71213
+ }
71214
+
71215
+ for (const item of this.#oldCache) {
71216
+ const [key, value] = item;
71217
+ if (!this.#cache.has(key)) {
71218
+ const deleted = this.#deleteIfExpired(key, value);
71219
+ if (deleted === false) {
71220
+ yield [key, value.value];
71221
+ }
71222
+ }
71223
+ }
71224
+ }
71225
+
71226
+ * entriesDescending() {
71227
+ let items = [...this.#cache];
71228
+ for (let i = items.length - 1; i >= 0; --i) {
71229
+ const item = items[i];
71230
+ const [key, value] = item;
71231
+ const deleted = this.#deleteIfExpired(key, value);
71232
+ if (deleted === false) {
71233
+ yield [key, value.value];
71234
+ }
71235
+ }
71236
+
71237
+ items = [...this.#oldCache];
71238
+ for (let i = items.length - 1; i >= 0; --i) {
71239
+ const item = items[i];
71240
+ const [key, value] = item;
71241
+ if (!this.#cache.has(key)) {
71242
+ const deleted = this.#deleteIfExpired(key, value);
71243
+ if (deleted === false) {
71244
+ yield [key, value.value];
71245
+ }
71246
+ }
71247
+ }
71248
+ }
71249
+
71250
+ * entriesAscending() {
71251
+ for (const [key, value] of this.#entriesAscending()) {
71252
+ yield [key, value.value];
71253
+ }
71254
+ }
71255
+
71256
+ get size() {
71257
+ if (!this.#size) {
71258
+ return this.#oldCache.size;
71259
+ }
71260
+
71261
+ let oldCacheSize = 0;
71262
+ for (const key of this.#oldCache.keys()) {
71263
+ if (!this.#cache.has(key)) {
71264
+ oldCacheSize++;
71265
+ }
71266
+ }
71267
+
71268
+ return Math.min(this.#size + oldCacheSize, this.#maxSize);
71269
+ }
71270
+
71271
+ get maxSize() {
71272
+ return this.#maxSize;
71273
+ }
71274
+
71275
+ entries() {
71276
+ return this.entriesAscending();
71277
+ }
71278
+
71279
+ forEach(callbackFunction, thisArgument = this) {
71280
+ for (const [key, value] of this.entriesAscending()) {
71281
+ callbackFunction.call(thisArgument, value, key, this);
71282
+ }
71283
+ }
71284
+
71285
+ get [Symbol.toStringTag]() {
71286
+ return 'QuickLRU';
71287
+ }
71288
+
71289
+ toString() {
71290
+ return `QuickLRU(${this.size}/${this.maxSize})`;
71291
+ }
71292
+
71293
+ [Symbol.for('nodejs.util.inspect.custom')]() {
71294
+ return this.toString();
71295
+ }
71296
+ }
71297
+
71298
+ function createInMemoryCache(params) {
71299
+ const cache = new QuickLRU({ maxSize: params.maxSize, maxAge: params.ttl });
71300
+ return {
71301
+ get: async (key) => {
71302
+ return cache.get(key);
71303
+ },
71304
+ set: async (key, value, ttl) => {
71305
+ cache.set(key, value, { maxAge: ttl ?? params.ttl });
71306
+ },
71307
+ clear: async () => {
71308
+ cache.clear();
71309
+ },
71310
+ delete: async (key) => {
71311
+ cache.delete(key);
71312
+ }
71313
+ };
71314
+ }
71315
+
71026
71316
  /**
71027
71317
  * creates empty basic message
71028
71318
  *
@@ -93705,8 +93995,9 @@ var PolygonIdSdk = (function (exports) {
93705
93995
  * @public
93706
93996
  * @param {Array<EthConnectionConfig>} _configs - list of ethereum network connections
93707
93997
  */
93708
- constructor(_configs) {
93998
+ constructor(_configs, _opts) {
93709
93999
  this._configs = _configs;
94000
+ this._stateStorage = new EthStateStorage(_configs, _opts?.stateStorageOptions);
93710
94001
  }
93711
94002
  /**
93712
94003
  * resolve is a method to resolve a credential status from the blockchain.
@@ -93737,8 +94028,7 @@ var PolygonIdSdk = (function (exports) {
93737
94028
  const issuerId = DID.idFromDID(issuer);
93738
94029
  let latestIssuerState;
93739
94030
  try {
93740
- const ethStorage = this._getStateStorageForIssuer(issuerId);
93741
- const latestStateInfo = await ethStorage.getLatestStateById(issuerId.bigInt());
94031
+ const latestStateInfo = await this._stateStorage.getLatestStateById(issuerId.bigInt());
93742
94032
  if (!latestStateInfo.state) {
93743
94033
  throw new Error('state contract returned empty state');
93744
94034
  }
@@ -93804,13 +94094,6 @@ var PolygonIdSdk = (function (exports) {
93804
94094
  }
93805
94095
  return network;
93806
94096
  }
93807
- // TODO: is dirty hack for mock in tests.
93808
- // need to pass to constructor list of state stores not list of network configs
93809
- _getStateStorageForIssuer(issuerId) {
93810
- const issuerChainId = getChainId(DID.blockchainFromId(issuerId), DID.networkIdFromId(issuerId));
93811
- const ethStorage = new EthStateStorage(this.networkByChainId(issuerChainId));
93812
- return ethStorage;
93813
- }
93814
94097
  _getOnChainRevocationStorageForIssuer(chainId, contractAddress) {
93815
94098
  const networkConfig = this.networkByChainId(chainId);
93816
94099
  const onChainCaller = new OnChainRevocationStorage(networkConfig, contractAddress);
@@ -96082,6 +96365,300 @@ var PolygonIdSdk = (function (exports) {
96082
96365
  };
96083
96366
  }
96084
96367
 
96368
+ const defaultEthConnectionConfig = {
96369
+ url: 'http://localhost:8545',
96370
+ defaultGasLimit: 600000,
96371
+ minGasPrice: '0',
96372
+ maxGasPrice: '100000000000',
96373
+ confirmationBlockCount: 5,
96374
+ confirmationTimeout: 600000,
96375
+ contractAddress: '',
96376
+ receiptTimeout: 600000,
96377
+ rpcResponseTimeout: 5000,
96378
+ waitReceiptCycleTime: 30000,
96379
+ waitBlockCycleTime: 3000
96380
+ };
96381
+ /**
96382
+ *
96383
+ *
96384
+ * @public
96385
+ * @class EthStateStorage
96386
+ * @implements implements IStateStorage interface
96387
+ */
96388
+ class EthStateStorage {
96389
+ /**
96390
+ * Creates an instance of EthStateStorage.
96391
+ * @param {EthConnectionConfig} [ethConfig=defaultEthConnectionConfig]
96392
+ */
96393
+ constructor(ethConfig, options) {
96394
+ this.ethConfig = ethConfig;
96395
+ this._disableCache = false;
96396
+ const config = Array.isArray(ethConfig) ? ethConfig[0] : ethConfig;
96397
+ this.provider = new JsonRpcProvider(config.url);
96398
+ this.stateContract = new Contract(config.contractAddress, abi$3, this.provider);
96399
+ this._transactionService = new TransactionService(this.getRpcProvider());
96400
+ // Store cache options for later use
96401
+ this._latestStateCacheOptions = {
96402
+ ttl: options?.latestStateCacheOptions?.ttl ?? DEFAULT_PROOF_VERIFY_DELAY / 2,
96403
+ maxSize: options?.latestStateCacheOptions?.maxSize ?? DEFAULT_CACHE_MAX_SIZE
96404
+ };
96405
+ this._stateCacheOptions = {
96406
+ notReplacedTtl: options?.stateCacheOptions?.notReplacedTtl ??
96407
+ DEFAULT_PROOF_VERIFY_DELAY / 2,
96408
+ replacedTtl: options?.stateCacheOptions?.replacedTtl ?? DEFAULT_PROOF_VERIFY_DELAY,
96409
+ maxSize: options?.stateCacheOptions?.maxSize ?? DEFAULT_CACHE_MAX_SIZE
96410
+ };
96411
+ this._rootCacheOptions = {
96412
+ replacedTtl: options?.rootCacheOptions?.replacedTtl ?? DEFAULT_AUTH_VERIFY_DELAY,
96413
+ notReplacedTtl: options?.rootCacheOptions?.notReplacedTtl ??
96414
+ DEFAULT_AUTH_VERIFY_DELAY / 2,
96415
+ maxSize: options?.rootCacheOptions?.maxSize ?? DEFAULT_CACHE_MAX_SIZE
96416
+ };
96417
+ this._gistProofCacheOptions = {
96418
+ ttl: DEFAULT_AUTH_VERIFY_DELAY / 2,
96419
+ maxSize: options?.gistProofCacheOptions?.maxSize ?? DEFAULT_CACHE_MAX_SIZE
96420
+ };
96421
+ // Initialize cache instances
96422
+ this._latestStateResolveCache =
96423
+ options?.latestStateCacheOptions?.cache ??
96424
+ createInMemoryCache({
96425
+ maxSize: this._latestStateCacheOptions.maxSize,
96426
+ ttl: this._latestStateCacheOptions.ttl
96427
+ });
96428
+ this._stateResolveCache =
96429
+ options?.stateCacheOptions?.cache ??
96430
+ createInMemoryCache({
96431
+ maxSize: this._stateCacheOptions.maxSize,
96432
+ ttl: this._stateCacheOptions.replacedTtl
96433
+ });
96434
+ this._rootResolveCache =
96435
+ options?.rootCacheOptions?.cache ??
96436
+ createInMemoryCache({
96437
+ maxSize: this._rootCacheOptions.maxSize,
96438
+ ttl: this._rootCacheOptions.replacedTtl
96439
+ });
96440
+ this._gistProofResolveCache =
96441
+ options?.gistProofCacheOptions?.cache ??
96442
+ createInMemoryCache({
96443
+ maxSize: this._gistProofCacheOptions.maxSize,
96444
+ ttl: this._gistProofCacheOptions.ttl
96445
+ });
96446
+ this._disableCache = options?.disableCache ?? false;
96447
+ }
96448
+ /** {@inheritdoc IStateStorage.getLatestStateById} */
96449
+ async getLatestStateById(id) {
96450
+ const cacheKey = this.getLatestStateCacheKey(id);
96451
+ if (!this._disableCache) {
96452
+ // Check cache first
96453
+ const cachedResult = await this._latestStateResolveCache?.get(cacheKey);
96454
+ if (cachedResult) {
96455
+ return cachedResult;
96456
+ }
96457
+ }
96458
+ const { stateContract } = this.getStateContractAndProviderForId(id);
96459
+ const rawData = await stateContract.getStateInfoById(id);
96460
+ const stateInfo = {
96461
+ id: BigInt(rawData[0]),
96462
+ state: BigInt(rawData[1]),
96463
+ replacedByState: BigInt(rawData[2]),
96464
+ createdAtTimestamp: BigInt(rawData[3]),
96465
+ replacedAtTimestamp: BigInt(rawData[4]),
96466
+ createdAtBlock: BigInt(rawData[5]),
96467
+ replacedAtBlock: BigInt(rawData[6])
96468
+ };
96469
+ !this._disableCache &&
96470
+ (await this._latestStateResolveCache?.set(cacheKey, stateInfo, this._latestStateCacheOptions.ttl));
96471
+ return stateInfo;
96472
+ }
96473
+ /** {@inheritdoc IStateStorage.getStateInfoByIdAndState} */
96474
+ async getStateInfoByIdAndState(id, state) {
96475
+ const cacheKey = this.getStateCacheKey(id, state);
96476
+ if (!this._disableCache) {
96477
+ // Check cache first
96478
+ const cachedResult = await this._stateResolveCache?.get(cacheKey);
96479
+ if (cachedResult) {
96480
+ return cachedResult;
96481
+ }
96482
+ }
96483
+ const { stateContract } = this.getStateContractAndProviderForId(id);
96484
+ const rawData = await stateContract.getStateInfoByIdAndState(id, state);
96485
+ const stateInfo = {
96486
+ id: BigInt(rawData[0]),
96487
+ state: BigInt(rawData[1]),
96488
+ replacedByState: BigInt(rawData[2]),
96489
+ createdAtTimestamp: BigInt(rawData[3]),
96490
+ replacedAtTimestamp: BigInt(rawData[4]),
96491
+ createdAtBlock: BigInt(rawData[5]),
96492
+ replacedAtBlock: BigInt(rawData[6])
96493
+ };
96494
+ const ttl = stateInfo.replacedAtTimestamp === 0n
96495
+ ? this._stateCacheOptions.notReplacedTtl
96496
+ : this._stateCacheOptions.replacedTtl;
96497
+ !this._disableCache && (await this._stateResolveCache?.set(cacheKey, stateInfo, ttl));
96498
+ return stateInfo;
96499
+ }
96500
+ /** {@inheritdoc IStateStorage.publishState} */
96501
+ async publishState(proof, signer) {
96502
+ const stateTransitionPubSig = new StateTransitionPubSignals();
96503
+ stateTransitionPubSig.pubSignalsUnmarshal(byteEncoder$1.encode(JSON.stringify(proof.pub_signals)));
96504
+ const { userId, oldUserState, newUserState, isOldStateGenesis } = stateTransitionPubSig;
96505
+ const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
96506
+ const contract = stateContract.connect(signer);
96507
+ const preparedZkpProof = prepareZkpProof(proof.proof);
96508
+ const payload = [
96509
+ userId.bigInt().toString(),
96510
+ oldUserState.bigInt().toString(),
96511
+ newUserState.bigInt().toString(),
96512
+ isOldStateGenesis,
96513
+ preparedZkpProof.a,
96514
+ preparedZkpProof.b,
96515
+ preparedZkpProof.c
96516
+ ];
96517
+ const feeData = await provider.getFeeData();
96518
+ const maxFeePerGas = defaultEthConnectionConfig.maxFeePerGas
96519
+ ? BigInt(defaultEthConnectionConfig.maxFeePerGas)
96520
+ : feeData.maxFeePerGas;
96521
+ const maxPriorityFeePerGas = defaultEthConnectionConfig.maxPriorityFeePerGas
96522
+ ? BigInt(defaultEthConnectionConfig.maxPriorityFeePerGas)
96523
+ : feeData.maxPriorityFeePerGas;
96524
+ const gasLimit = await contract.transitState.estimateGas(...payload);
96525
+ const txData = await contract.transitState.populateTransaction(...payload);
96526
+ const request = {
96527
+ to: txData.to,
96528
+ data: txData.data,
96529
+ gasLimit,
96530
+ maxFeePerGas,
96531
+ maxPriorityFeePerGas
96532
+ };
96533
+ const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
96534
+ return txnHash;
96535
+ }
96536
+ /** {@inheritdoc IStateStorage.publishStateGeneric} */
96537
+ async publishStateGeneric(signer, userStateTransitionInfo) {
96538
+ const { userId, oldUserState, newUserState, isOldStateGenesis, methodId, methodParams } = userStateTransitionInfo;
96539
+ const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
96540
+ const contract = stateContract.connect(signer);
96541
+ const feeData = await provider.getFeeData();
96542
+ const maxFeePerGas = defaultEthConnectionConfig.maxFeePerGas
96543
+ ? BigInt(defaultEthConnectionConfig.maxFeePerGas)
96544
+ : feeData.maxFeePerGas;
96545
+ const maxPriorityFeePerGas = defaultEthConnectionConfig.maxPriorityFeePerGas
96546
+ ? BigInt(defaultEthConnectionConfig.maxPriorityFeePerGas)
96547
+ : feeData.maxPriorityFeePerGas;
96548
+ const payload = [
96549
+ userId.bigInt().toString(),
96550
+ oldUserState.bigInt().toString(),
96551
+ newUserState.bigInt().toString(),
96552
+ isOldStateGenesis,
96553
+ methodId,
96554
+ methodParams //'0x'
96555
+ ];
96556
+ const gasLimit = await contract.transitStateGeneric.estimateGas(...payload);
96557
+ const txData = await contract.transitStateGeneric.populateTransaction(...payload);
96558
+ const request = {
96559
+ to: txData.to,
96560
+ data: txData.data,
96561
+ gasLimit,
96562
+ maxFeePerGas,
96563
+ maxPriorityFeePerGas
96564
+ };
96565
+ const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
96566
+ return txnHash;
96567
+ }
96568
+ /** {@inheritdoc IStateStorage.getGISTProof} */
96569
+ async getGISTProof(id) {
96570
+ const cacheKey = this.getGistProofCacheKey(id);
96571
+ if (!this._disableCache) {
96572
+ // Check cache first
96573
+ const cachedResult = await this._gistProofResolveCache?.get(cacheKey);
96574
+ if (cachedResult) {
96575
+ return cachedResult;
96576
+ }
96577
+ }
96578
+ const { stateContract } = this.getStateContractAndProviderForId(id);
96579
+ const data = await stateContract.getGISTProof(id);
96580
+ const stateProof = {
96581
+ root: BigInt(data.root.toString()),
96582
+ existence: data.existence,
96583
+ siblings: data.siblings?.map((sibling) => BigInt(sibling.toString())),
96584
+ index: BigInt(data.index.toString()),
96585
+ value: BigInt(data.value.toString()),
96586
+ auxExistence: data.auxExistence,
96587
+ auxIndex: BigInt(data.auxIndex.toString()),
96588
+ auxValue: BigInt(data.auxValue.toString())
96589
+ };
96590
+ !this._disableCache &&
96591
+ (await this._gistProofResolveCache?.set(cacheKey, stateProof, this._gistProofCacheOptions.ttl));
96592
+ return stateProof;
96593
+ }
96594
+ /** {@inheritdoc IStateStorage.getGISTRootInfo} */
96595
+ async getGISTRootInfo(root, id) {
96596
+ const cacheKey = this.getRootCacheKey(root);
96597
+ if (!this._disableCache) {
96598
+ // Check cache first
96599
+ const cachedResult = await this._rootResolveCache?.get(cacheKey);
96600
+ if (cachedResult) {
96601
+ return cachedResult;
96602
+ }
96603
+ }
96604
+ const { stateContract } = this.getStateContractAndProviderForId(id);
96605
+ const data = await stateContract.getGISTRootInfo(root);
96606
+ const rootInfo = {
96607
+ root: BigInt(data.root.toString()),
96608
+ replacedByRoot: BigInt(data.replacedByRoot.toString()),
96609
+ createdAtTimestamp: BigInt(data.createdAtTimestamp.toString()),
96610
+ replacedAtTimestamp: BigInt(data.replacedAtTimestamp.toString()),
96611
+ createdAtBlock: BigInt(data.createdAtBlock.toString()),
96612
+ replacedAtBlock: BigInt(data.replacedAtBlock.toString())
96613
+ };
96614
+ const ttl = rootInfo.replacedAtTimestamp == 0n
96615
+ ? this._rootCacheOptions.notReplacedTtl
96616
+ : this._rootCacheOptions.replacedTtl;
96617
+ !this._disableCache && (await this._rootResolveCache?.set(cacheKey, rootInfo, ttl));
96618
+ return rootInfo;
96619
+ }
96620
+ /** {@inheritdoc IStateStorage.getRpcProvider} */
96621
+ getRpcProvider() {
96622
+ return this.provider;
96623
+ }
96624
+ /** enable caching */
96625
+ enableCache() {
96626
+ this._disableCache = false;
96627
+ }
96628
+ /** disable caching */
96629
+ disableCache() {
96630
+ this._disableCache = true;
96631
+ }
96632
+ getStateContractAndProviderForId(id) {
96633
+ const idTyped = Id.fromBigInt(id);
96634
+ const chainId = getChainId(DID.blockchainFromId(idTyped), DID.networkIdFromId(idTyped));
96635
+ const config = this.networkByChainId(chainId);
96636
+ const provider = new JsonRpcProvider(config.url);
96637
+ const stateContract = new Contract(config.contractAddress, abi$3, provider);
96638
+ return { stateContract, provider };
96639
+ }
96640
+ networkByChainId(chainId) {
96641
+ const config = Array.isArray(this.ethConfig) ? this.ethConfig : [this.ethConfig];
96642
+ const network = config.find((c) => c.chainId === chainId);
96643
+ if (!network) {
96644
+ throw new Error(`chainId "${chainId}" not supported`);
96645
+ }
96646
+ return network;
96647
+ }
96648
+ getGistProofCacheKey(id) {
96649
+ return `gist-${id.toString()}`;
96650
+ }
96651
+ getLatestStateCacheKey(id) {
96652
+ return `latest-${id.toString()}`;
96653
+ }
96654
+ getStateCacheKey(id, state) {
96655
+ return `${id.toString()}-${state.toString()}`;
96656
+ }
96657
+ getRootCacheKey(root) {
96658
+ return root.toString();
96659
+ }
96660
+ }
96661
+
96085
96662
  var abi$1 = [
96086
96663
  {
96087
96664
  inputs: [
@@ -97417,7 +97994,7 @@ var PolygonIdSdk = (function (exports) {
97417
97994
  },
97418
97995
  {
97419
97996
  internalType: "address",
97420
- name: "owner",
97997
+ name: "creator",
97421
97998
  type: "address"
97422
97999
  }
97423
98000
  ],
@@ -100581,21 +101158,6 @@ var PolygonIdSdk = (function (exports) {
100581
101158
  return erc20Contract.decimals();
100582
101159
  }
100583
101160
 
100584
- /**
100585
- * Type of MerkleTree
100586
- *
100587
- * @enum {number}
100588
- */
100589
- exports.MerkleTreeType = void 0;
100590
- (function (MerkleTreeType) {
100591
- // Claims is merkle tree type for claims tree
100592
- MerkleTreeType[MerkleTreeType["Claims"] = 0] = "Claims";
100593
- // Revocations is merkle tree type for revocations tree
100594
- MerkleTreeType[MerkleTreeType["Revocations"] = 1] = "Revocations";
100595
- // Roots is merkle tree type for roots tree
100596
- MerkleTreeType[MerkleTreeType["Roots"] = 2] = "Roots";
100597
- })(exports.MerkleTreeType || (exports.MerkleTreeType = {}));
100598
-
100599
101161
  /**
100600
101162
  * search errors
100601
101163
  *
@@ -100866,136 +101428,6 @@ var PolygonIdSdk = (function (exports) {
100866
101428
  ? exports.SupportedDataFormat.Boolean
100867
101429
  : exports.SupportedDataFormat.String;
100868
101430
 
100869
- const MERKLE_TREE_TYPES = [
100870
- exports.MerkleTreeType.Claims,
100871
- exports.MerkleTreeType.Revocations,
100872
- exports.MerkleTreeType.Roots
100873
- ];
100874
- const createMerkleTreeMetaInfo = (identifier) => {
100875
- const treesMeta = [];
100876
- for (let index = 0; index < MERKLE_TREE_TYPES.length; index++) {
100877
- const mType = MERKLE_TREE_TYPES[index];
100878
- const treeId = `${identifier}+${mType}`;
100879
- treesMeta.push({ treeId, identifier, type: mType });
100880
- }
100881
- return treesMeta;
100882
- };
100883
-
100884
- /**
100885
- *
100886
- *
100887
- * @public
100888
- * @class InMemoryMerkleTreeStorage
100889
- * @implements implements IMerkleTreeStorage interface
100890
- */
100891
- class InMemoryMerkleTreeStorage {
100892
- /**
100893
- * Creates an instance of InMemoryMerkleTreeStorage.
100894
- * @param {number} _mtDepth
100895
- */
100896
- constructor(_mtDepth) {
100897
- this.mtDepth = _mtDepth;
100898
- this._data = {};
100899
- }
100900
- /** create trees in the memory*/
100901
- async createIdentityMerkleTrees(identifier) {
100902
- if (!identifier) {
100903
- identifier = `${v4()}`;
100904
- }
100905
- if (this._data[identifier]) {
100906
- throw new Error(`Present merkle tree meta information in the store for current identifier ${identifier}`);
100907
- }
100908
- this._data[identifier] = [];
100909
- const treesMeta = [];
100910
- MERKLE_TREE_TYPES.forEach((t) => {
100911
- const treeId = identifier.concat('+' + t.toString());
100912
- const tree = new Merkletree(new InMemoryDB(str2Bytes(treeId)), true, this.mtDepth);
100913
- const metaInfo = { treeId, identifier: identifier, type: t };
100914
- this._data[identifier].push({ tree, metaInfo });
100915
- treesMeta.push(metaInfo);
100916
- });
100917
- return treesMeta;
100918
- }
100919
- /** get trees meta info from the memory */
100920
- async getIdentityMerkleTreesInfo(identifier) {
100921
- return this._data[identifier].map((treeWithInfo) => treeWithInfo.metaInfo);
100922
- }
100923
- /** get merkle tree by identifier and type from memory */
100924
- async getMerkleTreeByIdentifierAndType(identifier, mtType) {
100925
- const treeWithMeta = this._data[identifier].find((treeWithInfo) => treeWithInfo.metaInfo.type == mtType);
100926
- if (!treeWithMeta) {
100927
- throw new Error(`Merkle tree not found for identifier ${identifier} and type ${mtType}`);
100928
- }
100929
- return treeWithMeta.tree;
100930
- }
100931
- /** adds entry to merkle tree in the memory */
100932
- async addToMerkleTree(identifier, mtType, hindex, hvalue) {
100933
- for (let index = 0; index < this._data[identifier].length; index++) {
100934
- if (this._data[identifier][index].metaInfo.type === mtType) {
100935
- await this._data[identifier][index].tree.add(hindex, hvalue);
100936
- }
100937
- }
100938
- }
100939
- /** bind merkle tree identifier in memory */
100940
- async bindMerkleTreeToNewIdentifier(oldIdentifier, newIdentifier) {
100941
- this._data[newIdentifier] = [...this._data[oldIdentifier]];
100942
- delete this._data[oldIdentifier];
100943
- this._data[newIdentifier].forEach((treeWithMeta) => {
100944
- treeWithMeta.metaInfo.identifier = newIdentifier;
100945
- });
100946
- }
100947
- }
100948
-
100949
- /**
100950
- * Storage Errors definition
100951
- *
100952
- * @enum {number}
100953
- */
100954
- var StorageErrors;
100955
- (function (StorageErrors) {
100956
- StorageErrors["ItemNotFound"] = "item not found";
100957
- })(StorageErrors || (StorageErrors = {}));
100958
-
100959
- /* eslint-disable @typescript-eslint/no-explicit-any */
100960
- /**
100961
- * Generic Memory Data Source
100962
- *
100963
- * @public
100964
- * @class InMemoryDataSource - class
100965
- * @template Type
100966
- */
100967
- class InMemoryDataSource {
100968
- constructor() {
100969
- this._data = [];
100970
- }
100971
- /** saves in the memory */
100972
- async save(key, value, keyName = 'id') {
100973
- const itemIndex = this._data.findIndex((i) => i[keyName] === key);
100974
- if (itemIndex === -1) {
100975
- this._data.push(value);
100976
- }
100977
- else {
100978
- this._data[itemIndex] = value;
100979
- }
100980
- }
100981
- /** gets value from from the memory */
100982
- async get(key, keyName = 'id') {
100983
- return this._data.find((t) => t[keyName] === key);
100984
- }
100985
- /** loads from value from the memory */
100986
- async load() {
100987
- return this._data;
100988
- }
100989
- /** deletes from value from the memory */
100990
- async delete(key, keyName = 'id') {
100991
- const newData = this._data.filter((i) => i[keyName] !== key);
100992
- if (newData.length === this._data.length) {
100993
- throw new Error(`${StorageErrors.ItemNotFound} to delete: ${key}`);
100994
- }
100995
- this._data = newData;
100996
- }
100997
- }
100998
-
100999
101431
  /* eslint-disable @typescript-eslint/no-explicit-any */
101000
101432
  /**
101001
101433
  * Storage in the browser, uses local storage
@@ -101447,9 +101879,16 @@ var PolygonIdSdk = (function (exports) {
101447
101879
  await this._profileDataSource.save(element.id, element);
101448
101880
  }
101449
101881
  }
101882
+ /**
101883
+ * @deprecated The method should not be used. It returns only one profile per verifier, which can potentially restrict business use cases
101884
+ * Use getProfilesByVerifier instead.
101885
+ */
101450
101886
  async getProfileByVerifier(verifier) {
101451
101887
  return this._profileDataSource.get(verifier, 'verifier');
101452
101888
  }
101889
+ async getProfilesByVerifier(verifier, tags) {
101890
+ return (await this._profileDataSource.load()).filter((p) => p.verifier === verifier && (!tags || tags.every((tag) => p.tags?.includes(tag))));
101891
+ }
101453
101892
  async getProfileById(profileId) {
101454
101893
  return this._profileDataSource.get(profileId);
101455
101894
  }
@@ -103652,18 +104091,23 @@ var PolygonIdSdk = (function (exports) {
103652
104091
  return { nonce: profile.nonce, genesisDID: DID.parse(profile.genesisIdentifier) };
103653
104092
  }
103654
104093
  /** {@inheritDoc IIdentityWallet.createProfile} */
103655
- async createProfile(did, nonce, verifier) {
104094
+ async createProfile(did, nonce, verifier, tags) {
103656
104095
  const profileDID = generateProfileDID(did, nonce);
103657
104096
  const identityProfiles = await this._storage.identity.getProfilesByGenesisIdentifier(did.string());
103658
- const existingProfile = identityProfiles.find((p) => p.nonce == nonce || p.verifier == verifier);
103659
- if (existingProfile) {
104097
+ const profilesForTagAndVerifier = await this._storage.identity.getProfilesByVerifier(verifier, tags);
104098
+ if (profilesForTagAndVerifier.length) {
104099
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS);
104100
+ }
104101
+ const existingProfileWithNonce = identityProfiles.find((p) => p.nonce == nonce);
104102
+ if (existingProfileWithNonce) {
103660
104103
  throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS);
103661
104104
  }
103662
104105
  await this._storage.identity.saveProfile({
103663
104106
  id: profileDID.string(),
103664
104107
  nonce,
103665
104108
  genesisIdentifier: did.string(),
103666
- verifier
104109
+ verifier,
104110
+ tags
103667
104111
  });
103668
104112
  return profileDID;
103669
104113
  }
@@ -103682,9 +104126,17 @@ var PolygonIdSdk = (function (exports) {
103682
104126
  const key = await this._kms.createKeyFromSeed(keyType, N$2(32));
103683
104127
  return key;
103684
104128
  }
104129
+ /**
104130
+ * @deprecated The method should not be used. It returns only one profile per verifier, which can potentially restrict business use cases
104131
+ * {@inheritDoc IIdentityWallet.getProfileByVerifier}
104132
+ */
103685
104133
  async getProfileByVerifier(verifier) {
103686
104134
  return this._storage.identity.getProfileByVerifier(verifier);
103687
104135
  }
104136
+ /** {@inheritDoc IIdentityWallet.getProfilesByVerifier} */
104137
+ async getProfilesByVerifier(verifier, tags) {
104138
+ return this._storage.identity.getProfilesByVerifier(verifier, tags);
104139
+ }
103688
104140
  /** {@inheritDoc IIdentityWallet.getDIDTreeModel} */
103689
104141
  async getDIDTreeModel(did) {
103690
104142
  const didStr = did.string();
@@ -104172,6 +104624,7 @@ var PolygonIdSdk = (function (exports) {
104172
104624
  exports.CredentialStatusResolverRegistry = CredentialStatusResolverRegistry;
104173
104625
  exports.CredentialStorage = CredentialStorage;
104174
104626
  exports.CredentialWallet = CredentialWallet;
104627
+ exports.DEFAULT_CACHE_MAX_SIZE = DEFAULT_CACHE_MAX_SIZE;
104175
104628
  exports.DIDDocumentJSONSchema = DIDDocumentJSONSchema;
104176
104629
  exports.DataPrepareHandlerFunc = DataPrepareHandlerFunc;
104177
104630
  exports.DidDocumentCredentialStatusResolver = DidDocumentCredentialStatusResolver;
@@ -104282,6 +104735,7 @@ var PolygonIdSdk = (function (exports) {
104282
104735
  exports.createAuthorizationRequestWithMessage = createAuthorizationRequestWithMessage;
104283
104736
  exports.createDiscoveryFeatureDiscloseMessage = createDiscoveryFeatureDiscloseMessage;
104284
104737
  exports.createDiscoveryFeatureQueryMessage = createDiscoveryFeatureQueryMessage;
104738
+ exports.createInMemoryCache = createInMemoryCache;
104285
104739
  exports.createPayment = createPayment;
104286
104740
  exports.createPaymentRequest = createPaymentRequest;
104287
104741
  exports.createProblemReportMessage = createProblemReportMessage;