UNPKG

@0xpolygonid/js-sdk

Version:
1 lines 1.19 MB
{"version":3,"sources":["../../../src/index.ts","../../../src/kms/kms.ts","../../../src/kms/key-providers/bjj-provider.ts","../../../src/kms/store/abstract-key-store.ts","../../../src/kms/store/memory-key-store.ts","../../../src/kms/store/types.ts","../../../src/kms/store/local-storage-key-store.ts","../../../src/kms/store/indexed-db-key-store.ts","../../../src/kms/provider-helpers.ts","../../../src/utils/encoding.ts","../../../src/utils/object.ts","../../../src/utils/did-helper.ts","../../../src/utils/message-bus.ts","../../../src/utils/compare-func.ts","../../../src/utils/payments/solana.ts","../../../src/verifiable/proof.ts","../../../src/verifiable/constants.ts","../../../src/verifiable/credential.ts","../../../src/credentials/utils.ts","../../../src/verifiable/core-utils.ts","../../../src/verifiable/presentation.ts","../../../src/verifiable/schema.ts","../../../src/utils/payments/evm.ts","../../../src/kms/key-providers/ed25519-provider.ts","../../../src/kms/key-providers/secp256k1-provider.ts","../../../src/kms/key-providers/rsa-oaep-key-provider.ts","../../../src/kms/key-providers/p384-provider.ts","../../../src/identity/identity-wallet.ts","../../../src/identity/common.ts","../../../src/schema-processor/utils.ts","../../../src/schema-processor/json/parser.ts","../../../src/schema-processor/json/validator.ts","../../../src/schema-processor/jsonld/parser.ts","../../../src/schema-processor/jsonld/cache.ts","../../../src/storage/blockchain/state.ts","../../../src/circuits/common.ts","../../../src/circuits/models.ts","../../../src/circuits/comparer.ts","../../../src/circuits/atomic-query-mtp-v2.ts","../../../src/circuits/atomic-query-mtp-v2-on-chain.ts","../../../src/circuits/atomic-query-sig-v2.ts","../../../src/circuits/atomic-query-v3.ts","../../../src/circuits/atomic-query-v3-on-chain.ts","../../../src/circuits/atomic-query-sig-v2-on-chain.ts","../../../src/circuits/auth-v2.ts","../../../src/circuits/state-transition.ts","../../../src/circuits/linked-multi-query.ts","../../../src/circuits/auth-v3.ts","../../../src/storage/blockchain/abi/State.json","../../../src/blockchain/transaction-service.ts","../../../src/storage/blockchain/common.ts","../../../src/storage/memory/merkletree.ts","../../../src/storage/entities/mt.ts","../../../src/storage/utils.ts","../../../src/storage/memory/data-source.ts","../../../node_modules/quick-lru/index.js","../../../src/storage/memory/cache-lru.ts","../../../src/iden3comm/constants.ts","../../../src/storage/memory/proof-storage.ts","../../../src/iden3comm/packageManager.ts","../../../src/iden3comm/utils/did.ts","../../../src/iden3comm/utils/accept-profile.ts","../../../src/iden3comm/utils/did-doc-builder.ts","../../../src/iden3comm/utils/jwk.ts","../../../src/iden3comm/packers/anon-crypt.ts","../../../src/iden3comm/packers/jws.ts","../../../src/iden3comm/packers/plain.ts","../../../src/iden3comm/packers/zkp.ts","../../../src/iden3comm/errors.ts","../../../src/iden3comm/types/protocol/credentials.ts","../../../src/iden3comm/types/protocol/contract-request.ts","../../../src/iden3comm/types/protocol/discovery-protocol.ts","../../../src/iden3comm/handlers/auth.ts","../../../src/iden3comm/handlers/common.ts","../../../src/iden3comm/handlers/message-handler.ts","../../../src/storage/blockchain/onchain-revocation.ts","../../../src/storage/blockchain/abi/CredentialStatusResolver.json","../../../src/credentials/status/on-chain-revocation.ts","../../../src/storage/blockchain/errors.ts","../../../src/credentials/status/reverse-sparse-merkle-tree.ts","../../../src/credentials/status/sparse-merkle-tree.ts","../../../src/credentials/status/resolver.ts","../../../src/credentials/status/agent-revocation.ts","../../../src/credentials/status/credential-status-publisher.ts","../../../src/credentials/status/did-resolver-revocation.ts","../../../src/credentials/credential-wallet.ts","../../../src/credentials/rhs.ts","../../../src/iden3comm/handlers/fetch.ts","../../../src/iden3comm/handlers/contract-request.ts","../../../src/iden3comm/handlers/refresh.ts","../../../src/iden3comm/handlers/revocation-status.ts","../../../src/iden3comm/handlers/credential-proposal.ts","../../../src/iden3comm/handlers/payment.ts","../../../src/iden3comm/handlers/discovery-protocol.ts","../../../src/iden3comm/handlers/problem-report.ts","../../../src/iden3comm/services/jose.ts","../../../src/iden3comm/services/key-resolver.ts","../../../src/iden3comm/notifications/index.ts","../../../src/iden3comm/notifications/types.ts","../../../src/iden3comm/notifications/push.ts","../../../src/storage/blockchain/onchain-zkp-verifier.ts","../../../src/storage/blockchain/abi/ZkpVerifier.json","../../../src/storage/blockchain/onchain-issuer.ts","../../../src/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.ts","../../../src/storage/blockchain/did-resolver-readonly-storage.ts","../../../src/storage/blockchain/erc20-helper.ts","../../../src/storage/blockchain/abi/ERC20Permit.json","../../../src/storage/blockchain/abi/ERC20.json","../../../src/storage/filters/jsonQuery.ts","../../../src/storage/local-storage/data-source.ts","../../../src/storage/local-storage/merkletree.ts","../../../src/storage/indexed-db/data-source.ts","../../../src/storage/indexed-db/merkletree.ts","../../../src/storage/shared/circuit-storage.ts","../../../src/storage/shared/credential-storage.ts","../../../src/storage/shared/identity-storage.ts","../../../src/storage/fs/circuits-storage.ts","../../../src/proof/proof-service.ts","../../../src/proof/common.ts","../../../src/proof/provers/prover.ts","../../../src/proof/provers/witness_calculator.ts","../../../src/proof/provers/inputs-generator.ts","../../../src/proof/verifiers/pub-signals-verifier.ts","../../../src/proof/verifiers/query.ts","../../../src/proof/verifiers/query-hash.ts"],"sourcesContent":["export * from './identity';\nexport * from './credentials';\nexport * from './kms';\nexport * from './storage';\nexport * from './verifiable';\nexport * from './schema-processor';\nexport * from './proof';\nexport * from './iden3comm';\nexport * from './circuits';\nexport * from './iden3comm';\nexport * from './utils';\nexport * from './blockchain';\nimport * as core from '@iden3/js-iden3-core';\nimport * as jsonLDMerklizer from '@iden3/js-jsonld-merklization';\nexport { core };\nexport { jsonLDMerklizer };\n","import { AbstractPrivateKeyStore, KmsKeyId, KmsKeyType } from './store';\n\n/**\n * KeyProvider is responsible for signing and creation of the keys\n *\n * @public\n * @interface IKeyProvider\n */\nexport interface IKeyProvider {\n /**\n * property to store key type\n *\n * @type {KmsKeyType}\n */\n keyType: KmsKeyType;\n\n /**\n * get all keys\n *\n * @returns list of keys\n */\n list(): Promise<\n {\n alias: string;\n key: string;\n }[]\n >;\n /**\n * gets public key by key id\n *\n * @param {KmsKeyId} keyID - kms key identifier\n * @returns `Promise<PublicKey>`\n */\n publicKey(keyID: KmsKeyId): Promise<string>;\n /**\n * sign data with kms key\n *\n * @param {KmsKeyId} keyId - key identifier\n * @param {Uint8Array} data - bytes payload\n * @param {{ [key: string]: unknown }} opts - additional options for signing\n * @returns `Promise<Uint8Array>`\n */\n sign(keyId: KmsKeyId, data: Uint8Array, opts?: { [key: string]: unknown }): Promise<Uint8Array>;\n\n /**\n * creates new key pair from given seed\n *\n * @param {Uint8Array} seed - seed\n * @returns `Promise<KmsKeyId>`\n */\n newPrivateKeyFromSeed(seed: Uint8Array): Promise<KmsKeyId>;\n\n /**\n * creates new key pair from given public key\n *\n * @param {JsonWebKey} privateKey - private key\n * @returns `Promise<KmsKeyId>`\n */\n newPrivateKey(): Promise<KmsKeyId>;\n\n /**\n * Verifies a message signature using the provided key ID.\n *\n * @param message - The message bytes to verify.\n * @param signatureHex - The signature in hexadecimal format.\n * @param keyId - The KMS key ID used to verify the signature.\n * @returns A promise that resolves to a boolean indicating whether the signature is valid.\n */\n verify(message: Uint8Array, signatureHex: string, keyId: KmsKeyId): Promise<boolean>;\n\n /**\n * get private key store\n *\n * @returns private key store\n */\n getPkStore(): Promise<AbstractPrivateKeyStore>;\n}\n/**\n * Key management system class contains different key providers.\n * allows to register custom provider, create key, get public key and sign\n *\n * @public\n * @class KMS - class\n */\nexport class KMS {\n private readonly _registry = new Map<KmsKeyType, IKeyProvider>();\n\n /**\n * register key provider in the KMS\n *\n * @param {KmsKeyType} keyType - kms key type\n * @param {IKeyProvider} keyProvider - key provider implementation\n */\n registerKeyProvider(keyType: KmsKeyType, keyProvider: IKeyProvider): void {\n if (this._registry.get(keyType)) {\n throw new Error('present keyType');\n }\n this._registry.set(keyType, keyProvider);\n }\n\n /**\n * generates a new key and returns it kms key id\n *\n * @param {KmsKeyType} keyType\n * @param {Uint8Array} bytes\n * @returns kms key id\n */\n async createKeyFromSeed(keyType: KmsKeyType, bytes: Uint8Array): Promise<KmsKeyId> {\n const keyProvider = this._registry.get(keyType);\n if (!keyProvider) {\n throw new Error(`keyProvider not found for: ${keyType}`);\n }\n return keyProvider.newPrivateKeyFromSeed(bytes);\n }\n\n async createKey(keyType: KmsKeyType): Promise<KmsKeyId> {\n const keyProvider = this._registry.get(keyType);\n if (!keyProvider) {\n throw new Error(`keyProvider not found for: ${keyType}`);\n }\n return keyProvider.newPrivateKey();\n }\n\n /**\n * gets public key for key id\n *\n * @param {KmsKeyId} keyId -- key id\n * @returns public key\n */\n async publicKey(keyId: KmsKeyId): Promise<string> {\n const keyProvider = this._registry.get(keyId.type);\n if (!keyProvider) {\n throw new Error(`keyProvider not found for: ${keyId.type}`);\n }\n\n return keyProvider.publicKey(keyId);\n }\n\n /**\n * sign Uint8Array with giv KmsKeyIden\n *\n * @param {KmsKeyId} keyId - key id\n * @param {Uint8Array} data - prepared data bytes\n * @returns `Promise<Uint8Array>` - return signature\n */\n async sign(\n keyId: KmsKeyId,\n data: Uint8Array,\n opts?: {\n [key: string]: unknown;\n }\n ): Promise<Uint8Array> {\n const keyProvider = this._registry.get(keyId.type);\n if (!keyProvider) {\n throw new Error(`keyProvider not found for: ${keyId.type}`);\n }\n\n return keyProvider.sign(keyId, data, opts);\n }\n\n /**\n * Verifies a signature against the provided data and key ID.\n *\n * @param data - The data to verify the signature against.\n * @param signatureHex - The signature to verify, in hexadecimal format.\n * @param keyId - The key ID to use for verification.\n * @returns A promise that resolves to a boolean indicating whether the signature is valid.\n */\n verify(data: Uint8Array, signatureHex: string, keyId: KmsKeyId): Promise<boolean> {\n const keyProvider = this._registry.get(keyId.type);\n if (!keyProvider) {\n throw new Error(`keyProvider not found for: ${keyId.type}`);\n }\n return keyProvider.verify(data, signatureHex, keyId);\n }\n\n /**\n * get all keys by key type\n *\n * @param keyType - Key type\n * @returns list of keys\n */\n list(keyType: KmsKeyType): Promise<\n {\n alias: string;\n key: string;\n }[]\n > {\n const keyProvider = this._registry.get(keyType);\n if (!keyProvider) {\n throw new Error(`keyProvider not found for: ${keyType}`);\n }\n\n return keyProvider.list();\n }\n\n /**\n * get key provider by key type\n *\n * @param keyType - Key type\n * @returns key provider\n */\n getKeyProvider(keyType: KmsKeyType): IKeyProvider | undefined {\n return this._registry.get(keyType);\n }\n}\n","import { Hex, PrivateKey, PublicKey, Signature } from '@iden3/js-crypto';\nimport { BytesHelper, checkBigIntInField } from '@iden3/js-iden3-core';\nimport { IKeyProvider } from '../kms';\nimport { AbstractPrivateKeyStore, KmsKeyId, KmsKeyType } from '../store';\n\nimport * as providerHelpers from '../provider-helpers';\nimport { hexToBytes } from '../../utils';\n\n/**\n * Provider for Baby Jub Jub keys\n * @public\n * @class BjjProvider\n * @implements implements IKeyProvider interface\n */\nexport class BjjProvider implements IKeyProvider {\n /**\n * key type that is handled by BJJ Provider\n * @type {KmsKeyType}\n */\n keyType: KmsKeyType;\n private keyStore: AbstractPrivateKeyStore;\n /**\n * Creates an instance of BjjProvider.\n * @param {KmsKeyType} keyType - kms key type\n * @param {AbstractPrivateKeyStore} keyStore - key store for kms\n */\n constructor(keyType: KmsKeyType, keyStore: AbstractPrivateKeyStore) {\n if (keyType !== KmsKeyType.BabyJubJub) {\n throw new Error('Key type must be BabyJubJub');\n }\n this.keyType = keyType;\n this.keyStore = keyStore;\n }\n\n /**\n * get private key store\n *\n * @returns private key store\n */\n async getPkStore(): Promise<AbstractPrivateKeyStore> {\n return this.keyStore;\n }\n /**\n * get all keys\n * @returns list of keys\n */\n async list(): Promise<\n {\n alias: string;\n key: string;\n }[]\n > {\n const allKeysFromKeyStore = await this.keyStore.list();\n return allKeysFromKeyStore.filter((key) => key.alias.startsWith(this.keyType));\n }\n\n /**\n * generates a baby jub jub key from a seed phrase\n * @param {Uint8Array} seed - byte array seed\n * @returns kms key identifier\n */\n async newPrivateKeyFromSeed(seed: Uint8Array): Promise<KmsKeyId> {\n const newKey: Uint8Array = new Uint8Array(32);\n newKey.set(Uint8Array.from(seed), 0);\n newKey.fill(seed.length, 32, 0);\n const privateKey: PrivateKey = new PrivateKey(seed);\n\n const publicKey = privateKey.public();\n\n const kmsId = {\n type: this.keyType,\n id: providerHelpers.keyPath(this.keyType, publicKey.hex())\n };\n await this.keyStore.importKey({ alias: kmsId.id, key: privateKey.hex() });\n\n return kmsId;\n }\n\n async newPrivateKey(): Promise<KmsKeyId> {\n const seed = globalThis.crypto.getRandomValues(new Uint8Array(32));\n return this.newPrivateKeyFromSeed(seed);\n }\n\n /**\n * Gets public key by kmsKeyId\n *\n * @param {KmsKeyId} keyId - key identifier\n */\n async publicKey(keyId: KmsKeyId): Promise<string> {\n const privateKey: PrivateKey = await this.privateKey(keyId);\n return privateKey.public().hex();\n }\n\n /**\n * signs prepared payload of size,\n * with a key id\n *\n * @param {KmsKeyId} keyId - key identifier\n * @param {Uint8Array} data - data to sign (32 bytes)\n * @returns Uint8Array signature\n */\n async sign(keyId: KmsKeyId, data: Uint8Array): Promise<Uint8Array> {\n if (data.length != 32) {\n throw new Error('data to sign is too large');\n }\n\n const i = BytesHelper.bytesToInt(data);\n if (!checkBigIntInField(i)) {\n throw new Error('data to sign is too large');\n }\n const privateKey = await this.privateKey(keyId);\n\n const signature = privateKey.signPoseidon(i);\n\n return signature.compress();\n }\n\n private async privateKey(keyId: KmsKeyId): Promise<PrivateKey> {\n const privateKeyHex = await this.keyStore.get({ alias: keyId.id });\n\n return new PrivateKey(Hex.decodeString(privateKeyHex));\n }\n\n async verify(message: Uint8Array, signatureHex: string, keyId: KmsKeyId): Promise<boolean> {\n const publicKey = await this.publicKey(keyId);\n\n return PublicKey.newFromCompressed(hexToBytes(publicKey)).verifyPoseidon(\n BytesHelper.bytesToInt(message),\n Signature.newFromCompressed(hexToBytes(signatureHex))\n );\n }\n}\n","/**\n * KeyStore that allows to import and get keys by alias.\n *\n * @abstract\n * @public\n * @class AbstractPrivateKeyStore\n */\nexport abstract class AbstractPrivateKeyStore {\n /**\n * imports key by alias\n *\n * @abstract\n * @param {{ alias: string; key: string }} args - key alias and hex representation\n * @returns `Promise<void>`\n */\n abstract importKey(args: { alias: string; key: string }): Promise<void>;\n\n /**\n * get key by alias\n *\n * @abstract\n * @param {{ alias: string }} args -key alias\n * @returns `Promise<string>`\n */\n abstract get(args: { alias: string }): Promise<string>;\n\n /**\n * get all keys\n *\n * @abstract\n * @returns `Promise<{ alias: string; key: string }[]>`\n */\n abstract list(): Promise<{ alias: string; key: string }[]>;\n}\n","import { AbstractPrivateKeyStore } from './abstract-key-store';\n\n/**\n * Key Store to use in memory\n *\n * @public\n * @class InMemoryPrivateKeyStore\n * @implements implements AbstractPrivateKeyStore interface\n */\nexport class InMemoryPrivateKeyStore implements AbstractPrivateKeyStore {\n private _data: Map<string, string>;\n constructor() {\n this._data = new Map<string, string>();\n }\n\n list(): Promise<{ alias: string; key: string }[]> {\n return Promise.resolve(Array.from(this._data).map(([alias, key]) => ({ alias, key })));\n }\n\n async get(args: { alias: string }): Promise<string> {\n const privateKey = this._data.get(args.alias);\n if (!privateKey) {\n throw new Error('no key under given alias');\n }\n return privateKey;\n }\n\n async importKey(args: { alias: string; key: string }): Promise<void> {\n this._data.set(args.alias, args.key);\n }\n}\n","import { TypedDataDomain, TypedDataField } from 'ethers';\n\n/**\n * Key type that can be used in the key management system\n *\n * @enum {number}\n */\nexport enum KmsKeyType {\n BabyJubJub = 'BJJ',\n Secp256k1 = 'Secp256k1',\n Ed25519 = 'Ed25519',\n RsaOaep256 = 'RSA-OAEP-256',\n P384 = 'P-384'\n}\n\n/**\n * ID of the key that describe contain key type\n *\n * @public\n * @interface KmsKeyId\n */\nexport interface KmsKeyId {\n type: KmsKeyType;\n id: string;\n}\n\nexport interface TypedData {\n domain: TypedDataDomain;\n types: Record<string, Array<TypedDataField>>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n message: Record<string, any>;\n}\n","import { AbstractPrivateKeyStore } from './abstract-key-store';\nimport { KmsKeyId } from './types';\n\n/**\n * Allows storing keys in the local storage of the browser\n * (NOT ENCRYPTED: DO NOT USE IN THE PRODUCTION)\n *\n * @public\n * @class LocalStoragePrivateKeyStore\n * @implements implements AbstractPrivateKeyStore interface\n */\nexport class LocalStoragePrivateKeyStore implements AbstractPrivateKeyStore {\n static readonly storageKey = 'keystore';\n\n /**\n * get all keys\n *\n * @abstract\n * @returns `Promise<{ alias: string; key: string }[]>`\n */\n list(): Promise<{ alias: string; key: string }[]> {\n const dataStr = localStorage.getItem(LocalStoragePrivateKeyStore.storageKey);\n if (!dataStr) {\n throw new Error('no key under given alias');\n }\n const data = JSON.parse(dataStr);\n return data.map((i: { id: string; value: string }) => ({ alias: i.id, key: i.value }));\n }\n /**\n * Gets key from the local storage\n *\n * @param {{ alias: string }} args\n * @returns hex string\n */\n async get(args: { alias: string }): Promise<string> {\n const dataStr = localStorage.getItem(LocalStoragePrivateKeyStore.storageKey);\n if (!dataStr) {\n throw new Error('no key under given alias');\n }\n const data = JSON.parse(dataStr);\n const privateKey = data.find((d: KmsKeyId) => d.id === args.alias);\n if (!privateKey) {\n throw new Error('no key under given alias');\n }\n return privateKey.value;\n }\n\n /**\n * Import key to the local storage\n *\n * @param {{ alias: string; key: string }} args - alias and private key in the hex\n * @returns void\n */\n async importKey(args: { alias: string; key: string }): Promise<void> {\n const dataStr = localStorage.getItem(LocalStoragePrivateKeyStore.storageKey);\n let data = [];\n if (dataStr) {\n data = JSON.parse(dataStr);\n }\n\n const index = data.findIndex((d: KmsKeyId) => d.id === args.alias);\n if (index > -1) {\n data[index].value = args.key;\n } else {\n data.push({ id: args.alias, value: args.key });\n }\n localStorage.setItem(LocalStoragePrivateKeyStore.storageKey, JSON.stringify(data));\n }\n}\n","import { UseStore, createStore, get, set, entries } from 'idb-keyval';\nimport { AbstractPrivateKeyStore } from './abstract-key-store';\n\n/**\n * Allows storing keys in the indexed db storage of the browser\n * (NOT ENCRYPTED: DO NOT USE IN THE PRODUCTION)\n *\n * @public\n * @class IndexedDBPrivateKeyStore\n * @implements implements AbstractPrivateKeyStore interface\n */\nexport class IndexedDBPrivateKeyStore implements AbstractPrivateKeyStore {\n static readonly storageKey = 'keystore';\n private readonly _store: UseStore;\n\n constructor() {\n this._store = createStore(\n `${IndexedDBPrivateKeyStore.storageKey}-db`,\n IndexedDBPrivateKeyStore.storageKey\n );\n }\n\n /**\n * get all keys\n *\n * @abstract\n * @returns `Promise<{ alias: string; key: string }[]>`\n */\n async list(): Promise<{ alias: string; key: string }[]> {\n const allEntries = await entries(this._store);\n return allEntries.map(([alias, key]) => ({ alias, key: key.value })) as unknown as {\n alias: string;\n key: string;\n }[];\n }\n\n /**\n * Gets key from the indexed db storage\n *\n * @param {{ alias: string }} args\n * @returns hex string\n */\n async get(args: { alias: string }): Promise<string> {\n const key = await get(args.alias, this._store);\n if (!key) {\n throw new Error('no key under given alias');\n }\n return key.value;\n }\n\n /**\n * Import key to the indexed db storage\n *\n * @param {{ alias: string; key: string }} args - alias and private key in the hex\n * @returns void\n */\n async importKey(args: { alias: string; key: string }): Promise<void> {\n await set(args.alias, { value: args.key }, this._store);\n }\n}\n","import { KmsKeyType } from './store';\n\n/**\n * builds key path\n *\n * @param {KmsKeyType} keyType - key type\n * @param {string} keyID - key id\n * @returns string path\n */\nexport function keyPath(keyType: KmsKeyType, keyID: string): string {\n const basePath = '';\n return basePath + String(keyType) + ':' + keyID;\n}\n","import { base58FromBytes, base58ToBytes as b58ToBytes, Hex } from '@iden3/js-crypto';\nimport { base64url, base64 } from 'rfc4648';\n\nexport const byteEncoder = new TextEncoder();\nexport const byteDecoder = new TextDecoder();\n\nexport function bytesToBase64url(b: Uint8Array, opts = { pad: false }): string {\n return base64url.stringify(b, opts);\n}\n\nexport function base64ToBytes(s: string, opts = { loose: true }): Uint8Array {\n return base64.parse(s, opts);\n}\n\nexport function bytesToBase64(b: Uint8Array, opts = { pad: false }): string {\n return base64.stringify(b, opts);\n}\n\nexport function base64UrlToBytes(s: string, opts = { loose: true }): Uint8Array {\n const inputBase64Url = s.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n return base64url.parse(inputBase64Url, opts);\n}\n\nexport function base58ToBytes(s: string): Uint8Array {\n return b58ToBytes(s);\n}\n\nexport function bytesToBase58(b: Uint8Array): string {\n return base58FromBytes(b);\n}\n\nexport function hexToBytes(s: string): Uint8Array {\n const input = s.startsWith('0x') ? s.substring(2) : s;\n return Hex.decodeString(input.toLowerCase());\n}\n\nexport function encodeBase64url(s: string, opts = { pad: false }): string {\n return base64url.stringify(byteEncoder.encode(s), opts);\n}\n\nexport function decodeBase64url(s: string, opts = { loose: true }): string {\n return byteDecoder.decode(base64url.parse(s, opts));\n}\n\nexport function bytesToHex(b: Uint8Array): string {\n return Hex.encodeString(b);\n}\n","/**\n * Merges two objects together, prioritizing the properties of the second object.\n * If a property exists in both objects, the value from the second object will be used.\n * @param credSubject - The first object to merge.\n * @param otherCredSubject - The second object to merge.\n * @returns A new object with the merged properties.\n */\n\nimport { JsonDocumentObject } from '../iden3comm';\n\nexport function mergeObjects(\n credSubject: JsonDocumentObject,\n otherCredSubject: JsonDocumentObject\n) {\n let result = {} as JsonDocumentObject;\n const credSubjectKeys = Object.keys(credSubject);\n\n for (const key of credSubjectKeys) {\n if (typeof otherCredSubject[key] !== 'undefined') {\n if (typeof credSubject[key] !== 'object' && typeof otherCredSubject[key] !== 'object') {\n throw new Error('Invalid query');\n }\n const subjectProperty = credSubject[key] as JsonDocumentObject;\n const otherSubjectProperty = otherCredSubject[key] as JsonDocumentObject;\n const propertyOperators = Object.keys(subjectProperty);\n const subjectPropertyResult: JsonDocumentObject = {};\n for (const operatorKey of propertyOperators) {\n if (typeof otherSubjectProperty[operatorKey] !== 'undefined') {\n const operatorValue1 = subjectProperty[operatorKey] as JsonDocumentObject;\n const operatorValue2 = otherSubjectProperty[operatorKey];\n subjectPropertyResult[operatorKey] = [\n ...new Set([\n ...((subjectPropertyResult[operatorKey] as Array<JsonDocumentObject>) ?? []),\n operatorValue1,\n ...(Array.isArray(operatorValue2) ? operatorValue2 : [operatorValue2])\n ])\n ];\n } else {\n subjectPropertyResult[operatorKey] = subjectProperty[operatorKey];\n }\n }\n result[key] = {\n ...(otherCredSubject[key] as JsonDocumentObject),\n ...subjectPropertyResult\n };\n }\n }\n\n // Add remaining keys from obj2\n result = { ...credSubject, ...otherCredSubject, ...result };\n return result;\n}\n","import { Hex } from '@iden3/js-crypto';\nimport { Id, buildDIDType, genesisFromEthAddress, DID } from '@iden3/js-iden3-core';\nimport { Hash } from '@iden3/js-merkletree';\nimport { DIDResolutionResult, VerificationMethod, DIDResolutionMetadata } from 'did-resolver';\nimport { keccak256 } from 'ethers';\nimport { hexToBytes } from './encoding';\n\n/**\n * Supported DID Document Signatures\n */\nexport enum DIDDocumentSignature {\n EthereumEip712Signature2021 = 'EthereumEip712Signature2021'\n}\n\n/**\n * Checks if state is genesis state\n *\n * @param {DID} did - did\n * @param {bigint|string} state - hash on bigInt or hex string format\n * @returns boolean\n */\nexport function isGenesisState(did: DID, state: bigint | string): boolean {\n if (typeof state === 'string') {\n state = Hash.fromHex(state).bigInt();\n }\n const id = DID.idFromDID(did);\n return getIsGenesisStateById(id, state);\n}\n\n/**\n * Checks if state is genesis state by id\n *\n * @param {Id} id - id\n * @param {bigint} state - hash as bigint\n * @returns boolean\n */\nexport function getIsGenesisStateById(id: Id, state: bigint): boolean {\n const { method, blockchain, networkId } = DID.decodePartsFromId(id);\n const type = buildDIDType(method, blockchain, networkId);\n const idFromState = Id.idGenesisFromIdenState(type, state);\n\n return id.bigInt().toString() === idFromState.bigInt().toString();\n}\n\n/**\n * Checks if DID is an ethereum identity\n *\n * @param {DID} did - did\n * @returns boolean\n */\nexport function isEthereumIdentity(did: DID): boolean {\n const issuerId = DID.idFromDID(did);\n try {\n Id.ethAddressFromId(issuerId);\n // is an ethereum identity\n return true;\n } catch {\n // not an ethereum identity (BabyJubJub or other)\n return false;\n }\n}\n\nexport const buildVerifierId = (\n address: string,\n info: { method: string; blockchain: string; networkId: string }\n): Id => {\n address = address.replace('0x', '');\n const ethAddrBytes = Hex.decodeString(address);\n const ethAddr = ethAddrBytes.slice(0, 20);\n const genesis = genesisFromEthAddress(ethAddr);\n\n const tp = buildDIDType(info.method, info.blockchain, info.networkId);\n\n return new Id(tp, genesis);\n};\n\nexport const validateDIDDocumentAuth = async (did: DID, resolverURL: string, state: Hash) => {\n const vm = await resolveDIDDocumentAuth(did, resolverURL, state);\n if (!vm) {\n throw new Error(`can't resolve DID document`);\n }\n // published or genesis\n if (\n !(vm as VerificationMethod & { published: string }).published &&\n !isGenesisState(did, state.bigInt())\n ) {\n throw new Error(`issuer state not published and not genesis`);\n }\n};\n\nexport const resolveDIDDocumentAuth = async (\n did: DID,\n resolveURL: string,\n state?: Hash\n): Promise<VerificationMethod | undefined> => {\n let url = `${resolveURL}/${encodeURIComponent(did.string())}`;\n if (state) {\n url += `?state=${state.hex()}`;\n }\n const resp = await fetch(url);\n const didResolutionRes = (await resp.json()) as DIDResolutionResult;\n return didResolutionRes.didDocument?.verificationMethod?.find(\n (i) => i.type === 'Iden3StateInfo2023'\n );\n};\n\nfunction emptyStateDID(did: DID) {\n const id = DID.idFromDID(did);\n const didType = buildDIDType(\n DID.methodFromId(id),\n DID.blockchainFromId(id),\n DID.networkIdFromId(id)\n );\n const identifier = Id.idGenesisFromIdenState(didType, 0n);\n const emptyDID = DID.parseFromId(identifier);\n\n return emptyDID;\n}\n\nexport const resolveDidDocument = async (\n did: DID,\n resolverUrl: string,\n opts?: {\n state?: Hash;\n gist?: Hash;\n signature?: DIDDocumentSignature;\n }\n): Promise<DIDResolutionMetadata> => {\n let didString = encodeURIComponent(did.string());\n // for gist resolve we have to `hide` user did (look into resolver implementation)\n const isGistRequest = opts?.gist && !opts.state;\n if (isGistRequest) {\n didString = encodeURIComponent(emptyStateDID(did).string());\n }\n let url = `${resolverUrl}/1.0/identifiers/${didString}`;\n\n if (opts?.signature) {\n url += `?signature=${opts.signature}`;\n }\n\n if (opts?.state) {\n url += `${url.includes('?') ? '&' : '?'}state=${opts.state.hex()}`;\n }\n\n if (opts?.gist) {\n url += `${url.includes('?') ? '&' : '?'}gist=${opts.gist.hex()}`;\n }\n try {\n const resp = await fetch(url);\n const data = await resp.json();\n return data;\n } catch (e) {\n throw new Error(`Failed to resolve DID document for ${did} ${e}`);\n }\n};\n\nconst _buildDIDFromEthAddress = (didType: Uint8Array, ethAddress: Uint8Array): DID => {\n const genesis = genesisFromEthAddress(ethAddress);\n const identifier = new Id(didType, genesis);\n return DID.parseFromId(identifier);\n};\n\nexport const buildDIDFromEthPubKey = (didType: Uint8Array, pubKeyEth: string): DID => {\n // Use Keccak-256 hash function to get public key hash\n const hashOfPublicKey = keccak256(hexToBytes(pubKeyEth));\n // Convert hash to buffer\n const ethAddressBuffer = hexToBytes(hashOfPublicKey);\n // Ethereum Address is '0x' concatenated with last 20 bytes\n // of the public key hash\n const ethAddr = ethAddressBuffer.slice(-20);\n return _buildDIDFromEthAddress(didType, ethAddr);\n};\n\nexport const buildDIDFromEthAddress = (didType: Uint8Array, ethAddress: string): DID => {\n return _buildDIDFromEthAddress(didType, hexToBytes(ethAddress));\n};\n","import PubSub from 'pubsub-js';\n\n/**\n * Represents an event in the SDK.\n */\ntype SdkEvent = string;\n\nexport const SDK_EVENTS: { [k: SdkEvent]: SdkEvent } = {\n TX_RECEIPT_ACCEPTED: 'TX_RECEIPT_ACCEPTED'\n};\n\n/**\n * Represents a topic in the SDK message bus.\n */\nexport type SdkTopic = keyof typeof SDK_EVENTS;\n\n/**\n * Represents a message bus that allows publishing and subscribing to topics.\n */\nexport class MessageBus {\n /**\n * The singleton instance of the MessageBus class.\n */\n private static instance: MessageBus;\n\n /**\n * Private constructor for the MessageBus class.\n */\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n private constructor() {}\n\n /**\n * Returns the singleton instance of the MessageBus class.\n * If the instance doesn't exist, it creates a new one.\n * @returns The singleton instance of the MessageBus class.\n */\n public static getInstance(): MessageBus {\n // If the instance doesn't exist, create it\n if (!MessageBus.instance) {\n MessageBus.instance = new MessageBus();\n }\n // Return the instance\n return MessageBus.instance;\n }\n\n /**\n * Publishes a message to the specified topic.\n *\n * @template T - The type of data being published.\n * @param {SdkTopic} topic - The topic to publish the message to.\n * @param {T} data - The data to be published.\n * @returns {boolean} - Returns true if the message was successfully published, false otherwise.\n */\n public publish<T>(topic: SdkTopic, data: T): boolean {\n return PubSub.publish(topic.toString(), data);\n }\n\n /**\n * Subscribes to a specific topic and registers a callback function to be executed when a message is published.\n *\n * @param topic - The topic to subscribe to.\n * @param callback - The callback function to be executed when a message is published.\n */\n public subscribe<T>(topic: SdkTopic, callback: (data: T) => void): string {\n return PubSub.subscribe(topic.toString(), (_, data) => callback(data));\n }\n\n /**\n * Subscribes to a specific topic and registers a callback function to be executed when a message is published.\n * The callback function is executed only once.\n *\n * @param topic - The topic to subscribe to.\n * @param callback - The callback function to be executed when a message is published.\n */\n public subscribeOnce<T>(topic: SdkTopic, callback: (data: T) => void): void {\n PubSub.subscribeOnce(topic.toString(), (_, data) => callback(data));\n }\n\n /**\n * Unsubscribes from a specific topic in the message bus.\n *\n * @param topic - The topic to unsubscribe from.\n * @returns A string or boolean indicating the success of the unsubscribe operation.\n */\n public unsubscribe(topic: SdkTopic): string | boolean {\n return PubSub.unsubscribe(topic.toString());\n }\n}\n","export const bigIntCompare = (a: bigint, b: bigint): number => {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n};\n","import { Schema, serialize } from 'borsh';\nimport {\n Iden3PaymentRailsSolanaRequestV1,\n Iden3PaymentRailsSolanaSPLRequestV1,\n Iden3SolanaEd25519SignatureV1,\n MultiChainPaymentConfigOption\n} from '../../iden3comm';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport {\n PaymentRequestDataType,\n SOLANA_CHAIN_REF,\n SupportedPaymentProofType\n} from '../../verifiable';\nimport { byteEncoder, bytesToHex } from '../encoding';\nimport { getUnixTimestamp } from '@iden3/js-iden3-core';\nimport { Keypair, PublicKey } from '@solana/web3.js';\nimport { Resolvable } from 'did-resolver';\n\nexport class SolanaNativePaymentRequest {\n version: Uint8Array;\n chainId: bigint;\n verifyingContract: Uint8Array;\n recipient: Uint8Array;\n amount: bigint;\n expirationDate: bigint;\n nonce: bigint;\n metadata: Uint8Array;\n\n constructor(fields: {\n version: Uint8Array;\n chainId: bigint;\n verifyingContract: Uint8Array;\n recipient: Uint8Array;\n amount: bigint;\n expirationDate: bigint;\n nonce: bigint;\n metadata: Uint8Array;\n }) {\n this.version = fields.version;\n this.chainId = fields.chainId;\n this.verifyingContract = fields.verifyingContract;\n this.recipient = fields.recipient;\n this.amount = fields.amount;\n this.expirationDate = fields.expirationDate;\n this.nonce = fields.nonce;\n this.metadata = fields.metadata;\n }\n}\n\nexport class SolanaSplPaymentRequest {\n version: Uint8Array;\n chainId: bigint;\n verifyingContract: Uint8Array;\n tokenAddress: Uint8Array;\n recipient: Uint8Array;\n amount: bigint;\n expirationDate: bigint;\n nonce: bigint;\n metadata: Uint8Array;\n\n constructor(fields: {\n version: Uint8Array;\n chainId: bigint;\n verifyingContract: Uint8Array;\n tokenAddress: Uint8Array;\n recipient: Uint8Array;\n amount: bigint;\n expirationDate: bigint;\n nonce: bigint;\n metadata: Uint8Array;\n }) {\n this.version = fields.version;\n this.chainId = fields.chainId;\n this.verifyingContract = fields.verifyingContract;\n this.tokenAddress = fields.tokenAddress;\n this.recipient = fields.recipient;\n this.amount = fields.amount;\n this.expirationDate = fields.expirationDate;\n this.nonce = fields.nonce;\n this.metadata = fields.metadata;\n }\n}\n\nexport const SolanaNativePaymentSchema = new Map([\n [\n SolanaNativePaymentRequest,\n {\n kind: 'struct',\n fields: [\n ['version', ['u8']],\n ['chainId', 'u64'],\n ['verifyingContract', ['u8', 32]],\n ['recipient', ['u8', 32]],\n ['amount', 'u64'],\n ['expirationDate', 'u64'],\n ['nonce', 'u64'],\n ['metadata', ['u8']]\n ]\n }\n ]\n]);\n\nexport const SolanaSplPaymentSchema = new Map([\n [\n SolanaSplPaymentRequest,\n {\n kind: 'struct',\n fields: [\n ['version', ['u8']],\n ['chainId', 'u64'],\n ['verifyingContract', ['u8', 32]],\n ['tokenAddress', ['u8', 32]],\n ['recipient', ['u8', 32]],\n ['amount', 'u64'],\n ['expirationDate', 'u64'],\n ['nonce', 'u64'],\n ['metadata', ['u8']]\n ]\n }\n ]\n]);\n\nexport class SolanaPaymentInstruction {\n recipient: Uint8Array;\n amount: bigint;\n expiration_date: bigint;\n nonce: bigint;\n metadata: Uint8Array;\n signature: Uint8Array;\n\n constructor(fields: {\n recipient: Uint8Array;\n amount: bigint;\n expiration_date: bigint;\n nonce: bigint;\n metadata: Uint8Array;\n signature: Uint8Array;\n }) {\n this.recipient = fields.recipient;\n this.amount = fields.amount;\n this.expiration_date = fields.expiration_date;\n this.nonce = fields.nonce;\n this.metadata = fields.metadata;\n this.signature = fields.signature;\n }\n}\n\nexport const SolanaPaymentInstructionSchema: Schema = new Map([\n [\n SolanaPaymentInstruction,\n {\n kind: 'struct',\n fields: [\n ['recipient', ['u8', 32]],\n ['amount', 'u64'],\n ['expiration_date', 'u64'],\n ['nonce', 'u64'],\n ['metadata', ['u8']],\n ['signature', [64]]\n ]\n }\n ]\n]);\n\n/**\n * @beta\n * buildSolanaPayment creates an Solana-based payment request and signs it using ed25519.\n * @param {Keypair} solSigner - Keypair for signing the payment request\n * @param {MultiChainPaymentConfigOption} option - payment option configuration\n * @param {string} chainId - EVM chain ID\n * @param {string} paymentRails - payment rails contract address\n * @param {string} recipient - recipient address\n * @param {bigint} amount - payment amount in smallest units\n * @param {Date} expirationDateRequired - expiration date\n * @param {bigint} nonce - unique nonce for the payment\n * @returns {Promise<Iden3PaymentRailsSolanaRequestV1 | Iden3PaymentRailsSolanaSPLRequestV1>} payment request object\n */\nexport const buildSolanaPayment = async (\n solSigner: Keypair,\n option: MultiChainPaymentConfigOption,\n chainId: string,\n paymentRails: string,\n recipient: string,\n amount: bigint,\n expirationDate: Date,\n nonce: bigint\n): Promise<Iden3PaymentRailsSolanaRequestV1 | Iden3PaymentRailsSolanaSPLRequestV1> => {\n let serialized: Uint8Array;\n const proofVersion =\n option.type === PaymentRequestDataType.Iden3PaymentRailsSolanaRequestV1\n ? 'SolanaEd25519NativeV1'\n : 'SolanaEd25519SPLV1';\n let chainRef = chainId;\n switch (chainId) {\n case '101':\n chainRef = SOLANA_CHAIN_REF.DEVNET;\n break;\n case '102':\n chainRef = SOLANA_CHAIN_REF.TESTNET;\n break;\n case '103':\n chainRef = SOLANA_CHAIN_REF.MAINNET;\n break;\n }\n if (option.type === PaymentRequestDataType.Iden3PaymentRailsSolanaRequestV1) {\n const request = new SolanaNativePaymentRequest({\n version: byteEncoder.encode(proofVersion),\n chainId: BigInt(chainId),\n verifyingContract: new PublicKey(paymentRails).toBytes(),\n recipient: new PublicKey(recipient).toBytes(),\n amount: BigInt(amount),\n expirationDate: BigInt(getUnixTimestamp(expirationDate)),\n nonce: nonce,\n metadata: byteEncoder.encode('0x')\n });\n serialized = serialize(SolanaNativePaymentSchema, request);\n } else {\n if (!option.contractAddress) {\n throw new Error(`failed request. no contract address for ${option.type} payment type`);\n }\n const request = new SolanaSplPaymentRequest({\n version: byteEncoder.encode(proofVersion),\n chainId: BigInt(chainId),\n verifyingContract: new PublicKey(paymentRails).toBytes(),\n tokenAddress: new PublicKey(option.contractAddress).toBytes(),\n recipient: new PublicKey(recipient).toBytes(),\n amount: BigInt(amount),\n expirationDate: BigInt(getUnixTimestamp(expirationDate)),\n nonce: nonce,\n metadata: byteEncoder.encode('0x')\n });\n serialized = serialize(SolanaSplPaymentSchema, request);\n }\n const privateKey = solSigner.secretKey.slice(0, 32);\n const signature = await ed25519.sign(serialized, privateKey);\n const proof: Iden3SolanaEd25519SignatureV1[] = [\n {\n type: SupportedPaymentProofType.SolanaEd25519Signature2025,\n proofPurpose: 'assertionMethod',\n proofValue: bytesToHex(signature),\n created: new Date().toISOString(),\n verificationMethod: `did:pkh:solana:${chainRef}:${solSigner.publicKey.toBase58()}`,\n domain: {\n version: proofVersion,\n chainId,\n verifyingContract: paymentRails\n }\n }\n ];\n const d: Iden3PaymentRailsSolanaRequestV1 = {\n type: PaymentRequestDataType.Iden3PaymentRailsSolanaRequestV1,\n '@context': [\n `https://schema.iden3.io/core/jsonld/payment.jsonld#${option.type}`,\n 'https://schema.iden3.io/core/jsonld/solanaEd25519.jsonld'\n ],\n recipient,\n amount: amount.toString(),\n expirationDate: expirationDate.toISOString(),\n nonce: nonce.toString(),\n metadata: '0x',\n proof\n };\n if (option.type === PaymentRequestDataType.Iden3PaymentRailsSolanaRequestV1) {\n return d;\n }\n\n return {\n ...d,\n type: option.type,\n tokenAddress: option.contractAddress || '',\n features: option.features || []\n } as Iden3PaymentRailsSolanaSPLRequestV1;\n};\n\nexport const serializeSolanaPaymentInstruction = (\n data: Iden3PaymentRailsSolanaRequestV1 | Iden3PaymentRailsSolanaSPLRequestV1\n): Uint8Array => {\n let serialized: Uint8Array;\n const proof = Array.isArray(data.proof) ? data.proof[0] : data.proof;\n const proofVersion =\n data.type === PaymentRequestDataType.Iden3PaymentRailsSolanaRequestV1\n ? 'SolanaEd25519NativeV1'\n : 'SolanaEd25519SPLV1';\n if (data.type === PaymentRequestDataType.Iden3PaymentRailsSolanaRequestV1) {\n const request = new SolanaNativePaymentRequest({\n version: byteEncoder.encode(proofVersion),\n chainId: BigInt(proof.domain.chainId),\n verifyingContract: new PublicKey(proof.domain.verifyingContract).toBytes(),\n recipient: new PublicKey(data.recipient).toBytes(),\n amount: BigInt(data.amount),\n expirationDate: BigInt(getUnixTimestamp(new Date(data.expirationDate))),\n nonce: BigInt(data.nonce),\n metadata: byteEncoder.encode('0x')\n });\n serialized = serialize(SolanaNativePaymentSchema, request);\n } else {\n const request = new SolanaSplPaymentRequest({\n version: byteEncoder.encode(proofVersion),\n chainId: BigInt(proof.domain.chainId),\n verifyingContract: new PublicKey(proof.domain.verifyingContract).toBytes(),\n tokenAddress: new PublicKey(data.tokenAddress).toBytes(),\n recipient: new PublicKey(data.recipient).toBytes(),\n amount: BigInt(data.amount),\n expirationDate: BigInt(getUnixTimestamp(new Date(data.expirationDate))),\n nonce: BigInt(data.nonce),\n metadata: byteEncoder.encode('0x')\n });\n serialized = serialize(SolanaSplPaymentSchema, request);\n }\n return serialized;\n};\nexport const verifyIden3SolanaPaymentRequest = async (\n data: Iden3PaymentRailsSolanaRequestV1 | Iden3PaymentRailsSolanaSPLRequestV1,\n resolver: Resolvable\n): Promise<boolean> => {\n const proof = Array.isArray(data.proof) ? data.proof[0] : data.proof;\n let serialized: Uint8Array;\n if (data.type === PaymentRequestDataType.Iden3PaymentRailsSolanaRequestV1) {\n const request = new SolanaNativePaymentRequest({\n version: byteEncoder.encode(proof.domain.version),\n chainId: BigInt(proof.domain.chainId),\n verifyingContract: new PublicKey(proof.domain.verifyingContract).toBytes(),\n recipient: new PublicKey(data.recipient).toBytes(),\n amount: BigInt(data.amount),\n expirationDate: BigInt(getUnixTimestamp(new Date(data.expirationDate))),\n nonce: BigInt(data.nonce),\n metadata: byteEncoder.encode('0x')\n });\n serialized = serialize(SolanaNativePaymentSchema, request);\n } else {\n const request = new SolanaSplPaymentRequest({\n version: byteEncoder.encode(proof.domain.version),\n chainId: BigInt(proof.domain.chainId),\n verifyingContract: new PublicKey(proof.domain.verifyingContract).toBytes(),\n tokenAddress: new PublicKey(data.tokenAddress).toBytes(),\n recipient: new PublicKey(data.recipient).toBytes(),\n amount: BigInt(data.amount),\n expirationDate: BigInt(getUnixTimestamp(new Date(data.expirationDate))),\n nonce: BigInt(data.nonce),\n metadata: byteEncoder.encode('0x')\n });\n serialized = serialize(SolanaSplPaymentSchema, request);\n }\n\n const { didDocument } = await resolver.resolve(proof.verificationMethod);\n let publicKeyMultibase;\n if (didDocument?.verificationMethod) {\n for (const verificationMethod of didDocument.verificationMethod) {\n if (verificationMethod.type === 'Ed25519VerificationKey2020') {\n publicKeyMultibase = verificationMethod.publicKeyMultibase;\n }\n }\n }\n\n if (!publicKeyMultibase) {\n throw new Error('No Ed25519VerificationKey2020 found in DID document');\n }\n\n return ed25519.verify(proof.proofValue, serialized, new PublicKey(publicKeyMultibase).toBytes());\n};\n","import { Hash, Proof } from '@iden3/js-merkletree';\nimport {\n ProofType,\n CredentialStatusType,\n RefreshServiceType,\n DisplayMethodType\n} from './constants';\nimport { TreeState } from '../circuits';\nimport { Hex, Signature } from '@iden3/js-crypto';\nimport { Claim, DID } from '@iden3/js-iden3-core';\nimport { JsonDocumentObject, JSONObject } from '../iden3comm';\n\n/**\n * Represents the published state of the issuer\n *\n * @public\n * @interface State\n */\nexport interface State {\n txId?: string;\n blockTimestamp?: number;\n blockNumber?: number;\n rootOfRoots: Hash;\n claimsTreeRoot: Hash;\n revocationTreeRoot: Hash;\n value: Hash;\n status?: string;\n}\n\n/**\n * Iden3SparseMerkleProof is a iden3 protocol merkle tree proof\n *\n * @public\n * @class Iden3SparseMerkleTreeProof\n */\nexport class Iden3SparseMerkleTreeProof {\n type: ProofType;\n issuerData: {\n id: DID;\n state: State;\n };\n mtp: Proof;\n coreClaim: Claim;\n /**\n * Creates an instance of Iden3SparseMerkleTreeProof.\n * @param {object} obj\n */\n constructor(obj: {\n issuerData: {\n id: DID;\n state: State;\n };\n mtp: Proof;\n coreClaim: Claim;\n }) {\n this.coreClaim = obj.coreClaim;\n this.issuerData = obj.issuerData;\n this.type = ProofType.Iden3SparseMerkleTreeProof;\n this.mtp = obj.mtp;\n }\n\n /**\n *\n *\n * @returns `json object in serialized presentation`\n */\n toJSON() {\n const issuerId = this.issuerData.id;\n return {\n issuerData: {\n id: issuerId.string(),\n state: {\n ...this.issuerData.state,\n rootOfRoots: this.issuerData.state.rootOfRoots.hex(),\n claimsTreeRoot: this.issuerData.state.claimsTreeRoot.hex(),\n revocationTreeRoot: this.issuerData.state.revocationTreeRoot.hex(),\n value: this.issuerData.state.value.hex()\n }\n },\n type: this.type,\n coreClaim: this.coreClaim.hex(),\n mtp: this.mtp.toJSON()\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static fromJSON(obj: any) {\n let mtp: Proof;\n if (obj?.mtp?.notEmpties && obj?.mtp?.depth && obj?.mtp?.siblings) {\n // legacy\n\n const ne = obj?.mtp?.notEmpties;\n const notEmpties = ne instanceof Uint8Array ? ne : new Uint8Array(Object.values(ne));\n const siblingsHashes = obj?.mtp?.siblings.map((h: unknown) =>\n Hash.fromString(JSON.stringify(h))\n );\n const allSiblings = Proof.buildAllSiblings(obj?.mtp?.depth, notEmpties, siblingsHashes);\n let nodeAux = obj.mtp.nodeAux || obj.mtp.node_aux;\n if (nodeAux) {\n nodeAux = {\n key: Hash.fromString(JSON.stringify(nodeAux.key)),\n value: Hash.fromString(JSON.stringify(nodeAux.value))\n };\n }\n mtp = new Proof({ ex