@0xpolygonid/js-sdk 1.37.2 → 1.37.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.
@@ -432,7 +432,7 @@ if (cid) {
432
432
  `?i="":(i!==""&&(i+=" "),i+=l)},showSharedRWMemory:function(){u()}}}),s=e;return new JF(o,s);function c(){let l="",d=o.exports.getMessageChar();for(;d!=0;)l+=String.fromCharCode(d),d=o.exports.getMessageChar();return l}function u(){let l=o.exports.getFieldNumLen32(),d=new Uint32Array(l);for(let h=0;h<l;h++)d[l-1-h]=o.exports.readSharedRWMemory(h);i!==""&&(i+=" "),i+=qF(d).toString()}}var JF=class{constructor(e,t){this.instance=e;this.instance=e,this.version=this.instance.exports.getVersion(),this.n32=this.instance.exports.getFieldNumLen32(),this.instance.exports.getRawPrime();let r=new Uint32Array(this.n32);for(let i=0;i<this.n32;i++)r[this.n32-1-i]=this.instance.exports.readSharedRWMemory(i);this.prime=qF(r),this.witnessSize=this.instance.exports.getWitnessSize(),this.sanityCheck=t}version;n32;prime;witnessSize;sanityCheck;circom_version(){return this.instance.exports.getVersion()}async _doCalculateWitness(e,t){this.instance.exports.init(this.sanityCheck||t?1:0);let r=Object.keys(e),i=0;if(r.forEach(o=>{let s=wDe(o),a=parseInt(s.slice(0,8),16),c=parseInt(s.slice(8,16),16),u=yDe(e[o]),l=this.instance.exports.getInputSignalSize(a,c);if(l<0)throw new Error(`Signal ${o} not found
433
433
  `);if(u.length<l)throw new Error(`Not enough values for input signal ${o}
434
434
  `);if(u.length>l)throw new Error(`Too many values for input signal ${o}
435
- `);for(let d=0;d<u.length;d++){let h=gDe(BigInt(u[d])%this.prime,this.n32);for(let f=0;f<this.n32;f++)this.instance.exports.writeSharedRWMemory(f,h[this.n32-1-f]);try{this.instance.exports.setInputSignal(a,c,d),i++}catch(f){throw new Error(f)}}}),i<this.instance.exports.getInputSize())throw new Error(`Not all inputs have been set. Only ${i} out of ${this.instance.exports.getInputSize()}`)}async calculateWitness(e,t){let r=[];await this._doCalculateWitness(e,t);for(let i=0;i<this.witnessSize;i++){this.instance.exports.getWitness(i);let o=new Uint32Array(this.n32);for(let s=0;s<this.n32;s++)o[this.n32-1-s]=this.instance.exports.readSharedRWMemory(s);r.push(qF(o))}return r}async calculateBinWitness(e,t){let r=new Uint32Array(this.witnessSize*this.n32),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t);for(let o=0;o<this.witnessSize;o++){this.instance.exports.getWitness(o);let s=o*this.n32;for(let a=0;a<this.n32;a++)r[s+a]=this.instance.exports.readSharedRWMemory(a)}return i}async calculateWTNSBin(e,t){let r=new Uint32Array(this.witnessSize*this.n32+this.n32+11),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t),i[0]=119,i[1]=116,i[2]=110,i[3]=115,r[1]=2,r[2]=2,r[3]=1;let o=this.n32*4,a=(8+o).toString(16);r[4]=parseInt(a.slice(0,8),16),r[5]=parseInt(a.slice(8,16),16),r[6]=o,this.instance.exports.getRawPrime();let c=7;for(let d=0;d<this.n32;d++)r[c+d]=this.instance.exports.readSharedRWMemory(d);c+=this.n32,r[c]=this.witnessSize,c++,r[c]=2,c++;let l=(o*this.witnessSize).toString(16);r[c]=parseInt(l.slice(0,8),16),r[c+1]=parseInt(l.slice(8,16),16),c+=2;for(let d=0;d<this.witnessSize;d++){this.instance.exports.getWitness(d);for(let h=0;h<this.n32;h++)r[c+h]=this.instance.exports.readSharedRWMemory(h);c+=this.n32}return i}};function gDe(n,e){let t=[],r=BigInt(4294967296);for(;n;)t.unshift(Number(n%r)),n=n/r;if(e){let i=e-t.length;for(;i>0;)t.unshift(0),i--}return t}function qF(n){let e=BigInt(0),t=BigInt(4294967296);for(let r=0;r<n.length;r++)e=e*t+BigInt(n[r]);return e}function yDe(n){let e=[];return t(e,n),e;function t(r,i){if(Array.isArray(i))for(let o=0;o<i.length;o++)t(r,i[o]);else r.push(i)}}function wDe(n){let e=BigInt(2)**BigInt(64),t=BigInt("0xCBF29CE484222325");for(let o=0;o<n.length;o++)t^=BigInt(n[o].charCodeAt()),t*=BigInt(1099511628211),t%=e;let r=t.toString(16),i=16-r.length;return r="0".repeat(i).concat(r),r}var II=class n{constructor(e){this._circuitStorage=e}static curveName="bn128";async verify(e,t){try{let r=await this._circuitStorage.loadCircuitData(t);if(!r.verificationKey)throw new Error(`verification file doesn't exist for circuit ${t}`);return GO(e,JSON.parse(lt.decode(r.verificationKey)))}catch(r){return console.log(r),!1}}async generate(e,t){let r=await this._circuitStorage.loadCircuitData(t);if(!r.wasm)throw new Error(`wasm file doesn't exist for circuit ${t}`);let i=await VF(r.wasm.buffer),o=JSON.parse(lt.decode(e)),s=await i.calculateWTNSBin(o,0);if(!r.provingKey)throw new Error(`proving file doesn't exist for circuit ${t}`);let{proof:a,publicSignals:c}=await KC.prove(r.provingKey,s);return await this.terminateCurve(),{proof:a,pub_signals:c}}async terminateCurve(){(await qE(n.curveName)).terminate()}};var QF=Object.values(fn),Xte=[0,1,2,3,4,5,6,16],_te=[1,2,3,4,5,6],Ah={credentialAtomicQueryMTPV2:{maxQueriesCount:1,supportedOperations:Xte},credentialAtomicQueryMTPV2OnChain:{maxQueriesCount:1,supportedOperations:_te},credentialAtomicQuerySigV2:{maxQueriesCount:1,supportedOperations:Xte},credentialAtomicQuerySigV2OnChain:{maxQueriesCount:1,supportedOperations:_te},"credentialAtomicQueryV3-beta.1":{maxQueriesCount:1,supportedOperations:QF},"credentialAtomicQueryV3OnChain-beta.1":{maxQueriesCount:1,supportedOperations:QF},authV2:{maxQueriesCount:0,supportedOperations:[]},authV3:{maxQueriesCount:0,supportedOperations:[]},"authV3-8-32":{maxQueriesCount:0,supportedOperations:[]},stateTransition:{maxQueriesCount:0,supportedOperations:[]},"linkedMultiQuery10-beta.1":{maxQueriesCount:10,supportedOperations:QF}},em=class{constructor(e,t,r){this._identityWallet=e;this._credentialWallet=t;this._stateStorage=r}async generateInputs(e){let{circuitId:t}=e.proofReq,r=`${t.split("-")[0]}PrepareInputs`;if(e.circuitQueries.length>Ah[t].maxQueriesCount)throw new Error(`circuit ${t} supports only ${Ah[t].maxQueriesCount} queries`);let o=this[r];if(!o)throw new Error(`inputs generator for ${t} not found`);return o(e)}async newCircuitClaimData(e){let t=e.credential.getIden3SparseMerkleTreeProof(),r=new cE;r.claim=e.credentialCoreClaim,r.issuerId=ve.idFromDID(ve.parse(e.credential.issuer)),t&&(r.proof=t.mtp,r.treeState={state:t.issuerData.state.value,claimsRoot:t.issuerData.state.claimsTreeRoot,revocationRoot:t.issuerData.state.revocationTreeRoot,rootOfRoots:t.issuerData.state.rootOfRoots});let i=e.credential.getBJJSignature2021Proof();if(i){let o=i.issuerData.id,s=jl(o,e.credential),{credentialStatus:a,mtp:c,authCoreClaim:u}=i.issuerData;if(!a)throw new Error("can't check the validity of issuer auth claim: no credential status in proof");if(!c)throw new Error("issuer auth credential must have a mtp proof");if(!u)throw new Error("issuer auth credential must have a core claim proof");let l={issuerGenesisState:i.issuerData.state,issuerDID:o,userDID:s},d=await this._credentialWallet.getRevocationStatus(a,l),h=qu(d);r.signatureProof={signature:i.signature,issuerAuthIncProof:{proof:i.issuerData.mtp,treeState:{state:i.issuerData.state.value,claimsRoot:i.issuerData.state.claimsTreeRoot,revocationRoot:i.issuerData.state.revocationTreeRoot,rootOfRoots:i.issuerData.state.rootOfRoots}},issuerAuthClaim:i.issuerData.authCoreClaim,issuerAuthNonRevProof:h}}return r}async prepareAuthBJJCredential(e,t){let{authCredential:r,incProof:i,nonRevProof:o}=await this._identityWallet.getActualAuthCredential(e,t),s=r.getCoreClaimFromProof("Iden3SparseMerkleTreeProof");if(!s)throw new Error("auth core claim is not defined for auth bjj credential");return{credential:r,incProof:i,nonRevProof:o,coreClaim:s}}credentialAtomicQueryMTPV2PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=qu(e.revStatus);let a=new uE;a.id=ve.idFromDID(t),a.requestID=BigInt(r.id);let c=o[0];return c.operator=this.transformV2QueryOperator(c.operator),a.query=c,a.claim={issuerID:s.issuerId,claim:s.claim,incProof:{proof:s.proof,treeState:s.treeState},nonRevProof:s.nonRevProof},a.currentTimeStamp=Ct(new Date),a.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),a.profileNonce=BigInt(i.authProfileNonce),a.skipClaimRevocationCheck=i.skipRevocation,this.checkOperatorSupport(r.circuitId,c.operator),a.inputsMarshal()};credentialAtomicQueryMTPV2OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e),a=await this.prepareAuthBJJCredential(t),c=await this.newCircuitClaimData({credential:a.credential,credentialCoreClaim:a.coreClaim});s.nonRevProof=qu(e.revStatus);let u=new dE,l=ve.idFromDID(t);u.id=ve.idFromDID(t),u.requestID=BigInt(r.id);let d=await this._stateStorage.getGISTProof(l.bigInt()),h=Ih(d);if(u.gistProof=h,c?.treeState&&(u.treeState={state:c?.treeState?.state,claimsRoot:c?.treeState?.claimsRoot,revocationRoot:c?.treeState?.revocationRoot,rootOfRoots:c?.treeState?.rootOfRoots}),u.authClaim=c.claim,u.authClaimIncMtp=c.proof,u.authClaimNonRevMtp=a.nonRevProof.proof,!i.challenge)throw new Error("challenge must be provided for onchain circuits");let f=await this._identityWallet.signChallenge(i.challenge,a.credential);u.signature=f,u.challenge=i.challenge;let m=o[0];return u.query=m,u.claim={issuerID:s.issuerId,claim:s.claim,incProof:{proof:s.proof,treeState:s.treeState},nonRevProof:s.nonRevProof},u.currentTimeStamp=Ct(new Date),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation,this.checkOperatorSupport(r.circuitId,m.operator),u.inputsMarshal()};credentialAtomicQuerySigV2PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=qu(e.revStatus);let a=new hE;a.id=ve.idFromDID(t),a.claim={issuerID:s?.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof},a.requestID=BigInt(r.id),a.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),a.profileNonce=BigInt(i.authProfileNonce),a.skipClaimRevocationCheck=i.skipRevocation;let c=o[0];return c.operator=this.transformV2QueryOperator(c.operator),a.query=c,a.currentTimeStamp=Ct(new Date),this.checkOperatorSupport(r.circuitId,c.operator),a.inputsMarshal()};credentialAtomicQuerySigV2OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e),a=await this.prepareAuthBJJCredential(t),c=await this.newCircuitClaimData({credential:a.credential,credentialCoreClaim:a.coreClaim});s.nonRevProof=qu(e.revStatus);let u=new bE,l=ve.idFromDID(t);u.id=l,u.claim={issuerID:s.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof},u.requestID=BigInt(r.id),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation;let d=o[0];u.query=d,u.currentTimeStamp=Ct(new Date),c.treeState&&(u.treeState={state:c.treeState?.state,claimsRoot:c.treeState?.claimsRoot,revocationRoot:c.treeState?.revocationRoot,rootOfRoots:c.treeState?.rootOfRoots});let h=await this._stateStorage.getGISTProof(l.bigInt()),f=Ih(h);if(u.gistProof=f,u.authClaim=c.claim,u.authClaimIncMtp=c.proof,u.authClaimNonRevMtp=a.nonRevProof.proof,!i.challenge)throw new Error("challenge must be provided for onchain circuits");let m=await this._identityWallet.signChallenge(i.challenge,a.credential);return u.signature=m,u.challenge=i.challenge,this.checkOperatorSupport(r.circuitId,d.operator),u.inputsMarshal()};credentialAtomicQueryV3PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=qu(e.revStatus);let a;switch(r.query.proofType){case"BJJSignature2021":a="BJJSignature2021";break;case"Iden3SparseMerkleTreeProof":a="Iden3SparseMerkleTreeProof";break;default:if(s.proof)a="Iden3SparseMerkleTreeProof";else if(s.signatureProof)a="BJJSignature2021";else throw Error("claim has no MTP or signature proof");break}let c=new mE;c.id=ve.idFromDID(t),c.claim={issuerID:s?.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof,incProof:{proof:s.proof,treeState:s.treeState}},c.requestID=BigInt(r.id),c.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),c.profileNonce=BigInt(i.authProfileNonce),c.skipClaimRevocationCheck=i.skipRevocation;let u=o[0];return u.values=[16,0].includes(u.operator)?[]:u.values,c.query=u,c.currentTimeStamp=Ct(new Date),c.proofType=a,c.linkNonce=i.linkNonce??BigInt(0),c.verifierID=i.verifierDid?ve.idFromDID(i.verifierDid):void 0,c.nullifierSessionID=r.params?.nullifierSessionId?BigInt(r.params?.nullifierSessionId?.toString()):BigInt(0),this.checkOperatorSupport(r.circuitId,u.operator),c.inputsMarshal()};credentialAtomicQueryV3OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=ve.idFromDID(t),a=await this.newCircuitClaimData(e);a.nonRevProof=qu(e.revStatus);let c;switch(r.query.proofType){case"BJJSignature2021":c="BJJSignature2021";break;case"Iden3SparseMerkleTreeProof":c="Iden3SparseMerkleTreeProof";break;default:if(a.proof)c="Iden3SparseMerkleTreeProof";else if(a.signatureProof)c="BJJSignature2021";else throw Error("claim has no MTP or signature proof");break}let u=new yE;u.id=ve.idFromDID(t),u.claim={issuerID:a?.issuerId,signatureProof:a.signatureProof,claim:a.claim,nonRevProof:a.nonRevProof,incProof:{proof:a.proof,treeState:a.treeState}},u.requestID=BigInt(r.id),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation;let l=o[0];l.values=[16,0].includes(l.operator)?[]:l.values,u.query=l,u.currentTimeStamp=Ct(new Date),u.proofType=c,u.linkNonce=i.linkNonce??BigInt(0),u.verifierID=i.verifierDid?ve.idFromDID(i.verifierDid):void 0,u.nullifierSessionID=r.params?.nullifierSessionId?BigInt(r.params?.nullifierSessionId?.toString()):BigInt(0);let d=gp(t);u.isBJJAuthEnabled=d?0:1,u.challenge=BigInt(i.challenge??0);let h=await this._stateStorage.getGISTProof(s.bigInt()),f=Ih(h);if(u.gistProof=f,u.isBJJAuthEnabled===1){let m=await this.prepareAuthBJJCredential(t),b=await this.newCircuitClaimData({credential:m.credential,credentialCoreClaim:m.coreClaim}),w=await this._identityWallet.signChallenge(u.challenge,m.credential);u.authClaim=b.claim,u.authClaimIncMtp=b.proof,u.authClaimNonRevMtp=m.nonRevProof.proof,u.treeState=b.treeState,u.signature=w}return this.checkOperatorSupport(r.circuitId,l.operator),u.inputsMarshal()};linkedMultiQuery10PrepareInputs=async({preparedCredential:e,params:t,proofReq:r,circuitQueries:i})=>{let o=await this.newCircuitClaimData(e);o.nonRevProof=qu(e.revStatus);let s=new cd;return s.linkNonce=t.linkNonce??BigInt(0),s.claim=o.claim,s.query=i,i.forEach(a=>{this.checkOperatorSupport(r.circuitId,a.operator)}),i.forEach(a=>{a.values=[16,0].includes(a.operator)?[]:a.values}),s.inputsMarshal()};transformV2QueryOperator(e){return e===16||e===0?1:e}checkOperatorSupport(e,t){if(!Ah[e].supportedOperations.includes(t))throw new Error(`operator ${sE(t)} is not supported by ${e}`)}};var bDe=1440*60*1e3;async function R8(n,e,t,r,i,o,s){let a=ve.parseFromId(r.issuerId);if(!(!n.allowedIssuers||n.allowedIssuers?.some(f=>f==="*"||f===a.string())))throw new Error("issuer is not in allowed list");if(!n.type)throw new Error("query type is missing");let u=await Gr.getTypeIDFromContext(JSON.stringify(t),n.type,{documentLoader:o});if(Wl(Me.encode(u)).bigInt()!==r.schemaHash.bigInt())throw new Error("schema that was used is not equal to requested in query");if(!n.skipClaimRevocationCheck&&r.isRevocationChecked===0)throw new Error("check revocation is required");$te(i,e);let d=bDe;if(s?.acceptedProofGenerationDelay&&(d=s.acceptedProofGenerationDelay),Date.now()-na(Number(r.timestamp)).getTime()>d)throw new Error("generated proof is outdated")}function $te(n,e){let t=Ah[n];if(e.length>t.maxQueriesCount)throw new Error(`circuit ${n} supports only ${Ah[n].maxQueriesCount} queries`)}function D8(n,e){if(!Ah[n].supportedOperations.includes(e))throw new Error(`circuit ${n} not support ${sE(e)} operator`)}function zF(n,e){if(n.operator!=fn.$noop){if(n.merklized===1){if(n.claimPathNotExists===1)throw new Error("proof doesn't contains target query key");if(n.claimPathKey!==e.claimPathKey)throw new Error("proof was generated for another path")}else if(n.slotIndex!==e.slotIndex)throw new Error("wrong claim slot was used in claim")}}function YF(n,e){if(n.operator!=0){if(n.operator===11&&!n.merklized)throw new Error("$exists operator is not supported for non-merklized credential");if(n.merklized===1){if(n.claimPathKey!==e.claimPathKey)throw new Error("proof was generated for another path")}else if(n.slotIndex!==e.slotIndex)throw new Error("wrong claim slot was used in claim")}}async function jF(n,e){if(e.operator!==1)throw new Error("empty credentialSubject request available only for equal operation");for(let i=1;i<e.value.length;i++)if(e.value[i]!==0n)throw new Error("empty credentialSubject request not available for array of values");let r=await Gr.newPath([qe.CREDENTIAL_SUBJECT_PATH]).mtEntry();if(e.claimPathKey!==r)throw new Error("proof doesn't contain credentialSubject in claimPathKey")}async function T8(n,e){if(e.operator!==n.operator)throw new Error("operator that was used is not equal to request");if(e.operator!==0){for(let t=0;t<e.value.length;t++)if(e.value[t]!==n.values[t]){if(e.value[t]===0n&&n.values[t]===void 0)continue;throw new Error("comparison value that was used is not equal to requested in query")}}}async function WF(n,e,t,r){if(await AI(n.fieldName,t,r)!==e.value[0])throw new Error("value that was used is not equal to requested in query");if(e.operator!==1)throw new Error("operator for selective disclosure must be $eq");for(let o=1;o<e.value.length;o++)if(e.value[o]!==0n)throw new Error("selective disclosure not available for array of values")}async function ZF(n,e,t,r){if(await AI(n.fieldName,t,r)!==e.operatorOutput)throw new Error("operator output should be equal to disclosed value");if(e.operator!==16)throw new Error("operator for selective disclosure must be $sd");for(let o=0;o<e.value.length;o++)if(e.value[o]!==0n)throw new Error("public signal values must be zero")}async function XF(n){if(n.operator!==0)throw new Error("empty credentialSubject request available only for $noop operation");for(let e=1;e<n.value.length;e++)if(n.value[e]!==0n)throw new Error("empty credentialSubject request not available for array of values")}var AI=async(n,e,t)=>{if(!e)throw new Error("verifiablePresentation is required for selective disclosure request");let r,i=JSON.stringify(e);try{r=await Ru.merklizeJSONLD(i,{documentLoader:t})}catch{throw new Error("can't merklize verifiablePresentation")}let o;try{let c=`verifiableCredential.credentialSubject.${n}`;o=await Gr.fromDocument(null,i,c,{documentLoader:t})}catch{throw new Error(`can't build path to '${n}' key`)}let s,a;try{({proof:s,value:a}=await r.proof(o))}catch{throw new Error(`can't get value by path '${n}'`)}if(!a)throw new Error(`can't get merkle value for field '${n}'`);if(!s.existence)throw new Error(`path [${o.parts}] doesn't exist in verifiablePresentation document`);return await a.mtEntry()};function EDe(n){let e=Array(n.length).fill("uint256");return BigInt(An.keccak256(An.solidityPacked(e,n)))&BigInt("0x0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")}function IDe(n,e){return(BigInt(An.keccak256(An.solidityPacked(["bytes","address"],[n,e])))&BigInt("0x0000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"))+BigInt("0x0001000000000000000000000000000000000000000000000000000000000000")}function ADe(n,e,t){return BigInt(An.keccak256(An.solidityPacked(["uint256[]","uint256[]","address"],[n,e,t])))}function xDe(n,e,t,r,i,o){let s=Qr(n,64),a=On.spongeHashX(s,6);return On.hash([e.bigInt(),BigInt(t),BigInt(r),BigInt(i),BigInt(o),a])}function _F(n,e,t,r,i,o,s,a,c,u){let l=Qr(n,cC),d=On.spongeHashX(l,6),h=On.hash([e.bigInt(),BigInt(t),BigInt(r),BigInt(i),BigInt(s),d]);return On.hash([h,BigInt(o),BigInt(a),BigInt(c),BigInt(u),0n])}var vDe=new Error("user state is not valid"),B8=0n,xI=class{constructor(e,t){this._documentLoader=e;this._stateStorage=t}async verify(e,t){let r=`${e.split("-")[0]}Verify`,i=this[r];if(!i)throw new Error(`public signals verifier for ${e} not found`);return i(t)}credentialAtomicQueryMTPV2Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s})=>{let a=new lE;if(a=a.pubSignalsUnmarshal(Me.encode(JSON.stringify(o))),!a.userID)throw new Error("user id is not presented in proof public signals");if(!a.requestID)throw new Error("requestId is not presented in proof public signals");let c={issuerId:a.issuerID,schemaHash:a.claimSchema,slotIndex:a.slotIndex,operator:a.operator,value:a.value,timestamp:a.timestamp,merklized:a.merklized,claimPathKey:a.claimPathKey,claimPathNotExists:a.claimPathNotExists,valueArraySize:a.getValueArrSize(),isRevocationChecked:a.isRevocationChecked};return await this.checkQueryV2Circuits("credentialAtomicQueryMTPV2",e,c,s,t),await this.checkStateExistenceForId(a.issuerID,a.issuerClaimIdenState),a.isRevocationChecked!==0&&await this.checkRevocationState(a.issuerID,a.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i,a.userID,a.requestID),a};credentialAtomicQuerySigV2Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s})=>{let a=new pE;a=a.pubSignalsUnmarshal(Me.encode(JSON.stringify(o)));let c={issuerId:a.issuerID,schemaHash:a.claimSchema,slotIndex:a.slotIndex,operator:a.operator,value:a.value,timestamp:a.timestamp,merklized:a.merklized,claimPathKey:a.claimPathKey,claimPathNotExists:a.claimPathNotExists,valueArraySize:a.getValueArrSize(),isRevocationChecked:a.isRevocationChecked};return await this.checkQueryV2Circuits("credentialAtomicQuerySigV2",e,c,s,t),await this.checkStateExistenceForId(a.issuerID,a.issuerAuthState),a.isRevocationChecked!==0&&await this.checkRevocationState(a.issuerID,a.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i,a.userID,a.requestID),a};credentialAtomicQueryV3Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s,params:a})=>{let c=new gE;c=c.pubSignalsUnmarshal(Me.encode(JSON.stringify(o)));let u={issuerId:c.issuerID,schemaHash:c.claimSchema,slotIndex:c.slotIndex,operator:c.operator,value:c.value,timestamp:c.timestamp,merklized:c.merklized,claimPathKey:c.claimPathKey,valueArraySize:c.getValueArrSize(),operatorOutput:c.operatorOutput,isRevocationChecked:c.isRevocationChecked};if(!e.type)throw new Error("proof query type is undefined");let l=this._documentLoader??Ho(),d;try{d=(await l(e.context??"")).document}catch{throw new Error("can't load schema for request query")}let h=await EI(e.type,JSON.stringify(d),e.credentialSubject,{documentLoader:l}),f="credentialAtomicQueryV3-beta.1";await R8(e,h,d,u,f,this._documentLoader,s);let m=h[0];if(D8(f,u.operator),m.operator===16)try{await ZF(m,u,t,l)}catch(H){throw new Error(`failed to validate selective disclosure: ${H.message}`)}else if(!m.fieldName&&m.operator==0)try{await XF(u)}catch(H){throw new Error(`failed to validate operators: ${H.message}`)}else try{await T8(m,u)}catch(H){throw new Error(`failed to validate operators: ${H.message}`)}YF(u,m);let{proofType:b,verifierID:w,nullifier:S,nullifierSessionID:T,linkID:G}=c;switch(e.proofType){case"BJJSignature2021":if(b!==1)throw new Error("wrong proof type for BJJSignature");break;case"Iden3SparseMerkleTreeProof":if(b!==2)throw new Error("wrong proof type for Iden3SparseMerkleTreeProof");break;default:}let U=BigInt(a?.nullifierSessionId??0);if(U!==0n){if(BigInt(S??0)===0n)throw new Error("nullifier should be provided for nullification and should not be 0");let H=a?.verifierDid;if(!H)throw new Error("verifierDid is required");let M=ve.idFromDID(H);if(w.bigInt()!=M.bigInt())throw new Error("wrong verifier is used for nullification");if(T!==U)throw new Error(`wrong verifier session id is used for nullification, expected ${U}, got ${T}`)}else if(T!==0n)throw new Error("Nullifier id is generated but wasn't requested");if(!e.groupId&&G!==0n)throw new Error("proof contains link id, but group id is not provided");if(e.groupId&&G===0n)throw new Error("proof doesn't contain link id, but group id is provided");return await this.checkStateExistenceForId(c.issuerID,c.issuerState),c.isRevocationChecked!==0&&await this.checkRevocationState(c.issuerID,c.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i,c.userID,c.requestID),c};authV2Verify=async({sender:e,challenge:t,pubSignals:r,opts:i})=>{let o=new Zs;o=o.pubSignalsUnmarshal(Me.encode(JSON.stringify(r)));let s=await this.checkGlobalState(o.GISTRoot,o.userID),a=Yr.DEFAULT_AUTH_VERIFY_DELAY;if(i?.acceptedStateTransitionDelay&&(a=i.acceptedStateTransitionDelay),!s.latest&&Date.now()-na(Number(s.transitionTimestamp)).getTime()>a)throw new Error("global state is outdated");return this.verifyIdOwnership(e,t,o.userID,o.challenge),new kn};linkedMultiQuery10Verify=async({query:e,verifiablePresentation:t,pubSignals:r})=>{let i=new xE;i=i.pubSignalsUnmarshal(Me.encode(JSON.stringify(r)));let o,s={documentLoader:this._documentLoader};try{o=(await s.documentLoader(e.context||"")).document}catch{throw new Error("can't load schema for request query")}let a=JSON.stringify(o),c=e.credentialSubject,u=await Gr.getTypeIDFromContext(a,e.type||"",s),l=Wl(Me.encode(u)),d=await EI(e.type||"",a,c,s),h=[],f=d[0]?.merklizedSchema?1:0;for(let w=0;w<cd.queryCount;w++){let S=d[w],T=S?.values??[],G=T.length,U=_F(T,l,S?.slotIndex??0,S?.operator??0,S?.claimPathKey.toString()??0,G,f,0,0,0);h.push({queryHash:U,queryMeta:S})}let m=(w,S)=>w.queryHash<S.queryHash?-1:w.queryHash>S.queryHash?1:0,b=i.circuitQueryHash.map((w,S)=>({queryHash:w,operatorOutput:i.operatorOutput[S]}));b.sort(m),h.sort(m);for(let w=0;w<cd.queryCount;w++){if(h[w].queryHash!=b[w].queryHash)throw new Error("query hashes do not match");if(h[w].queryMeta?.operator===16&&await AI(h[w].queryMeta.fieldName,t,this._documentLoader)!=b[w].operatorOutput)throw new Error("disclosed value is not in the proof outputs")}return i};verifyIdOwnership=(e,t,r,i)=>{if(ve.idFromDID(ve.parse(e)).string()!==r.string())throw new Error(`sender id is not used for proof creation, expected ${e}, user from public signals: ${r.string()}`);if(t!==i)throw new Error(`challenge is not used for proof creation, expected ${t}, challenge from public signals: ${i} `)};async checkQueryV2Circuits(e,t,r,i,o){if(!t.type)throw new Error("proof query type is undefined");let s=this._documentLoader??Ho(),a;try{a=(await s(t.context??"")).document}catch{throw new Error("can't load schema for request query")}let c=await EI(t.type,JSON.stringify(a),t.credentialSubject,{documentLoader:s});await R8(t,c,a,r,e,this._documentLoader,i);let u=c[0];if(D8(e,r.operator),u.operator===16)try{await WF(u,r,o,s)}catch(l){throw new Error(`failed to validate selective disclosure: ${l.message}`)}else if(!u.fieldName&&u.operator==0)try{await jF(u,r)}catch(l){throw new Error(`failed to validate operators: ${l.message}`)}else try{await T8(u,r)}catch(l){throw new Error(`failed to validate operators: ${l.message}`)}zF(r,u)}async resolve(e,t){let r=e.bigInt(),i=ve.parseFromId(e),o=iu(i,t),s;try{s=await this._stateStorage.getStateInfoByIdAndState(r,t)}catch(a){if(YO(a)){if(o)return{latest:!0,transitionTimestamp:0};throw new Error("State is not genesis and not registered in the smart contract")}throw a}if(!s.id||s.id.toString()!==r.toString())throw new Error("state was recorded for another identity");if(!s.state||s.state.toString()!==t.toString()){if(!s.replacedAtTimestamp||s.replacedAtTimestamp.toString()===B8.toString())throw new Error("no information about state transition");return{latest:!1,transitionTimestamp:s.replacedAtTimestamp.toString()}}return{latest:!s.replacedAtTimestamp||s.replacedAtTimestamp.toString()===B8.toString(),transitionTimestamp:s.replacedAtTimestamp?.toString()??0}}async rootResolve(e,t){let r;try{r=await this._stateStorage.getGISTRootInfo(e,t)}catch(i){throw jO(i)?new Error("GIST root does not exist in the smart contract"):i}if(r.root.toString()!==e.toString())throw new Error("gist info contains invalid state");if(r.replacedByRoot.toString()!==B8.toString()){if(r.replacedAtTimestamp.toString()===B8.toString())throw new Error("state was replaced, but replaced time unknown");return{latest:!1,transitionTimestamp:r.replacedAtTimestamp.toString()}}return{latest:!0,transitionTimestamp:0}}checkStateExistenceForId=async(e,t)=>{await this.resolve(e,t.bigInt())};checkGlobalState=async(e,t)=>this.rootResolve(e.bigInt(),t.bigInt());checkRevocationStateForId=async(e,t)=>await this.resolve(e,t.bigInt());checkRevocationState=async(e,t,r)=>{let i=await this.checkRevocationStateForId(e,t),o=r?.acceptedStateTransitionDelay??Yr.DEFAULT_PROOF_VERIFY_DELAY;if(!i.latest&&Date.now()-na(Number(i.transitionTimestamp)).getTime()>o)throw new Error("issuer state is outdated")}};var $F=class{constructor(e,t,r,i,o){this._identityWallet=e;this._credentialWallet=t;this._stateStorage=i;this._prover=o?.prover??new II(r),this._ldOptions={...o,documentLoader:o?.documentLoader??k0(o)},this._inputsGenerator=new em(e,t,i),this._pubSignalsVerifier=new xI(o?.documentLoader??k0(o),i),this._proofsCacheStorage=o?.proofsCacheStorage}_prover;_ldOptions;_inputsGenerator;_pubSignalsVerifier;_proofsCacheStorage;async verifyProof(e,t){return this._prover.verify(e,t)}async verifyZKPResponse(e,t){if(!await this._prover.verify(e,e.circuitId))throw Error(`Proof with circuit id ${e.circuitId} and request id ${e.id} is not valid`);let i={pubSignals:e.pub_signals,query:t.query,verifiablePresentation:e.vp,sender:t.sender,challenge:BigInt(e.id),opts:t.opts,params:t.params};return{linkID:(await this._pubSignalsVerifier.verify(e.circuitId,i)).linkID}}async generateProof(e,t,r){r||(r={skipRevocation:!1,challenge:0n});let i={cred:r.credential,revStatus:r.credentialRevocationStatus};if(r.credential||(i=await this.findCredentialByProofQuery(t,e.query)),r.credential&&!r.credentialRevocationStatus&&!r.skipRevocation){let Y=await this._credentialWallet.getRevocationStatusFromCredential(r.credential);i={cred:r.credential,revStatus:Y}}if(!i.cred)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+` ${JSON.stringify(e.query)}`);if(this._proofsCacheStorage&&!r?.bypassCache){let Y=await this._proofsCacheStorage.getProof(i.cred.id,e);if(Y)return Y}let o=await this._identityWallet.getCoreClaimFromCredential(i.cred),{nonce:s,genesisDID:a}=await this._identityWallet.getGenesisDIDMetadata(t),c={credential:i.cred,credentialCoreClaim:o,revStatus:i.revStatus},u=ve.parse(c.credential.credentialSubject.id),{nonce:l,genesisDID:d}=await this._identityWallet.getGenesisDIDMetadata(u);if(d.string()!==a.string())throw new Error(qe.ERRORS.PROOF_SERVICE_PROFILE_GENESIS_DID_MISMATCH);let h=S8(e.query.credentialSubject);if(!h.length)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_QUERIES_IN_ZKP_REQUEST);let f=c.credentialCoreClaim.getMerklizedPosition(),m;f!==jn.None&&(m=await c.credential.merklize(this._ldOptions));let b=e.query.context,w=e.query.groupId,S=await this.loadLdContext(b),T=e.query.type,G=[],U=[];for(let Y of h){let Q=await C8(Y,lt.decode(S),T,this._ldOptions);G.push(Q);let v=await this.toCircuitsQuery(c.credential,Q,m);U.push(v)}let H=await this.generateInputs(c,a,e,{...r,authProfileNonce:s,credentialSubjectProfileNonce:l,linkNonce:w?r.linkNonce:0n},U),M=G.filter(Y=>Y.operator===16),A;M.length&&(A=m6(b,T,c.credential,M));let{proof:D,pub_signals:z}=await this._prover.generate(H,e.circuitId),j={id:e.id,circuitId:e.circuitId,vp:A,proof:D,pub_signals:z};return this._proofsCacheStorage&&await this._proofsCacheStorage.storeProof(i.cred.id,e,j),j}async generateAuthProof(e,t,r){if(e!=="authV2"&&e!=="authV3"&&e!=="authV3-8-32")throw new Error("CircuitId is not supported");r||(r={challenge:0n});let i=r.challenge?vt.intToBytes(r.challenge).reverse():new Uint8Array(32),o=await this.generateAuthInputs(i,t,e),s=await this._prover.generate(o,e);return{circuitId:e,proof:s.proof,pub_signals:s.pub_signals}}async transitState(e,t,r,i,o){return this._identityWallet.transitState(e,t,r,o,this._prover)}async generateInputs(e,t,r,i,o){return this._inputsGenerator.generateInputs({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})}async toCircuitsQuery(e,t,r){if(t.merklizedSchema&&!r)throw new Error("merklized root position is set to None for merklized schema");if(!t.merklizedSchema&&r)throw new Error("merklized root position is not set to None for non-merklized schema");let i=new aE;if(i.slotIndex=t.slotIndex,i.operator=t.operator,i.values=t.values,t.merklizedSchema&&r){let{proof:o,value:s}=await r.proof(t.path);i.valueProof=new zr,i.valueProof.mtp=o,i.valueProof.path=t.claimPathKey;let a=await s?.mtEntry()??0n;if(i.valueProof.value=a,!t.fieldName)return i.values=[a],i}if(t.operator===16){let[o,...s]=t.fieldName.split("."),a=e.credentialSubject[o];for(let c of s)a=a[c];if(typeof a>"u")throw new Error(`credential doesn't contain value for field ${t.fieldName}`);i.values=await L8(a,t.datatype)}return i}async loadLdContext(e){let t=Ho(this._ldOptions),r;try{r=(await t(e)).document}catch{throw new Error(`can't load ld context from url ${e}`)}return Me.encode(JSON.stringify(r))}async generateAuthV2Inputs(e,t,r){if(r!=="authV2")throw new Error("CircuitId is not supported");let{nonce:i,genesisDID:o}=await this._identityWallet.getGenesisDIDMetadata(t),s=vt.bytesToInt(e.reverse()),a=await this._inputsGenerator.prepareAuthBJJCredential(o),c=await this._identityWallet.signChallenge(s,a.credential),u=ve.idFromDID(o),l=await this._stateStorage.getGISTProof(u.bigInt()),d=Ih(l),h=new F0;return h.genesisID=u,h.profileNonce=BigInt(i),h.authClaim=a.coreClaim,h.authClaimIncMtp=a.incProof.proof,h.authClaimNonRevMtp=a.nonRevProof.proof,h.treeState=a.incProof.treeState,h.signature=c,h.challenge=s,h.gistProof=d,h.inputsMarshal()}async generateAuthInputs(e,t,r){if(r!=="authV2"&&r!=="authV3"&&r!=="authV3-8-32")throw new Error("CircuitId is not supported");let{nonce:i,genesisDID:o}=await this._identityWallet.getGenesisDIDMetadata(t),s=vt.bytesToInt(e.reverse()),a=await this._inputsGenerator.prepareAuthBJJCredential(o),c=await this._identityWallet.signChallenge(s,a.credential),u=ve.idFromDID(o),l=await this._stateStorage.getGISTProof(u.bigInt()),d=Ih(l),h=new vE;return r==="authV3-8-32"&&(h.mtLevel=8,h.mtLevelOnChain=32),h.genesisID=u,h.profileNonce=BigInt(i),h.authClaim=a.coreClaim,h.authClaimIncMtp=a.incProof.proof,h.authClaimNonRevMtp=a.nonRevProof.proof,h.treeState=a.incProof.treeState,h.signature=c,h.challenge=s,h.gistProof=d,h.inputsMarshal()}async generateAuthV2Proof(e,t){let r=await this.generateAuthInputs(e,t,"authV2");return await this._prover.generate(r,"authV2")}async verifyState(e,t,r={acceptedStateTransitionDelay:Yr.DEFAULT_AUTH_VERIFY_DELAY}){if(e!=="authV2"&&e!=="authV3"&&e!=="authV3-8-32")throw new Error(`CircuitId is not supported ${e}`);let i,o;if(e==="authV2"){let a=new Zs().pubSignalsUnmarshal(Me.encode(JSON.stringify(t)));i=a.GISTRoot.bigInt(),o=a.userID.bigInt()}else{let a=new N0().pubSignalsUnmarshal(Me.encode(JSON.stringify(t)));i=a.GISTRoot.bigInt(),o=a.userID.bigInt()}let s=await this._stateStorage.getGISTRootInfo(i,o);if(s.root!==i)throw new Error("gist info contains invalid state");if(s.replacedByRoot!==0n){if(s.replacedAtTimestamp===0n)throw new Error("state was replaced, but replaced time unknown");if(Date.now()-na(Number(s.replacedAtTimestamp)).getTime()>(r?.acceptedStateTransitionDelay??Yr.DEFAULT_AUTH_VERIFY_DELAY))throw new Error("global state is outdated")}return!0}async findCredentialByProofQuery(e,t){let r=await this._identityWallet.findOwnedCredentialsByDID(e,t);if(!r.length)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE);return t.skipClaimRevocationCheck?{cred:r[0],revStatus:void 0}:await this._credentialWallet.findNonRevokedCredential(r)}};var eN=class{constructor(e,t,r,i){this._kms=e;this._storage=t;this._credentialWallet=r;this._opts=i;this._credentialStatusPublisherRegistry=this.getCredentialStatusPublisherRegistry(i),this._inputsGenerator=new em(this,r,t.states),this._transactionService=new Xs(t.states.getRpcProvider())}_credentialStatusPublisherRegistry;_inputsGenerator;_transactionService;get credentialWallet(){return this._credentialWallet}getCredentialStatusPublisherRegistry(e){if(e?.credentialStatusPublisherRegistry)return this._opts?.credentialStatusPublisherRegistry;{let t=new uI,r={publish:()=>Promise.resolve()};return t.register("Iden3ReverseSparseMerkleTreeProof",new _0),t.register("SparseMerkleTreeProof",r),t.register("Iden3commRevocationStatusV1.0",r),t}}async createAuthCoreClaim(e,t){let r=await this._kms.createKeyFromSeed("BJJ",t),i=await this._kms.publicKey(r),o=zu.newFromHex(i),s=$o.authSchemaHash,a=Fr.newClaim(s,Qa.withIndexDataInts(o.p[0],o.p[1]),Qa.withRevocationNonce(BigInt(0)));return a.setRevocationNonce(BigInt(e)),{authClaim:a,pubKey:o}}async createAuthBJJCredential(e,t,r,i,o){let s=r.getExpirationDate(),a=s?Ct(s):0,c={credentialSchema:qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL,type:qe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,credentialSubject:{x:t.p[0].toString(),y:t.p[1].toString()},subjectPosition:cP(r.getIdPosition()),version:0,expiration:a,revocationOpts:{nonce:Number(r.getRevocationNonce()),id:o.id.replace(/\/$/,""),type:o.type,issuerState:i.hex()}},u=await this._credentialWallet.getAllAuthBJJCredentials(e),l=new Pr;if(u.length===0){let d=JSON.parse(qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON);try{l=this._credentialWallet.createCredential(e,c,d)}catch(h){throw new Error(`Error create w3c credential ${h.message}`)}}else l=await this.issueCredential(e,c);return l}async createIdentity(e){let t=e.seed?wP(Pn.encode(Yu(e.seed)),lP):Ft();e.seed=e.seed??Kc(32),await this._storage.mt.createIdentityMerkleTrees(t);let r=e.revocationOpts.nonce??0,{authClaim:i,pubKey:o}=await this.createAuthCoreClaim(r,e.seed),{hi:s,hv:a}=i.hiHv();await this._storage.mt.addToMerkleTree(t,0,s,a);let c=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,0),u=await c.root(),l=Ch([u.bigInt(),Ne.bigInt(),Ne.bigInt()]),d=Vc(e.method||Fi.Iden3,e.blockchain||Kt.Polygon,e.networkId||Jt.Amoy),h=$e.idGenesisFromIdenState(d,l.bigInt()),f=ve.parseFromId(h);await this._storage.mt.bindMerkleTreeToNewIdentifier(t,f.string());let m={revocationRoot:Ne,claimsRoot:u,state:l,rootOfRoots:Ne};await this._storage.identity.getIdentity(f.string())||await this._storage.identity.saveIdentity({did:f.string(),state:l,isStatePublished:!1,isStateGenesis:!0});let w=await this._credentialWallet.findByQuery({credentialSubject:{x:{$eq:o.p[0].toString()},y:{$eq:o.p[1].toString()}},allowedIssuers:[f.string()]});if(w.length===1&&w[0].credentialStatus.type===e.revocationOpts.type)return{did:f,credential:w[0]};for(let H=0;H<w.length;H++)await this._credentialWallet.remove(w[H].id);let S=await this.createAuthBJJCredential(f,o,i,l,e.revocationOpts),T=i.hIndex(),{proof:G}=await c.generateProof(T,u),U=new pc({mtp:G,issuerData:{id:f,state:{rootOfRoots:m.rootOfRoots,revocationTreeRoot:m.revocationRoot,claimsTreeRoot:u,value:l}},coreClaim:i});return S.proof=[U],e.revocationOpts.genesisPublishingDisabled||await this.publishRevocationInfoByCredentialStatusType(f,e.revocationOpts.type,{rhsUrl:e.revocationOpts.id,onChain:e.revocationOpts.onChain}),await this._credentialWallet.save(S),{did:f,credential:S}}async createEthereumBasedIdentity(e){e.seed=e.seed??Kc(32),e.createBjjCredential=e.createBjjCredential??!0;let t,r=e.ethSigner;if(e.createBjjCredential&&!r)throw new Error(qe.ERRORS.ID_WALLET_SIGNER_IS_REQUIRED);let i=Ne,o=Vc(e.method||Fi.Iden3,e.blockchain||Kt.Polygon,e.networkId||Jt.Amoy),s=await this._kms.createKeyFromSeed("Secp256k1",e.seed),a=(await this._kms.publicKey(s)).slice(2),c=LR(o,a);if(await this._storage.mt.createIdentityMerkleTrees(c.string()),await this._storage.identity.saveIdentity({did:c.string(),state:i,isStatePublished:!1,isStateGenesis:!0}),e.createBjjCredential&&r){let u={revocationRoot:Ne,claimsRoot:Ne,state:i,rootOfRoots:Ne};t=await this.addBJJAuthCredential(c,u,!0,r,e)}return{did:c,credential:t}}async getGenesisDIDMetadata(e){let t=await this._storage.identity.getIdentity(e.string());if(t)return{nonce:0,genesisDID:ve.parse(t.did)};let r=await this._storage.identity.getProfileById(e.string());if(!r)throw new Error(qe.ERRORS.ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND);return{nonce:r.nonce,genesisDID:ve.parse(r.genesisIdentifier)}}async createProfile(e,t,r,i){let o=uP(e,t),s=Array.isArray(i),a=s?i:i?.tags,{didDocument:c,encryptionKeyOps:u}=s?{}:i??{},l=await this._storage.identity.getProfilesByGenesisIdentifier(e.string());if((await this._storage.identity.getProfilesByVerifier(r,a)).length)throw new Error(qe.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS);if(l.find(m=>m.nonce==t))throw new Error(qe.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS);let f=c;if(u?.provider){let m=new BE(u.provider,{alias:u.alias});if(!f)f=(await new TE(o.string()).addVerificationMethod(m,wC)).build();else{let b=await m.build(o.string()),w=[f["@context"]].flat().filter(S=>typeof S=="string");f={...f,verificationMethod:[...f.verificationMethod??[],b],"@context":[...new Set([...w,wC])]}}}return await this._storage.identity.saveProfile({id:o.string(),nonce:t,genesisIdentifier:e.string(),verifier:r,tags:a,did_doc:f}),o}async getProfilesByDID(e){return this._storage.identity.getProfilesByGenesisIdentifier(e.string())}async generateKey(e){return await this._kms.createKeyFromSeed(e,Kc(32))}async getProfileByVerifier(e){return this._storage.identity.getProfileByVerifier(e)}async getProfilesByVerifier(e,t){return this._storage.identity.getProfilesByVerifier(e,t)}async getDIDTreeModel(e){let t=e.string(),r=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,0),i=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,1),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,2);return{state:Ch([(await r.root()).bigInt(),(await i.root()).bigInt(),(await o.root()).bigInt()]),claimsTree:r,revocationTree:i,rootsTree:o}}async generateCredentialMtp(e,t,r){let i=await this.getCoreClaimFromCredential(t);return this.generateCoreClaimMtp(e,i,r)}async generateCoreClaimMtp(e,t,r){let i=await this.getDIDTreeModel(e),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),0),s=await i.claimsTree.root(),a=await i.rootsTree.root(),c=await i.revocationTree.root(),{proof:u}=await o.generateProof(t.hIndex(),r?r.claimsRoot:s);return{proof:u,treeState:r??{state:i.state,claimsRoot:s,rootOfRoots:a,revocationRoot:c}}}async generateNonRevocationMtp(e,t,r){let o=(await this.getCoreClaimFromCredential(t)).getRevocationNonce();return this.generateNonRevocationMtpWithNonce(e,o,r)}async generateNonRevocationMtpWithNonce(e,t,r){let i=await this.getDIDTreeModel(e),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),1),s=await i.claimsTree.root(),a=await i.rootsTree.root(),c=await i.revocationTree.root(),{proof:u}=await o.generateProof(t,r?r.revocationRoot:c);return{proof:u,treeState:r??{state:i.state,claimsRoot:s,rootOfRoots:a,revocationRoot:c}}}async sign(e,t){let r=rv(t),i=On.hashBytes(e),o=await this._kms.sign(r,vt.intToBytes(i));return Pd.newFromCompressed(o)}async signChallenge(e,t){let r=rv(t),i=await this._kms.sign(r,vt.intToBytes(e));return Pd.newFromCompressed(i)}async issueCredential(e,t,r){t.revocationOpts.id=t.revocationOpts.id.replace(/\/$/,"");let i,o=r?.documentLoader??k0(r);try{i=(await o(t.credentialSchema)).document}catch{throw new Error(`can't load credential schema ${t.credentialSchema}`)}let s=i,a=new Pr,c=await this.getDIDTreeModel(e);t.revocationOpts.issuerState=c.state.hex(),t.revocationOpts.nonce=typeof t.revocationOpts.nonce=="number"?t.revocationOpts.nonce:new DataView(Kc(16).buffer).getUint32(0,!1),t.subjectPosition=t.subjectPosition??"index";try{a=this._credentialWallet.createCredential(e,t,s);let T=Me.encode(JSON.stringify(a)),G=Me.encode(JSON.stringify(i));await new oE().validate(T,G)}catch(T){throw new Error(`Error create w3c credential ${T.message}`)}let{authCredential:u}=await this.getActualAuthCredential(e),l={revNonce:t.revocationOpts.nonce,subjectPosition:t.subjectPosition,merklizedRootPosition:t.merklizedRootPosition??"",updatable:!1,version:0,merklizeOpts:{...r,documentLoader:o}},d=await a.toCoreClaim(l),{hi:h,hv:f}=d.hiHv(),m=On.hash([h,f]),b=await this.signChallenge(m,u);if(!u.proof)throw new Error(qe.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF);let w=u.getIden3SparseMerkleTreeProof();if(!w)throw new Error(qe.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF);let S=new Ef({issuerData:{id:e,state:w.issuerData.state,authCoreClaim:w.coreClaim,mtp:w.mtp,credentialStatus:u.credentialStatus},coreClaim:d,signature:b});return a.proof=[S],a}async getActualAuthCredential(e,t){let r=await this._credentialWallet.getAllAuthBJJCredentials(e);for(let i=0;i<r.length;i++){let o=await this.generateCredentialMtp(e,r[i],t);if(!o.proof.existence)continue;let s=await this.generateNonRevocationMtp(e,r[i],t);if(!s.proof.existence)return{authCredential:r[i],incProof:o,nonRevProof:s}}throw new Error(qe.ERRORS.NO_AUTH_CRED_FOUND)}async revokeCredential(e,t){let r=await this.getDIDTreeModel(e),i=await this.getCoreClaimFromCredential(t);if(!i)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_ANY_PROOF);let o=i.getRevocationNonce();return await r.revocationTree.add(o,BigInt(0)),Number(BigInt.asUintN(64,o))}async addCredentialsToMerkleTree(e,t){let r=await this.getDIDTreeModel(t),i=await r.claimsTree.root(),o=await r.rootsTree.root(),s=await r.revocationTree.root(),a={state:r.state,claimsRoot:i,revocationRoot:s,rootOfRoots:o};for(let d=0;d<e.length;d++){let f=e[d].getCoreClaimFromProof("BJJSignature2021");if(!f)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);await this._storage.mt.addToMerkleTree(t.string(),0,f.hIndex(),f.hValue())}let u=await(await this.getDIDTreeModel(t)).claimsTree.root();await this._storage.mt.addToMerkleTree(t.string(),2,u.bigInt(),BigInt(0));let l=await this.getDIDTreeModel(t);return i=await l.claimsTree.root(),o=await l.rootsTree.root(),s=await l.revocationTree.root(),{credentials:e,newTreeState:{state:l.state,claimsRoot:i,rootOfRoots:o,revocationRoot:s},oldTreeState:a}}async generateIden3SparseMerkleTreeProof(e,t,r,i,o,s,a){for(let c=0;c<t.length;c++){let u=t[c],l=u.getCoreClaimFromProof("BJJSignature2021")||await u.toCoreClaim(a);if(!l)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);let d=await this.generateCoreClaimMtp(e,l,s),h=new pc({mtp:d.proof,issuerData:{id:e,state:{claimsTreeRoot:d.treeState.claimsRoot,revocationTreeRoot:d.treeState.revocationRoot,rootOfRoots:d.treeState.rootOfRoots,value:d.treeState.state,txId:r,blockNumber:i,blockTimestamp:o}},coreClaim:l});Array.isArray(t[c].proof)?t[c].proof.push(h):t[c].proof=t[c].proof?[t[c].proof,h]:[h]}return t}async publishSpecificStateToRHS(e,t,r){await l8(e.state,e,t,r)}async publishStateToRHS(e,t,r){let i=await this.getDIDTreeModel(e);await l8(i.state,{revocationTree:i.revocationTree,claimsTree:i.claimsTree,state:i.state,rootsTree:i.rootsTree},t,r)}async publishRevocationInfoByCredentialStatusType(e,t,r){let i=this._credentialStatusPublisherRegistry.get(t);if(!i)throw new Error(`there is no registered publisher to save hash is not registered for ${t} is not registered`);let o=[],s=r?.treeModel??await this.getDIDTreeModel(e);if(o=await d8(r?.revokedNonces??[],{revocationTree:s.revocationTree,claimsTree:s.claimsTree,state:s.state,rootsTree:s.rootsTree},s.state),!o.length)return;let a=i.map(c=>c.publish({nodes:o,...r,credentialStatusType:t,issuerDID:e}));await Promise.all(a)}async getCoreClaimFromCredential(e){let t=e.getCoreClaimFromProof("BJJSignature2021"),r=e.getCoreClaimFromProof("Iden3SparseMerkleTreeProof");if(r&&t&&r.hex()!==t.hex())throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_MISMATCH);if(!r&&!t)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_IS_NOT_SET);return r??t}async findOwnedCredentialsByDID(e,t){let r=await this._credentialWallet.findByQuery(t);if(!r.length)throw new Error(qe.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY);let{genesisDID:i}=await this.getGenesisDIDMetadata(e),o=await this.getProfilesByDID(i);return r.filter(s=>{let a=s.credentialSubject.id;return a==i.string()||o.some(c=>c.id===a)})}async updateIdentityState(e,t,r){let i=await this.getDIDTreeModel(e);await this._storage.identity.saveIdentity({did:e.string(),state:r?.state??i.state,isStatePublished:t,isStateGenesis:!1})}async transitState(e,t,r,i,o){let s=await this.getDIDTreeModel(e),a=await s.claimsTree.root(),c=await s.rootsTree.root(),l={revocationRoot:await s.revocationTree.root(),claimsRoot:a,state:s.state,rootOfRoots:c},d=ve.idFromDID(e),h,f=gp(e),m;if(f){let b=t.state,w=l.state,S={userId:d,oldUserState:b,newUserState:w,isOldStateGenesis:r,methodId:BigInt(1),methodParams:"0x"};m=await this._storage.states.publishStateGeneric(i,S)}else{if(!o)throw new Error(qe.ERRORS.ID_WALLET_PROVER_IS_REQUIRED);let b=await this._inputsGenerator.prepareAuthBJJCredential(e,t),w=r4.hash([t.state.bigInt(),l.state.bigInt()]),S=await this.signChallenge(w,b.credential),T=new IE;T.id=d,T.signature=S,T.isOldStateGenesis=r;let G=await this.generateCredentialMtp(e,b.credential,l);T.newTreeState=G.treeState,T.authClaimNewStateIncProof=G.proof,T.oldTreeState=t,T.authClaim={claim:b.coreClaim,incProof:b.incProof,nonRevProof:b.nonRevProof};let U=T.inputsMarshal();h=await o.generate(U,"stateTransition"),m=await this._storage.states.publishState(h,i)}return await this.updateIdentityState(e,!0,l),m}async getAuthBJJCredential(e,t,{nonce:r,seed:i,id:o,type:s}){let{authClaim:a,pubKey:c}=await this.createAuthCoreClaim(r,i),{hi:u,hv:l}=a.hiHv();await this._storage.mt.addToMerkleTree(e.string(),0,u,l);let d=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),0),h=Ch([(await d.root()).bigInt(),t.revocationRoot.bigInt(),t.rootOfRoots.bigInt()]);return this.createAuthBJJCredential(e,c,a,h,{id:o,type:s})}async addBJJAuthCredential(e,t,r,i,o,s){o.seed=o.seed??Kc(32),o.revocationOpts.nonce=o.revocationOpts.nonce??(r?0:o.revocationOpts.nonce??new DataView(Kc(12).buffer).getUint32(0));let a=await this.getAuthBJJCredential(e,t,{nonce:o.revocationOpts.nonce,seed:o.seed,id:o.revocationOpts.id,type:o.revocationOpts.type}),c=async()=>{let{receipt:d,block:h}=await this._transactionService.getTransactionReceiptAndBlock(u),f=await this.generateIden3SparseMerkleTreeProof(e,[a],u,d?.blockNumber,h?.timestamp,void 0,{revNonce:o.revocationOpts.nonce??0,subjectPosition:"",merklizedRootPosition:"",updatable:!1,version:0,merklizeOpts:{documentLoader:k0()}});return await this._credentialWallet.saveAll(f),await this.publishRevocationInfoByCredentialStatusType(e,o.revocationOpts.type,{rhsUrl:o.revocationOpts.id,onChain:o.revocationOpts.onChain}),f[0]},u="",l=2;do try{u=await this.transitState(e,t,r,i,s);break}catch(d){console.warn(`Error while transiting state, retrying state transition, attempt: ${l}`,d)}while(--l);if(!u){let d=JSON.stringify({claimsRoot:t.claimsRoot.hex(),revocationRoot:t.revocationRoot.hex(),rootOfRoots:t.rootOfRoots.hex(),state:t.state.hex(),isOldStateGenesis:r,credentialId:a.id,did:e.string()},null,2);throw await this._credentialWallet.save(a),new Error(`Error publishing state, info to publish: ${d}`)}return c()}};return z8(SDe);})();
435
+ `);for(let d=0;d<u.length;d++){let h=gDe(BigInt(u[d])%this.prime,this.n32);for(let f=0;f<this.n32;f++)this.instance.exports.writeSharedRWMemory(f,h[this.n32-1-f]);try{this.instance.exports.setInputSignal(a,c,d),i++}catch(f){throw new Error(f)}}}),i<this.instance.exports.getInputSize())throw new Error(`Not all inputs have been set. Only ${i} out of ${this.instance.exports.getInputSize()}`)}async calculateWitness(e,t){let r=[];await this._doCalculateWitness(e,t);for(let i=0;i<this.witnessSize;i++){this.instance.exports.getWitness(i);let o=new Uint32Array(this.n32);for(let s=0;s<this.n32;s++)o[this.n32-1-s]=this.instance.exports.readSharedRWMemory(s);r.push(qF(o))}return r}async calculateBinWitness(e,t){let r=new Uint32Array(this.witnessSize*this.n32),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t);for(let o=0;o<this.witnessSize;o++){this.instance.exports.getWitness(o);let s=o*this.n32;for(let a=0;a<this.n32;a++)r[s+a]=this.instance.exports.readSharedRWMemory(a)}return i}async calculateWTNSBin(e,t){let r=new Uint32Array(this.witnessSize*this.n32+this.n32+11),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t),i[0]=119,i[1]=116,i[2]=110,i[3]=115,r[1]=2,r[2]=2,r[3]=1;let o=this.n32*4,a=(8+o).toString(16);r[4]=parseInt(a.slice(0,8),16),r[5]=parseInt(a.slice(8,16),16),r[6]=o,this.instance.exports.getRawPrime();let c=7;for(let d=0;d<this.n32;d++)r[c+d]=this.instance.exports.readSharedRWMemory(d);c+=this.n32,r[c]=this.witnessSize,c++,r[c]=2,c++;let l=(o*this.witnessSize).toString(16);r[c]=parseInt(l.slice(0,8),16),r[c+1]=parseInt(l.slice(8,16),16),c+=2;for(let d=0;d<this.witnessSize;d++){this.instance.exports.getWitness(d);for(let h=0;h<this.n32;h++)r[c+h]=this.instance.exports.readSharedRWMemory(h);c+=this.n32}return i}};function gDe(n,e){let t=[],r=BigInt(4294967296);for(;n;)t.unshift(Number(n%r)),n=n/r;if(e){let i=e-t.length;for(;i>0;)t.unshift(0),i--}return t}function qF(n){let e=BigInt(0),t=BigInt(4294967296);for(let r=0;r<n.length;r++)e=e*t+BigInt(n[r]);return e}function yDe(n){let e=[];return t(e,n),e;function t(r,i){if(Array.isArray(i))for(let o=0;o<i.length;o++)t(r,i[o]);else r.push(i)}}function wDe(n){let e=BigInt(2)**BigInt(64),t=BigInt("0xCBF29CE484222325");for(let o=0;o<n.length;o++)t^=BigInt(n[o].charCodeAt()),t*=BigInt(1099511628211),t%=e;let r=t.toString(16),i=16-r.length;return r="0".repeat(i).concat(r),r}var II=class n{constructor(e){this._circuitStorage=e}static curveName="bn128";async verify(e,t){try{let r=await this._circuitStorage.loadCircuitData(t);if(!r.verificationKey)throw new Error(`verification file doesn't exist for circuit ${t}`);return GO(e,JSON.parse(lt.decode(r.verificationKey)))}catch(r){return console.log(r),!1}}async generate(e,t){let r=await this._circuitStorage.loadCircuitData(t);if(!r.wasm)throw new Error(`wasm file doesn't exist for circuit ${t}`);let i=await VF(r.wasm.buffer),o=JSON.parse(lt.decode(e)),s=await i.calculateWTNSBin(o,0);if(!r.provingKey)throw new Error(`proving file doesn't exist for circuit ${t}`);let{proof:a,publicSignals:c}=await KC.prove(r.provingKey,s);return await this.terminateCurve(),{proof:a,pub_signals:c}}async terminateCurve(){(await qE(n.curveName)).terminate()}};var QF=Object.values(fn),Xte=[0,1,2,3,4,5,6,16],_te=[1,2,3,4,5,6],Ah={credentialAtomicQueryMTPV2:{maxQueriesCount:1,supportedOperations:Xte},credentialAtomicQueryMTPV2OnChain:{maxQueriesCount:1,supportedOperations:_te},credentialAtomicQuerySigV2:{maxQueriesCount:1,supportedOperations:Xte},credentialAtomicQuerySigV2OnChain:{maxQueriesCount:1,supportedOperations:_te},"credentialAtomicQueryV3-beta.1":{maxQueriesCount:1,supportedOperations:QF},"credentialAtomicQueryV3OnChain-beta.1":{maxQueriesCount:1,supportedOperations:QF},authV2:{maxQueriesCount:0,supportedOperations:[]},authV3:{maxQueriesCount:0,supportedOperations:[]},"authV3-8-32":{maxQueriesCount:0,supportedOperations:[]},stateTransition:{maxQueriesCount:0,supportedOperations:[]},"linkedMultiQuery10-beta.1":{maxQueriesCount:10,supportedOperations:QF}},em=class{constructor(e,t,r){this._identityWallet=e;this._credentialWallet=t;this._stateStorage=r}async generateInputs(e){let{circuitId:t}=e.proofReq,r=`${t.split("-")[0]}PrepareInputs`;if(e.circuitQueries.length>Ah[t].maxQueriesCount)throw new Error(`circuit ${t} supports only ${Ah[t].maxQueriesCount} queries`);let o=this[r];if(!o)throw new Error(`inputs generator for ${t} not found`);return o(e)}async newCircuitClaimData(e){let t=e.credential.getIden3SparseMerkleTreeProof(),r=new cE;r.claim=e.credentialCoreClaim,r.issuerId=ve.idFromDID(ve.parse(e.credential.issuer)),t&&(r.proof=t.mtp,r.treeState={state:t.issuerData.state.value,claimsRoot:t.issuerData.state.claimsTreeRoot,revocationRoot:t.issuerData.state.revocationTreeRoot,rootOfRoots:t.issuerData.state.rootOfRoots});let i=e.credential.getBJJSignature2021Proof();if(i){let o=i.issuerData.id,s=jl(o,e.credential),{credentialStatus:a,mtp:c,authCoreClaim:u}=i.issuerData;if(!a)throw new Error("can't check the validity of issuer auth claim: no credential status in proof");if(!c)throw new Error("issuer auth credential must have a mtp proof");if(!u)throw new Error("issuer auth credential must have a core claim proof");let l={issuerGenesisState:i.issuerData.state,issuerDID:o,userDID:s},d=await this._credentialWallet.getRevocationStatus(a,l),h=qu(d);r.signatureProof={signature:i.signature,issuerAuthIncProof:{proof:i.issuerData.mtp,treeState:{state:i.issuerData.state.value,claimsRoot:i.issuerData.state.claimsTreeRoot,revocationRoot:i.issuerData.state.revocationTreeRoot,rootOfRoots:i.issuerData.state.rootOfRoots}},issuerAuthClaim:i.issuerData.authCoreClaim,issuerAuthNonRevProof:h}}return r}async prepareAuthBJJCredential(e,t){let{authCredential:r,incProof:i,nonRevProof:o}=await this._identityWallet.getActualAuthCredential(e,t),s=r.getCoreClaimFromProof("Iden3SparseMerkleTreeProof");if(!s)throw new Error("auth core claim is not defined for auth bjj credential");return{credential:r,incProof:i,nonRevProof:o,coreClaim:s}}credentialAtomicQueryMTPV2PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=qu(e.revStatus);let a=new uE;a.id=ve.idFromDID(t),a.requestID=BigInt(r.id);let c=o[0];return c.operator=this.transformV2QueryOperator(c.operator),a.query=c,a.claim={issuerID:s.issuerId,claim:s.claim,incProof:{proof:s.proof,treeState:s.treeState},nonRevProof:s.nonRevProof},a.currentTimeStamp=Ct(new Date),a.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),a.profileNonce=BigInt(i.authProfileNonce),a.skipClaimRevocationCheck=i.skipRevocation,this.checkOperatorSupport(r.circuitId,c.operator),a.inputsMarshal()};credentialAtomicQueryMTPV2OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e),a=await this.prepareAuthBJJCredential(t),c=await this.newCircuitClaimData({credential:a.credential,credentialCoreClaim:a.coreClaim});s.nonRevProof=qu(e.revStatus);let u=new dE,l=ve.idFromDID(t);u.id=ve.idFromDID(t),u.requestID=BigInt(r.id);let d=await this._stateStorage.getGISTProof(l.bigInt()),h=Ih(d);if(u.gistProof=h,c?.treeState&&(u.treeState={state:c?.treeState?.state,claimsRoot:c?.treeState?.claimsRoot,revocationRoot:c?.treeState?.revocationRoot,rootOfRoots:c?.treeState?.rootOfRoots}),u.authClaim=c.claim,u.authClaimIncMtp=c.proof,u.authClaimNonRevMtp=a.nonRevProof.proof,!i.challenge)throw new Error("challenge must be provided for onchain circuits");let f=await this._identityWallet.signChallenge(i.challenge,a.credential);u.signature=f,u.challenge=i.challenge;let m=o[0];return u.query=m,u.claim={issuerID:s.issuerId,claim:s.claim,incProof:{proof:s.proof,treeState:s.treeState},nonRevProof:s.nonRevProof},u.currentTimeStamp=Ct(new Date),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation,this.checkOperatorSupport(r.circuitId,m.operator),u.inputsMarshal()};credentialAtomicQuerySigV2PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=qu(e.revStatus);let a=new hE;a.id=ve.idFromDID(t),a.claim={issuerID:s?.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof},a.requestID=BigInt(r.id),a.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),a.profileNonce=BigInt(i.authProfileNonce),a.skipClaimRevocationCheck=i.skipRevocation;let c=o[0];return c.operator=this.transformV2QueryOperator(c.operator),a.query=c,a.currentTimeStamp=Ct(new Date),this.checkOperatorSupport(r.circuitId,c.operator),a.inputsMarshal()};credentialAtomicQuerySigV2OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e),a=await this.prepareAuthBJJCredential(t),c=await this.newCircuitClaimData({credential:a.credential,credentialCoreClaim:a.coreClaim});s.nonRevProof=qu(e.revStatus);let u=new bE,l=ve.idFromDID(t);u.id=l,u.claim={issuerID:s.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof},u.requestID=BigInt(r.id),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation;let d=o[0];u.query=d,u.currentTimeStamp=Ct(new Date),c.treeState&&(u.treeState={state:c.treeState?.state,claimsRoot:c.treeState?.claimsRoot,revocationRoot:c.treeState?.revocationRoot,rootOfRoots:c.treeState?.rootOfRoots});let h=await this._stateStorage.getGISTProof(l.bigInt()),f=Ih(h);if(u.gistProof=f,u.authClaim=c.claim,u.authClaimIncMtp=c.proof,u.authClaimNonRevMtp=a.nonRevProof.proof,!i.challenge)throw new Error("challenge must be provided for onchain circuits");let m=await this._identityWallet.signChallenge(i.challenge,a.credential);return u.signature=m,u.challenge=i.challenge,this.checkOperatorSupport(r.circuitId,d.operator),u.inputsMarshal()};credentialAtomicQueryV3PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=qu(e.revStatus);let a;switch(r.query.proofType){case"BJJSignature2021":a="BJJSignature2021";break;case"Iden3SparseMerkleTreeProof":a="Iden3SparseMerkleTreeProof";break;default:if(s.proof)a="Iden3SparseMerkleTreeProof";else if(s.signatureProof)a="BJJSignature2021";else throw Error("claim has no MTP or signature proof");break}let c=new mE;c.id=ve.idFromDID(t),c.claim={issuerID:s?.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof,incProof:{proof:s.proof,treeState:s.treeState}},c.requestID=BigInt(r.id),c.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),c.profileNonce=BigInt(i.authProfileNonce),c.skipClaimRevocationCheck=i.skipRevocation;let u=o[0];return u.values=[16,0].includes(u.operator)?[]:u.values,c.query=u,c.currentTimeStamp=Ct(new Date),c.proofType=a,c.linkNonce=i.linkNonce??BigInt(0),c.verifierID=i.verifierDid?ve.idFromDID(i.verifierDid):void 0,c.nullifierSessionID=r.params?.nullifierSessionId?BigInt(r.params?.nullifierSessionId?.toString()):BigInt(0),this.checkOperatorSupport(r.circuitId,u.operator),c.inputsMarshal()};credentialAtomicQueryV3OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=ve.idFromDID(t),a=await this.newCircuitClaimData(e);a.nonRevProof=qu(e.revStatus);let c;switch(r.query.proofType){case"BJJSignature2021":c="BJJSignature2021";break;case"Iden3SparseMerkleTreeProof":c="Iden3SparseMerkleTreeProof";break;default:if(a.proof)c="Iden3SparseMerkleTreeProof";else if(a.signatureProof)c="BJJSignature2021";else throw Error("claim has no MTP or signature proof");break}let u=new yE;u.id=ve.idFromDID(t),u.claim={issuerID:a?.issuerId,signatureProof:a.signatureProof,claim:a.claim,nonRevProof:a.nonRevProof,incProof:{proof:a.proof,treeState:a.treeState}},u.requestID=BigInt(r.id),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation;let l=o[0];l.values=[16,0].includes(l.operator)?[]:l.values,u.query=l,u.currentTimeStamp=Ct(new Date),u.proofType=c,u.linkNonce=i.linkNonce??BigInt(0),u.verifierID=i.verifierDid?ve.idFromDID(i.verifierDid):void 0,u.nullifierSessionID=r.params?.nullifierSessionId?BigInt(r.params?.nullifierSessionId?.toString()):BigInt(0);let d=gp(t);u.isBJJAuthEnabled=d?0:1,u.challenge=BigInt(i.challenge??0);let h=await this._stateStorage.getGISTProof(s.bigInt()),f=Ih(h);if(u.gistProof=f,u.isBJJAuthEnabled===1){let m=await this.prepareAuthBJJCredential(t),b=await this.newCircuitClaimData({credential:m.credential,credentialCoreClaim:m.coreClaim}),w=await this._identityWallet.signChallenge(u.challenge,m.credential);u.authClaim=b.claim,u.authClaimIncMtp=b.proof,u.authClaimNonRevMtp=m.nonRevProof.proof,u.treeState=b.treeState,u.signature=w}return this.checkOperatorSupport(r.circuitId,l.operator),u.inputsMarshal()};linkedMultiQuery10PrepareInputs=async({preparedCredential:e,params:t,proofReq:r,circuitQueries:i})=>{let o=await this.newCircuitClaimData(e);o.nonRevProof=qu(e.revStatus);let s=new cd;return s.linkNonce=t.linkNonce??BigInt(0),s.claim=o.claim,s.query=i,i.forEach(a=>{this.checkOperatorSupport(r.circuitId,a.operator)}),i.forEach(a=>{a.values=[16,0].includes(a.operator)?[]:a.values}),s.inputsMarshal()};transformV2QueryOperator(e){return e===16||e===0?1:e}checkOperatorSupport(e,t){if(!Ah[e].supportedOperations.includes(t))throw new Error(`operator ${sE(t)} is not supported by ${e}`)}};var bDe=1440*60*1e3;async function R8(n,e,t,r,i,o,s){let a=ve.parseFromId(r.issuerId);if(!(!n.allowedIssuers||n.allowedIssuers?.some(f=>f==="*"||f===a.string())))throw new Error("issuer is not in allowed list");if(!n.type)throw new Error("query type is missing");let u=await Gr.getTypeIDFromContext(JSON.stringify(t),n.type,{documentLoader:o});if(Wl(Me.encode(u)).bigInt()!==r.schemaHash.bigInt())throw new Error("schema that was used is not equal to requested in query");if(!n.skipClaimRevocationCheck&&r.isRevocationChecked===0)throw new Error("check revocation is required");$te(i,e);let d=bDe;if(s?.acceptedProofGenerationDelay&&(d=s.acceptedProofGenerationDelay),Date.now()-na(Number(r.timestamp)).getTime()>d)throw new Error("generated proof is outdated")}function $te(n,e){let t=Ah[n];if(e.length>t.maxQueriesCount)throw new Error(`circuit ${n} supports only ${Ah[n].maxQueriesCount} queries`)}function D8(n,e){if(!Ah[n].supportedOperations.includes(e))throw new Error(`circuit ${n} not support ${sE(e)} operator`)}function zF(n,e){if(n.operator!=fn.$noop){if(n.merklized===1){if(n.claimPathNotExists===1)throw new Error("proof doesn't contains target query key");if(n.claimPathKey!==e.claimPathKey)throw new Error("proof was generated for another path")}else if(n.slotIndex!==e.slotIndex)throw new Error("wrong claim slot was used in claim")}}function YF(n,e){if(n.operator!=0){if(n.operator===11&&!n.merklized)throw new Error("$exists operator is not supported for non-merklized credential");if(n.merklized===1){if(n.claimPathKey!==e.claimPathKey)throw new Error("proof was generated for another path")}else if(n.slotIndex!==e.slotIndex)throw new Error("wrong claim slot was used in claim")}}async function jF(n,e){if(e.operator!==1)throw new Error("empty credentialSubject request available only for equal operation");for(let i=1;i<e.value.length;i++)if(e.value[i]!==0n)throw new Error("empty credentialSubject request not available for array of values");let r=await Gr.newPath([qe.CREDENTIAL_SUBJECT_PATH]).mtEntry();if(e.claimPathKey!==r)throw new Error("proof doesn't contain credentialSubject in claimPathKey")}async function T8(n,e){if(e.operator!==n.operator)throw new Error("operator that was used is not equal to request");if(e.operator!==0){for(let t=0;t<e.value.length;t++)if(e.value[t]!==n.values[t]){if(e.value[t]===0n&&n.values[t]===void 0)continue;throw new Error("comparison value that was used is not equal to requested in query")}}}async function WF(n,e,t,r){if(await AI(n.fieldName,t,r)!==e.value[0])throw new Error("value that was used is not equal to requested in query");if(e.operator!==1)throw new Error("operator for selective disclosure must be $eq");for(let o=1;o<e.value.length;o++)if(e.value[o]!==0n)throw new Error("selective disclosure not available for array of values")}async function ZF(n,e,t,r){if(await AI(n.fieldName,t,r)!==e.operatorOutput)throw new Error("operator output should be equal to disclosed value");if(e.operator!==16)throw new Error("operator for selective disclosure must be $sd");for(let o=0;o<e.value.length;o++)if(e.value[o]!==0n)throw new Error("public signal values must be zero")}async function XF(n){if(n.operator!==0)throw new Error("empty credentialSubject request available only for $noop operation");for(let e=1;e<n.value.length;e++)if(n.value[e]!==0n)throw new Error("empty credentialSubject request not available for array of values")}var AI=async(n,e,t)=>{if(!e)throw new Error("verifiablePresentation is required for selective disclosure request");let r,i=JSON.stringify(e);try{r=await Ru.merklizeJSONLD(i,{documentLoader:t})}catch{throw new Error("can't merklize verifiablePresentation")}let o;try{let c=`verifiableCredential.credentialSubject.${n}`;o=await Gr.fromDocument(null,i,c,{documentLoader:t})}catch{throw new Error(`can't build path to '${n}' key`)}let s,a;try{({proof:s,value:a}=await r.proof(o))}catch{throw new Error(`can't get value by path '${n}'`)}if(!a)throw new Error(`can't get merkle value for field '${n}'`);if(!s.existence)throw new Error(`path [${o.parts}] doesn't exist in verifiablePresentation document`);return await a.mtEntry()};function EDe(n){let e=Array(n.length).fill("uint256");return BigInt(An.keccak256(An.solidityPacked(e,n)))&BigInt("0x0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")}function IDe(n,e){return(BigInt(An.keccak256(An.solidityPacked(["bytes","address"],[n,e])))&BigInt("0x0000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"))+BigInt("0x0001000000000000000000000000000000000000000000000000000000000000")}function ADe(n,e,t){return BigInt(An.keccak256(An.solidityPacked(["uint256[]","uint256[]","address"],[n,e,t])))}function xDe(n,e,t,r,i,o){let s=Qr(n,64),a=On.spongeHashX(s,6);return On.hash([e.bigInt(),BigInt(t),BigInt(r),BigInt(i),BigInt(o),a])}function _F(n,e,t,r,i,o,s,a,c,u){let l=Qr(n,cC),d=On.spongeHashX(l,6),h=On.hash([e.bigInt(),BigInt(t),BigInt(r),BigInt(i),BigInt(s),d]);return On.hash([h,BigInt(o),BigInt(a),BigInt(c),BigInt(u),0n])}var vDe=new Error("user state is not valid"),B8=0n,xI=class{constructor(e,t){this._documentLoader=e;this._stateStorage=t}async verify(e,t){let r=`${e.split("-")[0]}Verify`,i=this[r];if(!i)throw new Error(`public signals verifier for ${e} not found`);return i(t)}credentialAtomicQueryMTPV2Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s})=>{let a=new lE;if(a=a.pubSignalsUnmarshal(Me.encode(JSON.stringify(o))),!a.userID)throw new Error("user id is not presented in proof public signals");if(!a.requestID)throw new Error("requestId is not presented in proof public signals");let c={issuerId:a.issuerID,schemaHash:a.claimSchema,slotIndex:a.slotIndex,operator:a.operator,value:a.value,timestamp:a.timestamp,merklized:a.merklized,claimPathKey:a.claimPathKey,claimPathNotExists:a.claimPathNotExists,valueArraySize:a.getValueArrSize(),isRevocationChecked:a.isRevocationChecked};return await this.checkQueryV2Circuits("credentialAtomicQueryMTPV2",e,c,s,t),await this.checkStateExistenceForId(a.issuerID,a.issuerClaimIdenState),a.isRevocationChecked!==0&&await this.checkRevocationState(a.issuerID,a.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i,a.userID,a.requestID),a};credentialAtomicQuerySigV2Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s})=>{let a=new pE;a=a.pubSignalsUnmarshal(Me.encode(JSON.stringify(o)));let c={issuerId:a.issuerID,schemaHash:a.claimSchema,slotIndex:a.slotIndex,operator:a.operator,value:a.value,timestamp:a.timestamp,merklized:a.merklized,claimPathKey:a.claimPathKey,claimPathNotExists:a.claimPathNotExists,valueArraySize:a.getValueArrSize(),isRevocationChecked:a.isRevocationChecked};return await this.checkQueryV2Circuits("credentialAtomicQuerySigV2",e,c,s,t),await this.checkStateExistenceForId(a.issuerID,a.issuerAuthState),a.isRevocationChecked!==0&&await this.checkRevocationState(a.issuerID,a.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i,a.userID,a.requestID),a};credentialAtomicQueryV3Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s,params:a})=>{let c=new gE;c=c.pubSignalsUnmarshal(Me.encode(JSON.stringify(o)));let u={issuerId:c.issuerID,schemaHash:c.claimSchema,slotIndex:c.slotIndex,operator:c.operator,value:c.value,timestamp:c.timestamp,merklized:c.merklized,claimPathKey:c.claimPathKey,valueArraySize:c.getValueArrSize(),operatorOutput:c.operatorOutput,isRevocationChecked:c.isRevocationChecked};if(!e.type)throw new Error("proof query type is undefined");let l=this._documentLoader??Ho(),d;try{d=(await l(e.context??"")).document}catch{throw new Error("can't load schema for request query")}let h=await EI(e.type,JSON.stringify(d),e.credentialSubject,{documentLoader:l}),f="credentialAtomicQueryV3-beta.1";await R8(e,h,d,u,f,this._documentLoader,s);let m=h[0];if(D8(f,u.operator),m.operator===16)try{await ZF(m,u,t,l)}catch(H){throw new Error(`failed to validate selective disclosure: ${H.message}`)}else if(!m.fieldName&&m.operator==0)try{await XF(u)}catch(H){throw new Error(`failed to validate operators: ${H.message}`)}else try{await T8(m,u)}catch(H){throw new Error(`failed to validate operators: ${H.message}`)}YF(u,m);let{proofType:b,verifierID:w,nullifier:S,nullifierSessionID:T,linkID:G}=c;switch(e.proofType){case"BJJSignature2021":if(b!==1)throw new Error("wrong proof type for BJJSignature");break;case"Iden3SparseMerkleTreeProof":if(b!==2)throw new Error("wrong proof type for Iden3SparseMerkleTreeProof");break;default:}let U=BigInt(a?.nullifierSessionId??0);if(U!==0n){if(BigInt(S??0)===0n)throw new Error("nullifier should be provided for nullification and should not be 0");let H=a?.verifierDid;if(!H)throw new Error("verifierDid is required");let M=ve.idFromDID(H);if(w.bigInt()!=M.bigInt())throw new Error("wrong verifier is used for nullification");if(T!==U)throw new Error(`wrong verifier session id is used for nullification, expected ${U}, got ${T}`)}else if(T!==0n)throw new Error("Nullifier id is generated but wasn't requested");if(!e.groupId&&G!==0n)throw new Error("proof contains link id, but group id is not provided");if(e.groupId&&G===0n)throw new Error("proof doesn't contain link id, but group id is provided");return await this.checkStateExistenceForId(c.issuerID,c.issuerState),c.isRevocationChecked!==0&&await this.checkRevocationState(c.issuerID,c.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i,c.userID,c.requestID),c};authV2Verify=async({sender:e,challenge:t,pubSignals:r,opts:i})=>{let o=new Zs;o=o.pubSignalsUnmarshal(Me.encode(JSON.stringify(r)));let s=await this.checkGlobalState(o.GISTRoot,o.userID),a=Yr.DEFAULT_AUTH_VERIFY_DELAY;if(i?.acceptedStateTransitionDelay&&(a=i.acceptedStateTransitionDelay),!s.latest&&Date.now()-na(Number(s.transitionTimestamp)).getTime()>a)throw new Error("global state is outdated");return this.verifyIdOwnership(e,t,o.userID,o.challenge),new kn};linkedMultiQuery10Verify=async({query:e,verifiablePresentation:t,pubSignals:r})=>{let i=new xE;i=i.pubSignalsUnmarshal(Me.encode(JSON.stringify(r)));let o,s={documentLoader:this._documentLoader};try{o=(await s.documentLoader(e.context||"")).document}catch{throw new Error("can't load schema for request query")}let a=JSON.stringify(o),c=e.credentialSubject,u=await Gr.getTypeIDFromContext(a,e.type||"",s),l=Wl(Me.encode(u)),d=await EI(e.type||"",a,c,s),h=[],f=d[0]?.merklizedSchema?1:0;for(let w=0;w<cd.queryCount;w++){let S=d[w],T=S?.values??[],G=T.length,U=_F(T,l,S?.slotIndex??0,S?.operator??0,S?.claimPathKey.toString()??0,G,f,0,0,0);h.push({queryHash:U,queryMeta:S})}let m=(w,S)=>w.queryHash<S.queryHash?-1:w.queryHash>S.queryHash?1:0,b=i.circuitQueryHash.map((w,S)=>({queryHash:w,operatorOutput:i.operatorOutput[S]}));b.sort(m),h.sort(m);for(let w=0;w<cd.queryCount;w++){if(h[w].queryHash!=b[w].queryHash)throw new Error("query hashes do not match");if(h[w].queryMeta?.operator===16&&await AI(h[w].queryMeta.fieldName,t,this._documentLoader)!=b[w].operatorOutput)throw new Error("disclosed value is not in the proof outputs")}return i};verifyIdOwnership=(e,t,r,i)=>{if(ve.idFromDID(ve.parse(e)).string()!==r.string())throw new Error(`sender id is not used for proof creation, expected ${e}, user from public signals: ${r.string()}`);if(t!==i)throw new Error(`challenge is not used for proof creation, expected ${t}, challenge from public signals: ${i} `)};async checkQueryV2Circuits(e,t,r,i,o){if(!t.type)throw new Error("proof query type is undefined");let s=this._documentLoader??Ho(),a;try{a=(await s(t.context??"")).document}catch{throw new Error("can't load schema for request query")}let c=await EI(t.type,JSON.stringify(a),t.credentialSubject,{documentLoader:s});await R8(t,c,a,r,e,this._documentLoader,i);let u=c[0];if(D8(e,r.operator),u.operator===16)try{await WF(u,r,o,s)}catch(l){throw new Error(`failed to validate selective disclosure: ${l.message}`)}else if(!u.fieldName&&u.operator==0)try{await jF(u,r)}catch(l){throw new Error(`failed to validate operators: ${l.message}`)}else try{await T8(u,r)}catch(l){throw new Error(`failed to validate operators: ${l.message}`)}zF(r,u)}async resolve(e,t){let r=e.bigInt(),i=ve.parseFromId(e),o=iu(i,t),s;try{s=await this._stateStorage.getStateInfoByIdAndState(r,t)}catch(a){if(YO(a)){if(o)return{latest:!0,transitionTimestamp:0};throw new Error("State is not genesis and not registered in the smart contract")}throw a}if(!s.id||s.id.toString()!==r.toString())throw new Error("state was recorded for another identity");if(!s.state||s.state.toString()!==t.toString()){if(!s.replacedAtTimestamp||s.replacedAtTimestamp.toString()===B8.toString())throw new Error("no information about state transition");return{latest:!1,transitionTimestamp:s.replacedAtTimestamp.toString()}}return{latest:!s.replacedAtTimestamp||s.replacedAtTimestamp.toString()===B8.toString(),transitionTimestamp:s.replacedAtTimestamp?.toString()??0}}async rootResolve(e,t){let r;try{r=await this._stateStorage.getGISTRootInfo(e,t)}catch(i){throw jO(i)?new Error("GIST root does not exist in the smart contract"):i}if(r.root.toString()!==e.toString())throw new Error("gist info contains invalid state");if(r.replacedByRoot.toString()!==B8.toString()){if(r.replacedAtTimestamp.toString()===B8.toString())throw new Error("state was replaced, but replaced time unknown");return{latest:!1,transitionTimestamp:r.replacedAtTimestamp.toString()}}return{latest:!0,transitionTimestamp:0}}checkStateExistenceForId=async(e,t)=>{await this.resolve(e,t.bigInt())};checkGlobalState=async(e,t)=>this.rootResolve(e.bigInt(),t.bigInt());checkRevocationStateForId=async(e,t)=>await this.resolve(e,t.bigInt());checkRevocationState=async(e,t,r)=>{let i=await this.checkRevocationStateForId(e,t),o=r?.acceptedStateTransitionDelay??Yr.DEFAULT_PROOF_VERIFY_DELAY;if(!i.latest&&Date.now()-na(Number(i.transitionTimestamp)).getTime()>o)throw new Error("issuer state is outdated")}};var $F=class{constructor(e,t,r,i,o){this._identityWallet=e;this._credentialWallet=t;this._stateStorage=i;this._prover=o?.prover??new II(r),this._ldOptions={...o,documentLoader:o?.documentLoader??k0(o)},this._inputsGenerator=new em(e,t,i),this._pubSignalsVerifier=new xI(o?.documentLoader??k0(o),i),this._proofsCacheStorage=o?.proofsCacheStorage}_prover;_ldOptions;_inputsGenerator;_pubSignalsVerifier;_proofsCacheStorage;async verifyProof(e,t){return this._prover.verify(e,t)}async verifyZKPResponse(e,t){if(!await this._prover.verify(e,e.circuitId))throw Error(`Proof with circuit id ${e.circuitId} and request id ${e.id} is not valid`);let i={pubSignals:e.pub_signals,query:t.query,verifiablePresentation:e.vp,sender:t.sender,challenge:BigInt(e.id),opts:t.opts,params:t.params};return{linkID:(await this._pubSignalsVerifier.verify(e.circuitId,i)).linkID}}async generateProof(e,t,r){r||(r={skipRevocation:!1,challenge:0n});let i={cred:r.credential,revStatus:r.credentialRevocationStatus};if(r.credential||(i=await this.findCredentialByProofQuery(t,e.query)),r.credential&&!r.credentialRevocationStatus&&!r.skipRevocation){let Y=await this._credentialWallet.getRevocationStatusFromCredential(r.credential);i={cred:r.credential,revStatus:Y}}if(!i.cred)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+` ${JSON.stringify(e.query)}`);if(this._proofsCacheStorage&&!r?.bypassCache){let Y=await this._proofsCacheStorage.getProof(i.cred.id,e);if(Y)return Y}let o=await this._identityWallet.getCoreClaimFromCredential(i.cred),{nonce:s,genesisDID:a}=await this._identityWallet.getGenesisDIDMetadata(t),c={credential:i.cred,credentialCoreClaim:o,revStatus:i.revStatus},u=ve.parse(c.credential.credentialSubject.id),{nonce:l,genesisDID:d}=await this._identityWallet.getGenesisDIDMetadata(u);if(d.string()!==a.string())throw new Error(qe.ERRORS.PROOF_SERVICE_PROFILE_GENESIS_DID_MISMATCH);let h=S8(e.query.credentialSubject);if(!h.length)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_QUERIES_IN_ZKP_REQUEST);let f=c.credentialCoreClaim.getMerklizedPosition(),m;f!==jn.None&&(m=await c.credential.merklize(this._ldOptions));let b=e.query.context,w=e.query.groupId,S=await this.loadLdContext(b),T=e.query.type,G=[],U=[];for(let Y of h){let Q=await C8(Y,lt.decode(S),T,this._ldOptions);G.push(Q);let v=await this.toCircuitsQuery(c.credential,Q,m);U.push(v)}let H=await this.generateInputs(c,a,e,{...r,authProfileNonce:s,credentialSubjectProfileNonce:l,linkNonce:w?r.linkNonce:0n},U),M=G.filter(Y=>Y.operator===16),A;M.length&&(A=m6(b,T,c.credential,M));let{proof:D,pub_signals:z}=await this._prover.generate(H,e.circuitId),j={id:e.id,circuitId:e.circuitId,vp:A,proof:D,pub_signals:z};return this._proofsCacheStorage&&await this._proofsCacheStorage.storeProof(i.cred.id,e,j),j}async generateAuthProof(e,t,r){if(e!=="authV2"&&e!=="authV3"&&e!=="authV3-8-32")throw new Error("CircuitId is not supported");r||(r={challenge:0n});let i=r.challenge?vt.intToBytes(r.challenge).reverse():new Uint8Array(32),o=await this.generateAuthInputs(i,t,e),s=await this._prover.generate(o,e);return{circuitId:e,proof:s.proof,pub_signals:s.pub_signals}}async transitState(e,t,r,i,o){return this._identityWallet.transitState(e,t,r,o,this._prover)}async generateInputs(e,t,r,i,o){return this._inputsGenerator.generateInputs({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})}async toCircuitsQuery(e,t,r){if(t.merklizedSchema&&!r)throw new Error("merklized root position is set to None for merklized schema");if(!t.merklizedSchema&&r)throw new Error("merklized root position is not set to None for non-merklized schema");let i=new aE;if(i.slotIndex=t.slotIndex,i.operator=t.operator,i.values=t.values,t.merklizedSchema&&r){let{proof:o,value:s}=await r.proof(t.path);i.valueProof=new zr,i.valueProof.mtp=o,i.valueProof.path=t.claimPathKey;let a=await s?.mtEntry()??0n;if(i.valueProof.value=a,!t.fieldName)return i.values=[a],i}if(t.operator===16){let[o,...s]=t.fieldName.split("."),a=e.credentialSubject[o];for(let c of s)a=a[c];if(typeof a>"u")throw new Error(`credential doesn't contain value for field ${t.fieldName}`);i.values=await L8(a,t.datatype)}return i}async loadLdContext(e){let t=Ho(this._ldOptions),r;try{r=(await t(e)).document}catch{throw new Error(`can't load ld context from url ${e}`)}return Me.encode(JSON.stringify(r))}async generateAuthV2Inputs(e,t,r){if(r!=="authV2")throw new Error("CircuitId is not supported");let{nonce:i,genesisDID:o}=await this._identityWallet.getGenesisDIDMetadata(t),s=vt.bytesToInt(e.reverse()),a=await this._inputsGenerator.prepareAuthBJJCredential(o),c=await this._identityWallet.signChallenge(s,a.credential),u=ve.idFromDID(o),l=await this._stateStorage.getGISTProof(u.bigInt()),d=Ih(l),h=new F0;return h.genesisID=u,h.profileNonce=BigInt(i),h.authClaim=a.coreClaim,h.authClaimIncMtp=a.incProof.proof,h.authClaimNonRevMtp=a.nonRevProof.proof,h.treeState=a.incProof.treeState,h.signature=c,h.challenge=s,h.gistProof=d,h.inputsMarshal()}async generateAuthInputs(e,t,r){if(r!=="authV2"&&r!=="authV3"&&r!=="authV3-8-32")throw new Error("CircuitId is not supported");let{nonce:i,genesisDID:o}=await this._identityWallet.getGenesisDIDMetadata(t),s=vt.bytesToInt(e.reverse()),a=await this._inputsGenerator.prepareAuthBJJCredential(o),c=await this._identityWallet.signChallenge(s,a.credential),u=ve.idFromDID(o),l=await this._stateStorage.getGISTProof(u.bigInt()),d=Ih(l),h=new vE;return r==="authV3-8-32"&&(h.mtLevel=8,h.mtLevelOnChain=32),h.genesisID=u,h.profileNonce=BigInt(i),h.authClaim=a.coreClaim,h.authClaimIncMtp=a.incProof.proof,h.authClaimNonRevMtp=a.nonRevProof.proof,h.treeState=a.incProof.treeState,h.signature=c,h.challenge=s,h.gistProof=d,h.inputsMarshal()}async generateAuthV2Proof(e,t){let r=await this.generateAuthInputs(e,t,"authV2");return await this._prover.generate(r,"authV2")}async verifyState(e,t,r={acceptedStateTransitionDelay:Yr.DEFAULT_AUTH_VERIFY_DELAY}){if(e!=="authV2"&&e!=="authV3"&&e!=="authV3-8-32")throw new Error(`CircuitId is not supported ${e}`);let i,o;if(e==="authV2"){let a=new Zs().pubSignalsUnmarshal(Me.encode(JSON.stringify(t)));i=a.GISTRoot.bigInt(),o=a.userID.bigInt()}else{let a=new N0().pubSignalsUnmarshal(Me.encode(JSON.stringify(t)));i=a.GISTRoot.bigInt(),o=a.userID.bigInt()}let s=await this._stateStorage.getGISTRootInfo(i,o);if(s.root!==i)throw new Error("gist info contains invalid state");if(s.replacedByRoot!==0n){if(s.replacedAtTimestamp===0n)throw new Error("state was replaced, but replaced time unknown");if(Date.now()-na(Number(s.replacedAtTimestamp)).getTime()>(r?.acceptedStateTransitionDelay??Yr.DEFAULT_AUTH_VERIFY_DELAY))throw new Error("global state is outdated")}return!0}async findCredentialByProofQuery(e,t){let r=await this._identityWallet.findOwnedCredentialsByDID(e,t);if(!r.length)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE);return t.skipClaimRevocationCheck?{cred:r[0],revStatus:void 0}:await this._credentialWallet.findNonRevokedCredential(r)}};var eN=class{constructor(e,t,r,i){this._kms=e;this._storage=t;this._credentialWallet=r;this._opts=i;this._credentialStatusPublisherRegistry=this.getCredentialStatusPublisherRegistry(i),this._inputsGenerator=new em(this,r,t.states),this._transactionService=new Xs(t.states.getRpcProvider())}_credentialStatusPublisherRegistry;_inputsGenerator;_transactionService;get credentialWallet(){return this._credentialWallet}getCredentialStatusPublisherRegistry(e){if(e?.credentialStatusPublisherRegistry)return this._opts?.credentialStatusPublisherRegistry;{let t=new uI,r={publish:()=>Promise.resolve()};return t.register("Iden3ReverseSparseMerkleTreeProof",new _0),t.register("SparseMerkleTreeProof",r),t.register("Iden3commRevocationStatusV1.0",r),t}}async createAuthCoreClaim(e,t){let r=await this._kms.createKeyFromSeed("BJJ",t),i=await this._kms.publicKey(r),o=zu.newFromHex(i),s=$o.authSchemaHash,a=Fr.newClaim(s,Qa.withIndexDataInts(o.p[0],o.p[1]),Qa.withRevocationNonce(BigInt(0)));return a.setRevocationNonce(BigInt(e)),{authClaim:a,pubKey:o}}async createAuthBJJCredential(e,t,r,i,o){let s=r.getExpirationDate(),a=s?Ct(s):0,c={credentialSchema:qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL,type:qe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,credentialSubject:{x:t.p[0].toString(),y:t.p[1].toString()},subjectPosition:cP(r.getIdPosition()),version:0,expiration:a,revocationOpts:{nonce:Number(r.getRevocationNonce()),id:o.id.replace(/\/$/,""),type:o.type,issuerState:i.hex()}},u=await this._credentialWallet.getAllAuthBJJCredentials(e),l=new Pr;if(u.length===0){let d=JSON.parse(qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON);try{l=this._credentialWallet.createCredential(e,c,d)}catch(h){throw new Error(`Error create w3c credential ${h.message}`)}}else l=await this.issueCredential(e,c);return l}async createIdentity(e){let t=e.seed?wP(Pn.encode(Yu(e.seed)),lP):Ft();e.seed=e.seed??Kc(32),await this._storage.mt.createIdentityMerkleTrees(t);let r=e.revocationOpts.nonce??0,{authClaim:i,pubKey:o}=await this.createAuthCoreClaim(r,e.seed),{hi:s,hv:a}=i.hiHv();await this._storage.mt.addToMerkleTree(t,0,s,a);let c=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,0),u=await c.root(),l=Ch([u.bigInt(),Ne.bigInt(),Ne.bigInt()]),d=Vc(e.method||Fi.Iden3,e.blockchain||Kt.Polygon,e.networkId||Jt.Amoy),h=$e.idGenesisFromIdenState(d,l.bigInt()),f=ve.parseFromId(h);await this._storage.mt.bindMerkleTreeToNewIdentifier(t,f.string());let m={revocationRoot:Ne,claimsRoot:u,state:l,rootOfRoots:Ne};await this._storage.identity.getIdentity(f.string())||await this._storage.identity.saveIdentity({did:f.string(),state:l,isStatePublished:!1,isStateGenesis:!0});let w=await this._credentialWallet.findByQuery({credentialSubject:{x:{$eq:o.p[0].toString()},y:{$eq:o.p[1].toString()}},allowedIssuers:[f.string()]});if(w.length===1&&w[0].credentialStatus.type===e.revocationOpts.type)return{did:f,credential:w[0]};for(let H=0;H<w.length;H++)await this._credentialWallet.remove(w[H].id);let S=await this.createAuthBJJCredential(f,o,i,l,e.revocationOpts),T=i.hIndex(),{proof:G}=await c.generateProof(T,u),U=new pc({mtp:G,issuerData:{id:f,state:{rootOfRoots:m.rootOfRoots,revocationTreeRoot:m.revocationRoot,claimsTreeRoot:u,value:l}},coreClaim:i});return S.proof=[U],e.revocationOpts.genesisPublishingDisabled||await this.publishRevocationInfoByCredentialStatusType(f,e.revocationOpts.type,{rhsUrl:e.revocationOpts.id,onChain:e.revocationOpts.onChain}),await this._credentialWallet.save(S),{did:f,credential:S}}async createEthereumBasedIdentity(e){e.seed=e.seed??Kc(32),e.createBjjCredential=e.createBjjCredential??!0;let t,r=e.ethSigner;if(e.createBjjCredential&&!r)throw new Error(qe.ERRORS.ID_WALLET_SIGNER_IS_REQUIRED);let i=Ne,o=Vc(e.method||Fi.Iden3,e.blockchain||Kt.Polygon,e.networkId||Jt.Amoy),s=await this._kms.createKeyFromSeed("Secp256k1",e.seed),a=(await this._kms.publicKey(s)).slice(2),c=LR(o,a);if(await this._storage.mt.createIdentityMerkleTrees(c.string()),await this._storage.identity.saveIdentity({did:c.string(),state:i,isStatePublished:!1,isStateGenesis:!0}),e.createBjjCredential&&r){let u={revocationRoot:Ne,claimsRoot:Ne,state:i,rootOfRoots:Ne};t=await this.addBJJAuthCredential(c,u,!0,r,e)}return{did:c,credential:t}}async getGenesisDIDMetadata(e){let t=await this._storage.identity.getIdentity(e.string());if(t)return{nonce:0,genesisDID:ve.parse(t.did)};let r=await this._storage.identity.getProfileById(e.string());if(!r)throw new Error(qe.ERRORS.ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND);return{nonce:r.nonce,genesisDID:ve.parse(r.genesisIdentifier)}}async createProfile(e,t,r,i){let o=uP(e,t),s=Array.isArray(i),a=s?i:i?.tags,c=s?void 0:i?.metadata,{didDocument:u,encryptionKeyOps:l}=s?{}:i??{},d=await this._storage.identity.getProfilesByGenesisIdentifier(e.string());if((await this._storage.identity.getProfilesByVerifier(r,a)).length)throw new Error(qe.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS);if(d.find(b=>b.nonce==t))throw new Error(qe.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS);let m=u;if(l?.provider){let b=new BE(l.provider,{alias:l.alias});if(!m)m=(await new TE(o.string()).addVerificationMethod(b,wC)).build();else{let w=await b.build(o.string()),S=[m["@context"]].flat().filter(T=>typeof T=="string");m={...m,verificationMethod:[...m.verificationMethod??[],w],"@context":[...new Set([...S,wC])]}}}return await this._storage.identity.saveProfile({id:o.string(),nonce:t,genesisIdentifier:e.string(),verifier:r,tags:a,did_doc:m,metadata:c}),o}async getProfilesByDID(e){return this._storage.identity.getProfilesByGenesisIdentifier(e.string())}async generateKey(e){return await this._kms.createKeyFromSeed(e,Kc(32))}async getProfileByVerifier(e){return this._storage.identity.getProfileByVerifier(e)}async getProfilesByVerifier(e,t){return this._storage.identity.getProfilesByVerifier(e,t)}async getDIDTreeModel(e){let t=e.string(),r=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,0),i=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,1),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,2);return{state:Ch([(await r.root()).bigInt(),(await i.root()).bigInt(),(await o.root()).bigInt()]),claimsTree:r,revocationTree:i,rootsTree:o}}async generateCredentialMtp(e,t,r){let i=await this.getCoreClaimFromCredential(t);return this.generateCoreClaimMtp(e,i,r)}async generateCoreClaimMtp(e,t,r){let i=await this.getDIDTreeModel(e),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),0),s=await i.claimsTree.root(),a=await i.rootsTree.root(),c=await i.revocationTree.root(),{proof:u}=await o.generateProof(t.hIndex(),r?r.claimsRoot:s);return{proof:u,treeState:r??{state:i.state,claimsRoot:s,rootOfRoots:a,revocationRoot:c}}}async generateNonRevocationMtp(e,t,r){let o=(await this.getCoreClaimFromCredential(t)).getRevocationNonce();return this.generateNonRevocationMtpWithNonce(e,o,r)}async generateNonRevocationMtpWithNonce(e,t,r){let i=await this.getDIDTreeModel(e),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),1),s=await i.claimsTree.root(),a=await i.rootsTree.root(),c=await i.revocationTree.root(),{proof:u}=await o.generateProof(t,r?r.revocationRoot:c);return{proof:u,treeState:r??{state:i.state,claimsRoot:s,rootOfRoots:a,revocationRoot:c}}}async sign(e,t){let r=rv(t),i=On.hashBytes(e),o=await this._kms.sign(r,vt.intToBytes(i));return Pd.newFromCompressed(o)}async signChallenge(e,t){let r=rv(t),i=await this._kms.sign(r,vt.intToBytes(e));return Pd.newFromCompressed(i)}async issueCredential(e,t,r){t.revocationOpts.id=t.revocationOpts.id.replace(/\/$/,"");let i,o=r?.documentLoader??k0(r);try{i=(await o(t.credentialSchema)).document}catch{throw new Error(`can't load credential schema ${t.credentialSchema}`)}let s=i,a=new Pr,c=await this.getDIDTreeModel(e);t.revocationOpts.issuerState=c.state.hex(),t.revocationOpts.nonce=typeof t.revocationOpts.nonce=="number"?t.revocationOpts.nonce:new DataView(Kc(16).buffer).getUint32(0,!1),t.subjectPosition=t.subjectPosition??"index";try{a=this._credentialWallet.createCredential(e,t,s);let T=Me.encode(JSON.stringify(a)),G=Me.encode(JSON.stringify(i));await new oE().validate(T,G)}catch(T){throw new Error(`Error create w3c credential ${T.message}`)}let{authCredential:u}=await this.getActualAuthCredential(e),l={revNonce:t.revocationOpts.nonce,subjectPosition:t.subjectPosition,merklizedRootPosition:t.merklizedRootPosition??"",updatable:!1,version:0,merklizeOpts:{...r,documentLoader:o}},d=await a.toCoreClaim(l),{hi:h,hv:f}=d.hiHv(),m=On.hash([h,f]),b=await this.signChallenge(m,u);if(!u.proof)throw new Error(qe.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF);let w=u.getIden3SparseMerkleTreeProof();if(!w)throw new Error(qe.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF);let S=new Ef({issuerData:{id:e,state:w.issuerData.state,authCoreClaim:w.coreClaim,mtp:w.mtp,credentialStatus:u.credentialStatus},coreClaim:d,signature:b});return a.proof=[S],a}async getActualAuthCredential(e,t){let r=await this._credentialWallet.getAllAuthBJJCredentials(e);for(let i=0;i<r.length;i++){let o=await this.generateCredentialMtp(e,r[i],t);if(!o.proof.existence)continue;let s=await this.generateNonRevocationMtp(e,r[i],t);if(!s.proof.existence)return{authCredential:r[i],incProof:o,nonRevProof:s}}throw new Error(qe.ERRORS.NO_AUTH_CRED_FOUND)}async revokeCredential(e,t){let r=await this.getDIDTreeModel(e),i=await this.getCoreClaimFromCredential(t);if(!i)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_ANY_PROOF);let o=i.getRevocationNonce();return await r.revocationTree.add(o,BigInt(0)),Number(BigInt.asUintN(64,o))}async addCredentialsToMerkleTree(e,t){let r=await this.getDIDTreeModel(t),i=await r.claimsTree.root(),o=await r.rootsTree.root(),s=await r.revocationTree.root(),a={state:r.state,claimsRoot:i,revocationRoot:s,rootOfRoots:o};for(let d=0;d<e.length;d++){let f=e[d].getCoreClaimFromProof("BJJSignature2021");if(!f)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);await this._storage.mt.addToMerkleTree(t.string(),0,f.hIndex(),f.hValue())}let u=await(await this.getDIDTreeModel(t)).claimsTree.root();await this._storage.mt.addToMerkleTree(t.string(),2,u.bigInt(),BigInt(0));let l=await this.getDIDTreeModel(t);return i=await l.claimsTree.root(),o=await l.rootsTree.root(),s=await l.revocationTree.root(),{credentials:e,newTreeState:{state:l.state,claimsRoot:i,rootOfRoots:o,revocationRoot:s},oldTreeState:a}}async generateIden3SparseMerkleTreeProof(e,t,r,i,o,s,a){for(let c=0;c<t.length;c++){let u=t[c],l=u.getCoreClaimFromProof("BJJSignature2021")||await u.toCoreClaim(a);if(!l)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);let d=await this.generateCoreClaimMtp(e,l,s),h=new pc({mtp:d.proof,issuerData:{id:e,state:{claimsTreeRoot:d.treeState.claimsRoot,revocationTreeRoot:d.treeState.revocationRoot,rootOfRoots:d.treeState.rootOfRoots,value:d.treeState.state,txId:r,blockNumber:i,blockTimestamp:o}},coreClaim:l});Array.isArray(t[c].proof)?t[c].proof.push(h):t[c].proof=t[c].proof?[t[c].proof,h]:[h]}return t}async publishSpecificStateToRHS(e,t,r){await l8(e.state,e,t,r)}async publishStateToRHS(e,t,r){let i=await this.getDIDTreeModel(e);await l8(i.state,{revocationTree:i.revocationTree,claimsTree:i.claimsTree,state:i.state,rootsTree:i.rootsTree},t,r)}async publishRevocationInfoByCredentialStatusType(e,t,r){let i=this._credentialStatusPublisherRegistry.get(t);if(!i)throw new Error(`there is no registered publisher to save hash is not registered for ${t} is not registered`);let o=[],s=r?.treeModel??await this.getDIDTreeModel(e);if(o=await d8(r?.revokedNonces??[],{revocationTree:s.revocationTree,claimsTree:s.claimsTree,state:s.state,rootsTree:s.rootsTree},s.state),!o.length)return;let a=i.map(c=>c.publish({nodes:o,...r,credentialStatusType:t,issuerDID:e}));await Promise.all(a)}async getCoreClaimFromCredential(e){let t=e.getCoreClaimFromProof("BJJSignature2021"),r=e.getCoreClaimFromProof("Iden3SparseMerkleTreeProof");if(r&&t&&r.hex()!==t.hex())throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_MISMATCH);if(!r&&!t)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_IS_NOT_SET);return r??t}async findOwnedCredentialsByDID(e,t){let r=await this._credentialWallet.findByQuery(t);if(!r.length)throw new Error(qe.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY);let{genesisDID:i}=await this.getGenesisDIDMetadata(e),o=await this.getProfilesByDID(i);return r.filter(s=>{let a=s.credentialSubject.id;return a==i.string()||o.some(c=>c.id===a)})}async updateIdentityState(e,t,r){let i=await this.getDIDTreeModel(e);await this._storage.identity.saveIdentity({did:e.string(),state:r?.state??i.state,isStatePublished:t,isStateGenesis:!1})}async transitState(e,t,r,i,o){let s=await this.getDIDTreeModel(e),a=await s.claimsTree.root(),c=await s.rootsTree.root(),l={revocationRoot:await s.revocationTree.root(),claimsRoot:a,state:s.state,rootOfRoots:c},d=ve.idFromDID(e),h,f=gp(e),m;if(f){let b=t.state,w=l.state,S={userId:d,oldUserState:b,newUserState:w,isOldStateGenesis:r,methodId:BigInt(1),methodParams:"0x"};m=await this._storage.states.publishStateGeneric(i,S)}else{if(!o)throw new Error(qe.ERRORS.ID_WALLET_PROVER_IS_REQUIRED);let b=await this._inputsGenerator.prepareAuthBJJCredential(e,t),w=r4.hash([t.state.bigInt(),l.state.bigInt()]),S=await this.signChallenge(w,b.credential),T=new IE;T.id=d,T.signature=S,T.isOldStateGenesis=r;let G=await this.generateCredentialMtp(e,b.credential,l);T.newTreeState=G.treeState,T.authClaimNewStateIncProof=G.proof,T.oldTreeState=t,T.authClaim={claim:b.coreClaim,incProof:b.incProof,nonRevProof:b.nonRevProof};let U=T.inputsMarshal();h=await o.generate(U,"stateTransition"),m=await this._storage.states.publishState(h,i)}return await this.updateIdentityState(e,!0,l),m}async getAuthBJJCredential(e,t,{nonce:r,seed:i,id:o,type:s}){let{authClaim:a,pubKey:c}=await this.createAuthCoreClaim(r,i),{hi:u,hv:l}=a.hiHv();await this._storage.mt.addToMerkleTree(e.string(),0,u,l);let d=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),0),h=Ch([(await d.root()).bigInt(),t.revocationRoot.bigInt(),t.rootOfRoots.bigInt()]);return this.createAuthBJJCredential(e,c,a,h,{id:o,type:s})}async addBJJAuthCredential(e,t,r,i,o,s){o.seed=o.seed??Kc(32),o.revocationOpts.nonce=o.revocationOpts.nonce??(r?0:o.revocationOpts.nonce??new DataView(Kc(12).buffer).getUint32(0));let a=await this.getAuthBJJCredential(e,t,{nonce:o.revocationOpts.nonce,seed:o.seed,id:o.revocationOpts.id,type:o.revocationOpts.type}),c=async()=>{let{receipt:d,block:h}=await this._transactionService.getTransactionReceiptAndBlock(u),f=await this.generateIden3SparseMerkleTreeProof(e,[a],u,d?.blockNumber,h?.timestamp,void 0,{revNonce:o.revocationOpts.nonce??0,subjectPosition:"",merklizedRootPosition:"",updatable:!1,version:0,merklizeOpts:{documentLoader:k0()}});return await this._credentialWallet.saveAll(f),await this.publishRevocationInfoByCredentialStatusType(e,o.revocationOpts.type,{rhsUrl:o.revocationOpts.id,onChain:o.revocationOpts.onChain}),f[0]},u="",l=2;do try{u=await this.transitState(e,t,r,i,s);break}catch(d){console.warn(`Error while transiting state, retrying state transition, attempt: ${l}`,d)}while(--l);if(!u){let d=JSON.stringify({claimsRoot:t.claimsRoot.hex(),revocationRoot:t.revocationRoot.hex(),rootOfRoots:t.rootOfRoots.hex(),state:t.state.hex(),isOldStateGenesis:r,credentialId:a.id,did:e.string()},null,2);throw await this._credentialWallet.save(a),new Error(`Error publishing state, info to publish: ${d}`)}return c()}};return z8(SDe);})();
436
436
  /*! Bundled license information:
437
437
 
438
438
  ieee754/index.js: