@0xpolygonid/js-sdk 1.35.5 → 1.35.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/esm/index.js +3 -0
- package/dist/browser/esm/index.js.map +1 -1
- package/dist/browser/umd/index.global.js +1 -1
- package/dist/browser/umd/index.global.js.map +1 -1
- package/dist/node/cjs/index.cjs +3 -0
- package/dist/node/cjs/index.cjs.map +1 -1
- package/dist/node/esm/index.js +3 -0
- package/dist/node/esm/index.js.map +1 -1
- package/dist/types/iden3comm/handlers/auth.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/iden3comm/handlers/auth.ts +3 -0
|
@@ -420,7 +420,7 @@ if (cid) {
|
|
|
420
420
|
`?i="":(i!==""&&(i+=" "),i+=u)},showSharedRWMemory:function(){l()}}}),s=e;return new kM(o,s);function c(){let u="",d=o.exports.getMessageChar();for(;d!=0;)u+=String.fromCharCode(d),d=o.exports.getMessageChar();return u}function l(){let u=o.exports.getFieldNumLen32(),d=new Uint32Array(u);for(let h=0;h<u;h++)d[u-1-h]=o.exports.readSharedRWMemory(h);i!==""&&(i+=" "),i+=MM(d).toString()}}var kM=class{instance;version;n32;prime;witnessSize;sanityCheck;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=MM(r),this.witnessSize=this.instance.exports.getWitnessSize(),this.sanityCheck=t}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=k8e(o),a=parseInt(s.slice(0,8),16),c=parseInt(s.slice(8,16),16),l=P8e(e[o]),u=this.instance.exports.getInputSignalSize(a,c);if(u<0)throw new Error(`Signal ${o} not found
|
|
421
421
|
`);if(l.length<u)throw new Error(`Not enough values for input signal ${o}
|
|
422
422
|
`);if(l.length>u)throw new Error(`Too many values for input signal ${o}
|
|
423
|
-
`);for(let d=0;d<l.length;d++){let h=B8e(BigInt(l[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(MM(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 u=(o*this.witnessSize).toString(16);r[c]=parseInt(u.slice(0,8),16),r[c+1]=parseInt(u.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 B8e(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 MM(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 P8e(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 k8e(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 Py=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function OC(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function OM(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Zo(n,...e){if(!OC(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function M8e(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");OM(n.outputLen),OM(n.blockLen)}function LC(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function O8e(n,e){Zo(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function RC(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function vM(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Fl(n,e){return n<<32-e|n>>>e}var A$=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",F8e=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function NE(n){if(Zo(n),A$)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=F8e[n[t]];return e}var ld={_0:48,_9:57,A:65,F:70,a:97,f:102};function n$(n){if(n>=ld._0&&n<=ld._9)return n-ld._0;if(n>=ld.A&&n<=ld.F)return n-(ld.A-10);if(n>=ld.a&&n<=ld.f)return n-(ld.a-10)}function ZM(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(A$)return Uint8Array.fromHex(n);let e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let i=0,o=0;i<t;i++,o+=2){let s=n$(n.charCodeAt(o)),a=n$(n.charCodeAt(o+1));if(s===void 0||a===void 0){let c=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[i]=s*16+a}return r}function FC(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function XM(n){return typeof n=="string"&&(n=FC(n)),Zo(n),n}function so(...n){let e=0;for(let r=0;r<n.length;r++){let i=n[r];Zo(i),e+=i.length}let t=new Uint8Array(e);for(let r=0,i=0;r<n.length;r++){let o=n[r];t.set(o,i),i+=o.length}return t}var DC=class{};function N8e(n){let e=r=>n().update(XM(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function x$(n=32){if(Py&&typeof Py.getRandomValues=="function")return Py.getRandomValues(new Uint8Array(n));if(Py&&typeof Py.randomBytes=="function")return Uint8Array.from(Py.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}function U8e(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);let i=BigInt(32),o=BigInt(4294967295),s=Number(t>>i&o),a=Number(t&o),c=r?4:0,l=r?0:4;n.setUint32(e+c,s,r),n.setUint32(e+l,a,r)}function G8e(n,e,t){return n&e^~n&t}function K8e(n,e,t){return n&e^n&t^e&t}var FM=class extends DC{constructor(e,t,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=vM(this.buffer)}update(e){LC(this),e=XM(e),Zo(e);let{view:t,buffer:r,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=vM(e);for(;i<=o-s;s+=i)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){LC(this),O8e(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,RC(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)t[d]=0;U8e(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=vM(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},ih=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),H8e=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),oh=new Uint32Array(64),NM=class extends FM{constructor(e=32){super(64,e,8,!1),this.A=ih[0]|0,this.B=ih[1]|0,this.C=ih[2]|0,this.D=ih[3]|0,this.E=ih[4]|0,this.F=ih[5]|0,this.G=ih[6]|0,this.H=ih[7]|0}get(){let{A:e,B:t,C:r,D:i,E:o,F:s,G:a,H:c}=this;return[e,t,r,i,o,s,a,c]}set(e,t,r,i,o,s,a,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)oh[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=oh[d-15],f=oh[d-2],p=Fl(h,7)^Fl(h,18)^h>>>3,E=Fl(f,17)^Fl(f,19)^f>>>10;oh[d]=E+oh[d-7]+p+oh[d-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let h=Fl(a,6)^Fl(a,11)^Fl(a,25),f=u+h+G8e(a,c,l)+H8e[d]+oh[d]|0,E=(Fl(r,2)^Fl(r,13)^Fl(r,22))+K8e(r,i,o)|0;u=l,l=c,c=a,a=s+f|0,s=o,o=i,i=r,r=f+E|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,i,o,s,a,c,l,u)}roundClean(){RC(oh)}destroy(){this.set(0,0,0,0,0,0,0,0),RC(this.buffer)}},_M=N8e(()=>new NM);var $M=BigInt(0),TC=BigInt(1);function BC(n,e){if(typeof e!="boolean")throw new Error(n+" boolean expected, got "+e)}function IC(n){let e=n.toString(16);return e.length&1?"0"+e:e}function v$(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?$M:BigInt("0x"+n)}function HE(n){return v$(NE(n))}function S$(n){return Zo(n),v$(NE(Uint8Array.from(n).reverse()))}function eO(n,e){return ZM(n.toString(16).padStart(e*2,"0"))}function C$(n,e){return eO(n,e).reverse()}function Ls(n,e,t){let r;if(typeof e=="string")try{r=ZM(e)}catch(o){throw new Error(n+" must be hex string or Uint8Array, cause: "+o)}else if(OC(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");let i=r.length;if(typeof t=="number"&&i!==t)throw new Error(n+" of length "+t+" expected, got "+i);return r}var SM=n=>typeof n=="bigint"&&$M<=n;function L$(n,e,t){return SM(n)&&SM(e)&&SM(t)&&e<=n&&n<t}function J8e(n,e,t,r){if(!L$(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function kE(n){let e;for(e=0;n>$M;n>>=TC,e+=1);return e}function q8e(n,e){return n>>BigInt(e)&TC}var O0=n=>(TC<<BigInt(n))-TC;function V8e(n,e,t){if(typeof n!="number"||n<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=f=>new Uint8Array(f),i=f=>Uint8Array.of(f),o=r(n),s=r(n),a=0,c=()=>{o.fill(1),s.fill(0),a=0},l=(...f)=>t(s,o,...f),u=(f=r(0))=>{s=l(i(0),f),o=l(),f.length!==0&&(s=l(i(1),f),o=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<e;){o=l();let E=o.slice();p.push(E),f+=o.length}return so(...p)};return(f,p)=>{c(),u(f);let E;for(;!(E=p(d()));)u();return c(),E}}function Q8e(n){return typeof n=="function"&&Number.isSafeInteger(n.outputLen)}function NC(n,e,t={}){if(!n||typeof n!="object")throw new Error("expected valid options object");function r(i,o,s){let a=n[i];if(s&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([i,o])=>r(i,o,!1)),Object.entries(t).forEach(([i,o])=>r(i,o,!0))}var li=()=>{throw new Error("not implemented")};function UM(n){let e=new WeakMap;return(t,...r)=>{let i=e.get(t);if(i!==void 0)return i;let o=n(t,...r);return e.set(t,o),o}}var ta=BigInt(0),Wo=BigInt(1),k0=BigInt(2),z8e=BigInt(3),R$=BigInt(4),D$=BigInt(5),T$=BigInt(8);function Mc(n,e){let t=n%e;return t>=ta?t:e+t}function r$(n,e){if(n===ta)throw new Error("invert: expected non-zero number");if(e<=ta)throw new Error("invert: expected positive modulus, got "+e);let t=Mc(n,e),r=e,i=ta,o=Wo;for(;t!==ta;){let a=r/t,c=r%t,l=i-o*a;r=t,t=c,i=o,o=l}if(r!==Wo)throw new Error("invert: does not exist");return Mc(i,e)}function B$(n,e){let t=(n.ORDER+Wo)/R$,r=n.pow(e,t);if(!n.eql(n.sqr(r),e))throw new Error("Cannot find square root");return r}function Y8e(n,e){let t=(n.ORDER-D$)/T$,r=n.mul(e,k0),i=n.pow(r,t),o=n.mul(e,i),s=n.mul(n.mul(o,k0),i),a=n.mul(o,n.sub(s,n.ONE));if(!n.eql(n.sqr(a),e))throw new Error("Cannot find square root");return a}function j8e(n){if(n<BigInt(3))throw new Error("sqrt is not defined for small field");let e=n-Wo,t=0;for(;e%k0===ta;)e/=k0,t++;let r=k0,i=JE(n);for(;PC(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return B$;let o=i.pow(r,e),s=(e+Wo)/k0;return function(c,l){if(c.is0(l))return l;if(PC(c,l)!==1)throw new Error("Cannot find square root");let u=t,d=c.mul(c.ONE,o),h=c.pow(l,e),f=c.pow(l,s);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let p=1,E=c.sqr(h);for(;!c.eql(E,c.ONE);)if(p++,E=c.sqr(E),p===u)throw new Error("Cannot find square root");let b=Wo<<BigInt(u-p-1),C=c.pow(d,b);u=p,d=c.sqr(C),h=c.mul(h,d),f=c.mul(f,C)}return f}}function W8e(n){return n%R$===z8e?B$:n%T$===D$?Y8e:j8e(n)}var Z8e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function X8e(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=Z8e.reduce((r,i)=>(r[i]="function",r),e);return NC(n,t),n}function CC(n,e,t){if(t<ta)throw new Error("invalid exponent, negatives unsupported");if(t===ta)return n.ONE;if(t===Wo)return e;let r=n.ONE,i=e;for(;t>ta;)t&Wo&&(r=n.mul(r,i)),i=n.sqr(i),t>>=Wo;return r}function ME(n,e,t=!1){let r=new Array(e.length).fill(t?n.ZERO:void 0),i=e.reduce((s,a,c)=>n.is0(a)?s:(r[c]=s,n.mul(s,a)),n.ONE),o=n.inv(i);return e.reduceRight((s,a,c)=>n.is0(a)?s:(r[c]=n.mul(s,r[c]),n.mul(s,a)),o),r}function PC(n,e){let t=(n.ORDER-Wo)/k0,r=n.pow(e,t),i=n.eql(r,n.ONE),o=n.eql(r,n.ZERO),s=n.eql(r,n.neg(n.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function _8e(n,e){e!==void 0&&OM(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function JE(n,e,t=!1,r={}){if(n<=ta)throw new Error("invalid field: expected ORDER > 0, got "+n);let i,o;if(typeof e=="object"&&e!=null){if(r.sqrt||t)throw new Error("cannot specify opts in two arguments");let u=e;u.BITS&&(i=u.BITS),u.sqrt&&(o=u.sqrt),typeof u.isLE=="boolean"&&(t=u.isLE)}else typeof e=="number"&&(i=e),r.sqrt&&(o=r.sqrt);let{nBitLength:s,nByteLength:a}=_8e(n,i);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c,l=Object.freeze({ORDER:n,isLE:t,BITS:s,BYTES:a,MASK:O0(s),ZERO:ta,ONE:Wo,create:u=>Mc(u,n),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return ta<=u&&u<n},is0:u=>u===ta,isValidNot0:u=>!l.is0(u)&&l.isValid(u),isOdd:u=>(u&Wo)===Wo,neg:u=>Mc(-u,n),eql:(u,d)=>u===d,sqr:u=>Mc(u*u,n),add:(u,d)=>Mc(u+d,n),sub:(u,d)=>Mc(u-d,n),mul:(u,d)=>Mc(u*d,n),pow:(u,d)=>CC(l,u,d),div:(u,d)=>Mc(u*r$(d,n),n),sqrN:u=>u*u,addN:(u,d)=>u+d,subN:(u,d)=>u-d,mulN:(u,d)=>u*d,inv:u=>r$(u,n),sqrt:o||(u=>(c||(c=W8e(n)),c(l,u))),toBytes:u=>t?C$(u,a):eO(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return t?S$(u):HE(u)},invertBatch:u=>ME(l,u),cmov:(u,d,h)=>h?d:u});return Object.freeze(l)}function P$(n){if(typeof n!="bigint")throw new Error("field order must be bigint");let e=n.toString(2).length;return Math.ceil(e/8)}function tO(n){let e=P$(n);return e+Math.ceil(e/2)}function k$(n,e,t=!1){let r=n.length,i=P$(e),o=tO(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let s=t?S$(n):HE(n),a=Mc(s,e-Wo)+Wo;return t?C$(a,i):eO(a,i)}var Fy=BigInt(0),M0=BigInt(1);function OE(n,e){let t=e.negate();return n?t:e}function GM(n,e,t){let r=s=>s.pz,i=ME(n.Fp,t.map(r));return t.map((s,a)=>s.toAffine(i[a])).map(n.fromAffine)}function M$(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function CM(n,e){M$(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),i=2**n,o=O0(n),s=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function i$(n,e,t){let{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=t,a=Number(n&i),c=n>>s;a>r&&(a-=o,c+=M0);let l=e*r,u=l+Math.abs(a)-1,d=a===0,h=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:l}}function $8e(n,e){if(!Array.isArray(n))throw new Error("array expected");n.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function eLe(n,e){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}var LM=new WeakMap,O$=new WeakMap;function RM(n){return O$.get(n)||1}function o$(n){if(n!==Fy)throw new Error("invalid wNAF")}function tLe(n,e){return{constTimeNegate:OE,hasPrecomputes(t){return RM(t)!==1},unsafeLadder(t,r,i=n.ZERO){let o=t;for(;r>Fy;)r&M0&&(i=i.add(o)),o=o.double(),r>>=M0;return i},precomputeWindow(t,r){let{windows:i,windowSize:o}=CM(r,e),s=[],a=t,c=a;for(let l=0;l<i;l++){c=a,s.push(c);for(let u=1;u<o;u++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(t,r,i){let o=n.ZERO,s=n.BASE,a=CM(t,e);for(let c=0;c<a.windows;c++){let{nextN:l,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:p}=i$(i,c,a);i=l,d?s=s.add(OE(f,r[p])):o=o.add(OE(h,r[u]))}return o$(i),{p:o,f:s}},wNAFUnsafe(t,r,i,o=n.ZERO){let s=CM(t,e);for(let a=0;a<s.windows&&i!==Fy;a++){let{nextN:c,offset:l,isZero:u,isNeg:d}=i$(i,a,s);if(i=c,!u){let h=r[l];o=o.add(d?h.negate():h)}}return o$(i),o},getPrecomputes(t,r,i){let o=LM.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof i=="function"&&(o=i(o)),LM.set(r,o))),o},wNAFCached(t,r,i){let o=RM(t);return this.wNAF(o,this.getPrecomputes(o,t,i),r)},wNAFCachedUnsafe(t,r,i,o){let s=RM(t);return s===1?this.unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,i),r,o)},setWindowSize(t,r){M$(r,e),O$.set(t,r),LM.delete(t)}}}function nLe(n,e,t,r){let i=e,o=n.ZERO,s=n.ZERO;for(;t>Fy||r>Fy;)t&M0&&(o=o.add(i)),r&M0&&(s=s.add(i)),i=i.double(),t>>=M0,r>>=M0;return{p1:o,p2:s}}function rLe(n,e,t,r){$8e(t,n),eLe(r,e);let i=t.length,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=n.ZERO,a=kE(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=O0(c),u=new Array(Number(l)+1).fill(s),d=Math.floor((e.BITS-1)/c)*c,h=s;for(let f=d;f>=0;f-=c){u.fill(s);for(let E=0;E<o;E++){let b=r[E],C=Number(b>>BigInt(f)&l);u[C]=u[C].add(t[E])}let p=s;for(let E=u.length-1,b=s;E>0;E--)b=b.add(u[E]),p=p.add(b);if(h=h.add(p),f!==0)for(let E=0;E<c;E++)h=h.double()}return h}function s$(n,e){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return X8e(e),e}else return JE(n)}function iLe(n,e,t={}){if(!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let a of["p","n","h"]){let c=e[a];if(!(typeof c=="bigint"&&c>Fy))throw new Error(`CURVE.${a} must be positive bigint`)}let r=s$(e.p,t.Fp),i=s$(e.n,t.Fn),s=["Gx","Gy","a","b"];for(let a of s)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:i}}var oLe=HE;function sh(n,e){if(UE(n),UE(e),n<0||n>=1<<8*e)throw new Error("invalid I2OSP input: "+n);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=n&255,n>>>=8;return new Uint8Array(t)}function sLe(n,e){let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function UE(n){if(!Number.isSafeInteger(n))throw new Error("number expected")}function aLe(n,e,t,r){Zo(n),Zo(e),UE(t),e.length>255&&(e=r(so(FC("H2C-OVERSIZE-DST-"),e)));let{outputLen:i,blockLen:o}=r,s=Math.ceil(t/i);if(t>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=so(e,sh(e.length,1)),c=sh(0,o),l=sh(t,2),u=new Array(s),d=r(so(c,n,l,sh(0,1),a));u[0]=r(so(d,sh(1,1),a));for(let f=1;f<=s;f++){let p=[sLe(d,u[f-1]),sh(f+1,1),a];u[f]=r(so(...p))}return so(...u).slice(0,t)}function cLe(n,e,t,r,i){if(Zo(n),Zo(e),UE(t),e.length>255){let o=Math.ceil(2*r/8);e=i.create({dkLen:o}).update(FC("H2C-OVERSIZE-DST-")).update(e).digest()}if(t>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:t}).update(n).update(sh(t,2)).update(e).update(sh(e.length,1)).digest()}function a$(n,e,t){NC(t,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:s,expand:a,DST:c}=t;if(!OC(c)&&typeof c!="string")throw new Error("DST must be string or uint8array");if(!Q8e(t.hash))throw new Error("expected valid hash");Zo(n),UE(e);let l=typeof c=="string"?FC(c):c,u=r.toString(2).length,d=Math.ceil((u+i)/8),h=e*o*d,f;if(a==="xmd")f=aLe(n,l,h,s);else if(a==="xof")f=cLe(n,l,h,i,s);else if(a==="_internal_pass")f=n;else throw new Error('expand must be "xmd" or "xof"');let p=new Array(e);for(let E=0;E<e;E++){let b=new Array(o);for(let C=0;C<o;C++){let B=d*(C+E*o),J=f.subarray(B,B+d);b[C]=Mc(oLe(J),r)}p[E]=b}return p}function c$(n,e,t){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function r(o){return n.fromAffine(e(o))}function i(o){let s=o.clearCofactor();return s.equals(n.ZERO)?n.ZERO:(s.assertValidity(),s)}return{defaults:t,hashToCurve(o,s){let a=t.DST?t.DST:{},c=Object.assign({},t,a,s),l=a$(o,2,c),u=r(l[0]),d=r(l[1]);return i(u.add(d))},encodeToCurve(o,s){let a=t.encodeDST?t.encodeDST:{},c=Object.assign({},t,a,s),l=a$(o,1,c);return i(r(l[0]))},mapToCurve(o){if(!Array.isArray(o))throw new Error("expected array of bigints");for(let s of o)if(typeof s!="bigint")throw new Error("expected array of bigints");return i(r(o))}}}var kC=class extends DC{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,M8e(e);let r=XM(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),RC(o)}update(e){return LC(this),this.iHash.update(e),this}digestInto(e){LC(this),Zo(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:r,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},F$=(n,e,t)=>new kC(n,e).update(t).digest();F$.create=(n,e)=>new kC(n,e);function l$(n){n.lowS!==void 0&&BC("lowS",n.lowS),n.prehash!==void 0&&BC("prehash",n.prehash)}var KM=class extends Error{constructor(e=""){super(e)}},ud={Err:KM,_tlv:{encode:(n,e)=>{let{Err:t}=ud;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,i=IC(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?IC(i.length/2|128):"";return IC(n)+o+i+e},decode(n,e){let{Err:t}=ud,r=0;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==n)throw new t("tlv.decode: wrong tlv");let i=e[r++],o=!!(i&128),s=0;if(!o)s=i;else{let c=i&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(r+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(n){let{Err:e}=ud;if(n<FE)throw new e("integer: negative integers are not allowed");let t=IC(n);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(n){let{Err:e}=ud;if(n[0]&128)throw new e("invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return HE(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=ud,i=Ls("signature",n),{v:o,l:s}=r.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,o),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(n){let{_tlv:e,_int:t}=ud,r=e.encode(2,t.encode(n.r)),i=e.encode(2,t.encode(n.s)),o=r+i;return e.encode(48,o)}},FE=BigInt(0),Oy=BigInt(1),lLe=BigInt(2),AC=BigInt(3),uLe=BigInt(4);function N$(n,e,t){function r(i){let o=n.sqr(i),s=n.mul(o,i);return n.add(n.add(s,n.mul(i,e)),t)}return r}function nO(n,e,t){let{BYTES:r}=n;function i(o){let s;if(typeof o=="bigint")s=o;else{let a=Ls("private key",o);if(e){if(!e.includes(a.length*2))throw new Error("invalid private key");let c=new Uint8Array(r);c.set(a,c.length-a.length),a=c}try{s=n.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof o}`)}}if(t&&(s=n.create(s)),!n.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}return i}function U$(n,e={}){let{Fp:t,Fn:r}=iLe("weierstrass",n,e),{h:i,n:o}=n;NC(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:s}=e;if(s&&(!t.is0(n.a)||typeof s.beta!="bigint"||typeof s.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(D,z,j){let{x:Y,y:H}=z.toAffine(),I=t.toBytes(Y);if(BC("isCompressed",j),j){a();let m=!t.isOdd(H);return so(G$(m),I)}else return so(Uint8Array.of(4),I,t.toBytes(H))}function l(D){Zo(D);let z=t.BYTES,j=z+1,Y=2*z+1,H=D.length,I=D[0],m=D.subarray(1);if(H===j&&(I===2||I===3)){let x=t.fromBytes(m);if(!t.isValid(x))throw new Error("bad point: is not on curve, wrong x");let y=h(x),A;try{A=t.sqrt(y)}catch(N){let M=N instanceof Error?": "+N.message:"";throw new Error("bad point: is not on curve, sqrt error"+M)}a();let L=t.isOdd(A);return(I&1)===1!==L&&(A=t.neg(A)),{x,y:A}}else if(H===Y&&I===4){let x=t.fromBytes(m.subarray(z*0,z*1)),y=t.fromBytes(m.subarray(z*1,z*2));if(!f(x,y))throw new Error("bad point: is not on curve");return{x,y}}else throw new Error(`bad point: got length ${H}, expected compressed=${j} or uncompressed=${Y}`)}let u=e.toBytes||c,d=e.fromBytes||l,h=N$(t,n.a,n.b);function f(D,z){let j=t.sqr(z),Y=h(D);return t.eql(j,Y)}if(!f(n.Gx,n.Gy))throw new Error("bad curve params: generator point");let p=t.mul(t.pow(n.a,AC),uLe),E=t.mul(t.sqr(n.b),BigInt(27));if(t.is0(t.add(p,E)))throw new Error("bad curve params: a or b");function b(D,z,j=!1){if(!t.isValid(z)||j&&t.is0(z))throw new Error(`bad point coordinate ${D}`);return z}function C(D){if(!(D instanceof U))throw new Error("ProjectivePoint expected")}let B=UM((D,z)=>{let{px:j,py:Y,pz:H}=D;if(t.eql(H,t.ONE))return{x:j,y:Y};let I=D.is0();z==null&&(z=I?t.ONE:t.inv(H));let m=t.mul(j,z),x=t.mul(Y,z),y=t.mul(H,z);if(I)return{x:t.ZERO,y:t.ZERO};if(!t.eql(y,t.ONE))throw new Error("invZ was invalid");return{x:m,y:x}}),J=UM(D=>{if(D.is0()){if(e.allowInfinityPoint&&!t.is0(D.py))return;throw new Error("bad point: ZERO")}let{x:z,y:j}=D.toAffine();if(!t.isValid(z)||!t.isValid(j))throw new Error("bad point: x or y not field elements");if(!f(z,j))throw new Error("bad point: equation left != right");if(!D.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function G(D,z,j,Y,H){return j=new U(t.mul(j.px,D),j.py,j.pz),z=OE(Y,z),j=OE(H,j),z.add(j)}class U{constructor(z,j,Y){this.px=b("x",z),this.py=b("y",j,!0),this.pz=b("z",Y),Object.freeze(this)}static fromAffine(z){let{x:j,y:Y}=z||{};if(!z||!t.isValid(j)||!t.isValid(Y))throw new Error("invalid affine point");if(z instanceof U)throw new Error("projective point not allowed");return t.is0(j)&&t.is0(Y)?U.ZERO:new U(j,Y,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(z){return GM(U,"pz",z)}static fromBytes(z){return Zo(z),U.fromHex(z)}static fromHex(z){let j=U.fromAffine(d(Ls("pointHex",z)));return j.assertValidity(),j}static fromPrivateKey(z){let j=nO(r,e.allowedPrivateKeyLengths,e.wrapPrivateKey);return U.BASE.multiply(j(z))}static msm(z,j){return rLe(U,r,z,j)}precompute(z=8,j=!0){return v.setWindowSize(this,z),j||this.multiply(AC),this}_setWindowSize(z){this.precompute(z)}assertValidity(){J(this)}hasEvenY(){let{y:z}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(z)}equals(z){C(z);let{px:j,py:Y,pz:H}=this,{px:I,py:m,pz:x}=z,y=t.eql(t.mul(j,x),t.mul(I,H)),A=t.eql(t.mul(Y,x),t.mul(m,H));return y&&A}negate(){return new U(this.px,t.neg(this.py),this.pz)}double(){let{a:z,b:j}=n,Y=t.mul(j,AC),{px:H,py:I,pz:m}=this,x=t.ZERO,y=t.ZERO,A=t.ZERO,L=t.mul(H,H),F=t.mul(I,I),N=t.mul(m,m),M=t.mul(H,I);return M=t.add(M,M),A=t.mul(H,m),A=t.add(A,A),x=t.mul(z,A),y=t.mul(Y,N),y=t.add(x,y),x=t.sub(F,y),y=t.add(F,y),y=t.mul(x,y),x=t.mul(M,x),A=t.mul(Y,A),N=t.mul(z,N),M=t.sub(L,N),M=t.mul(z,M),M=t.add(M,A),A=t.add(L,L),L=t.add(A,L),L=t.add(L,N),L=t.mul(L,M),y=t.add(y,L),N=t.mul(I,m),N=t.add(N,N),L=t.mul(N,M),x=t.sub(x,L),A=t.mul(N,F),A=t.add(A,A),A=t.add(A,A),new U(x,y,A)}add(z){C(z);let{px:j,py:Y,pz:H}=this,{px:I,py:m,pz:x}=z,y=t.ZERO,A=t.ZERO,L=t.ZERO,F=n.a,N=t.mul(n.b,AC),M=t.mul(j,I),T=t.mul(Y,m),Q=t.mul(H,x),_=t.add(j,Y),S=t.add(I,m);_=t.mul(_,S),S=t.add(M,T),_=t.sub(_,S),S=t.add(j,H);let g=t.add(I,x);return S=t.mul(S,g),g=t.add(M,Q),S=t.sub(S,g),g=t.add(Y,H),y=t.add(m,x),g=t.mul(g,y),y=t.add(T,Q),g=t.sub(g,y),L=t.mul(F,S),y=t.mul(N,Q),L=t.add(y,L),y=t.sub(T,L),L=t.add(T,L),A=t.mul(y,L),T=t.add(M,M),T=t.add(T,M),Q=t.mul(F,Q),S=t.mul(N,S),T=t.add(T,Q),Q=t.sub(M,Q),Q=t.mul(F,Q),S=t.add(S,Q),M=t.mul(T,S),A=t.add(A,M),M=t.mul(g,S),y=t.mul(_,y),y=t.sub(y,M),M=t.mul(_,T),L=t.mul(g,L),L=t.add(L,M),new U(y,A,L)}subtract(z){return this.add(z.negate())}is0(){return this.equals(U.ZERO)}multiply(z){let{endo:j}=e;if(!r.isValidNot0(z))throw new Error("invalid scalar: out of range");let Y,H,I=m=>v.wNAFCached(this,m,U.normalizeZ);if(j){let{k1neg:m,k1:x,k2neg:y,k2:A}=j.splitScalar(z),{p:L,f:F}=I(x),{p:N,f:M}=I(A);H=F.add(M),Y=G(j.beta,L,N,m,y)}else{let{p:m,f:x}=I(z);Y=m,H=x}return U.normalizeZ([Y,H])[0]}multiplyUnsafe(z){let{endo:j}=e,Y=this;if(!r.isValid(z))throw new Error("invalid scalar: out of range");if(z===FE||Y.is0())return U.ZERO;if(z===Oy)return Y;if(v.hasPrecomputes(this))return this.multiply(z);if(j){let{k1neg:H,k1:I,k2neg:m,k2:x}=j.splitScalar(z),{p1:y,p2:A}=nLe(U,Y,I,x);return G(j.beta,y,A,H,m)}else return v.wNAFCachedUnsafe(Y,z)}multiplyAndAddUnsafe(z,j,Y){let H=this.multiplyUnsafe(j).add(z.multiplyUnsafe(Y));return H.is0()?void 0:H}toAffine(z){return B(this,z)}isTorsionFree(){let{isTorsionFree:z}=e;return i===Oy?!0:z?z(U,this):v.wNAFCachedUnsafe(this,o).is0()}clearCofactor(){let{clearCofactor:z}=e;return i===Oy?this:z?z(U,this):this.multiplyUnsafe(i)}toBytes(z=!0){return BC("isCompressed",z),this.assertValidity(),u(U,this,z)}toRawBytes(z=!0){return this.toBytes(z)}toHex(z=!0){return NE(this.toBytes(z))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}U.BASE=new U(n.Gx,n.Gy,t.ONE),U.ZERO=new U(t.ZERO,t.ONE,t.ZERO),U.Fp=t,U.Fn=r;let O=r.BITS,v=tLe(U,e.endo?Math.ceil(O/2):O);return U}function u$(n){let{CURVE:e,curveOpts:t}=K$(n),r=U$(e,t);return hLe(n,r)}function G$(n){return Uint8Array.of(n?2:3)}function dLe(n,e,t={}){NC(e,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=e.randomBytes||x$,i=e.hmac||((Y,...H)=>F$(e.hash,Y,so(...H))),{Fp:o,Fn:s}=n,{ORDER:a,BITS:c}=s;function l(Y){let H=a>>Oy;return Y>H}function u(Y){return l(Y)?s.neg(Y):Y}function d(Y,H){if(!s.isValidNot0(H))throw new Error(`invalid signature ${Y}: out of range 1..CURVE.n`)}class h{constructor(H,I,m){d("r",H),d("s",I),this.r=H,this.s=I,m!=null&&(this.recovery=m),Object.freeze(this)}static fromCompact(H){let I=s.BYTES,m=Ls("compactSignature",H,I*2);return new h(s.fromBytes(m.subarray(0,I)),s.fromBytes(m.subarray(I,I*2)))}static fromDER(H){let{r:I,s:m}=ud.toSig(Ls("DER",H));return new h(I,m)}assertValidity(){}addRecoveryBit(H){return new h(this.r,this.s,H)}recoverPublicKey(H){let I=o.ORDER,{r:m,s:x,recovery:y}=this;if(y==null||![0,1,2,3].includes(y))throw new Error("recovery id invalid");if(a*lLe<I&&y>1)throw new Error("recovery id is ambiguous for h>1 curve");let L=y===2||y===3?m+a:m;if(!o.isValid(L))throw new Error("recovery id 2 or 3 invalid");let F=o.toBytes(L),N=n.fromHex(so(G$((y&1)===0),F)),M=s.inv(L),T=J(Ls("msgHash",H)),Q=s.create(-T*M),_=s.create(x*M),S=n.BASE.multiplyUnsafe(Q).add(N.multiplyUnsafe(_));if(S.is0())throw new Error("point at infinify");return S.assertValidity(),S}hasHighS(){return l(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,s.neg(this.s),this.recovery):this}toBytes(H){if(H==="compact")return so(s.toBytes(this.r),s.toBytes(this.s));if(H==="der")return ZM(ud.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return NE(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return NE(this.toBytes("compact"))}}let f=nO(s,t.allowedPrivateKeyLengths,t.wrapPrivateKey),p={isValidPrivateKey(Y){try{return f(Y),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let Y=a;return k$(r(tO(Y)),Y)},precompute(Y=8,H=n.BASE){return H.precompute(Y,!1)}};function E(Y,H=!0){return n.fromPrivateKey(Y).toBytes(H)}function b(Y){if(typeof Y=="bigint")return!1;if(Y instanceof n)return!0;let I=Ls("key",Y).length,m=o.BYTES,x=m+1,y=2*m+1;if(!(t.allowedPrivateKeyLengths||s.BYTES===x))return I===x||I===y}function C(Y,H,I=!0){if(b(Y)===!0)throw new Error("first arg must be private key");if(b(H)===!1)throw new Error("second arg must be public key");return n.fromHex(H).multiply(f(Y)).toBytes(I)}let B=e.bits2int||function(Y){if(Y.length>8192)throw new Error("input is too large");let H=HE(Y),I=Y.length*8-c;return I>0?H>>BigInt(I):H},J=e.bits2int_modN||function(Y){return s.create(B(Y))},G=O0(c);function U(Y){return J8e("num < 2^"+c,Y,FE,G),s.toBytes(Y)}function O(Y,H,I=v){if(["recovered","canonical"].some(_=>_ in I))throw new Error("sign() legacy options not supported");let{hash:m}=e,{lowS:x,prehash:y,extraEntropy:A}=I;x==null&&(x=!0),Y=Ls("msgHash",Y),l$(I),y&&(Y=Ls("prehashed msgHash",m(Y)));let L=J(Y),F=f(H),N=[U(F),U(L)];if(A!=null&&A!==!1){let _=A===!0?r(o.BYTES):A;N.push(Ls("extraEntropy",_))}let M=so(...N),T=L;function Q(_){let S=B(_);if(!s.isValidNot0(S))return;let g=s.inv(S),K=n.BASE.multiply(S).toAffine(),w=s.create(K.x);if(w===FE)return;let q=s.create(g*s.create(T+w*F));if(q===FE)return;let V=(K.x===w?0:2)|Number(K.y&Oy),R=q;return x&&l(q)&&(R=u(q),V^=1),new h(w,R,V)}return{seed:M,k2sig:Q}}let v={lowS:e.lowS,prehash:!1},D={lowS:e.lowS,prehash:!1};function z(Y,H,I=v){let{seed:m,k2sig:x}=O(Y,H,I);return V8e(e.hash.outputLen,s.BYTES,i)(m,x)}n.BASE.precompute(8);function j(Y,H,I,m=D){let x=Y;H=Ls("msgHash",H),I=Ls("publicKey",I),l$(m);let{lowS:y,prehash:A,format:L}=m;if("strict"in m)throw new Error("options.strict was renamed to lowS");if(L!==void 0&&!["compact","der","js"].includes(L))throw new Error('format must be "compact", "der" or "js"');let F=typeof x=="string"||OC(x),N=!F&&!L&&typeof x=="object"&&x!==null&&typeof x.r=="bigint"&&typeof x.s=="bigint";if(!F&&!N)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let M,T;try{if(N)if(L===void 0||L==="js")M=new h(x.r,x.s);else throw new Error("invalid format");if(F){try{L!=="compact"&&(M=h.fromDER(x))}catch(R){if(!(R instanceof ud.Err))throw R}!M&&L!=="der"&&(M=h.fromCompact(x))}T=n.fromHex(I)}catch{return!1}if(!M||y&&M.hasHighS())return!1;A&&(H=e.hash(H));let{r:Q,s:_}=M,S=J(H),g=s.inv(_),K=s.create(S*g),w=s.create(Q*g),q=n.BASE.multiplyUnsafe(K).add(T.multiplyUnsafe(w));return q.is0()?!1:s.create(q.x)===Q}return Object.freeze({getPublicKey:E,getSharedSecret:C,sign:z,verify:j,utils:p,Point:n,Signature:h})}function K$(n){let e={a:n.a,b:n.b,p:n.Fp.ORDER,n:n.n,h:n.h,Gx:n.Gx,Gy:n.Gy},t=n.Fp,r=JE(e.n,n.nBitLength),i={Fp:t,Fn:r,allowedPrivateKeyLengths:n.allowedPrivateKeyLengths,allowInfinityPoint:n.allowInfinityPoint,endo:n.endo,wrapPrivateKey:n.wrapPrivateKey,isTorsionFree:n.isTorsionFree,clearCofactor:n.clearCofactor,fromBytes:n.fromBytes,toBytes:n.toBytes};return{CURVE:e,curveOpts:i}}function fLe(n){let{CURVE:e,curveOpts:t}=K$(n),r={hash:n.hash,hmac:n.hmac,randomBytes:n.randomBytes,lowS:n.lowS,bits2int:n.bits2int,bits2int_modN:n.bits2int_modN};return{CURVE:e,curveOpts:t,ecdsaOpts:r}}function hLe(n,e){let{Fp:t,Fn:r}=e;function i(a){return L$(a,Oy,r.ORDER)}let o=N$(t,n.a,n.b),s=nO(r,n.allowedPrivateKeyLengths,n.wrapPrivateKey);return Object.assign({},{CURVE:n,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:s,weierstrassEquation:o,isWithinCurveOrder:i})}function pLe(n,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:n})}function mLe(n){let{CURVE:e,curveOpts:t,ecdsaOpts:r}=fLe(n),i=U$(e,t),o=dLe(i,r,t);return pLe(n,o)}var gLe=BigInt(0),xC=BigInt(1),d$=BigInt(2),ky=BigInt(3);function yLe(n){let e=[];for(;n>xC;n>>=xC)(n&xC)===gLe?e.unshift(0):(n&ky)===ky?(e.unshift(-1),n+=xC):e.unshift(1);return e}function wLe(n){let{Fp:e,Fr:t,Fp2:r,Fp6:i,Fp12:o}=n.fields,s=u$(n.G1),a=Object.assign(s,c$(s.Point,n.G1.mapToCurve,{...n.htfDefaults,...n.G1.htfDefaults})),c=u$(n.G2),l=Object.assign(c,c$(c.Point,n.G2.mapToCurve,{...n.htfDefaults,...n.G2.htfDefaults})),u;u=(S,g,K,w,q,V)=>o.mul034(w,r.mul(K,V),r.mul(g,q),S);let d=r.div(r.ONE,r.mul(r.ONE,d$));function h(S,g,K,w){let q=r.sqr(K),V=r.sqr(w),R=r.mulByB(r.mul(V,ky)),X=r.mul(R,ky),re=r.sub(r.sub(r.sqr(r.add(K,w)),V),q),ee=r.sub(R,q),le=r.mul(r.sqr(g),ky),Be=r.neg(re);return S.push([ee,le,Be]),g=r.mul(r.mul(r.mul(r.sub(q,X),g),K),d),K=r.sub(r.sqr(r.mul(r.add(q,X),d)),r.mul(r.sqr(R),ky)),w=r.mul(q,re),{Rx:g,Ry:K,Rz:w}}function f(S,g,K,w,q,V){let R=r.sub(K,r.mul(V,w)),X=r.sub(g,r.mul(q,w)),re=r.sub(r.mul(R,q),r.mul(X,V)),ee=r.neg(R),le=X;S.push([re,ee,le]);let Be=r.sqr(X),xe=r.mul(Be,X),Pe=r.mul(Be,g),ct=r.add(r.sub(xe,r.mul(Pe,d$)),r.mul(r.sqr(R),w));return g=r.mul(X,ct),K=r.sub(r.mul(r.sub(Pe,ct),R),r.mul(xe,K)),w=r.mul(w,xe),{Rx:g,Ry:K,Rz:w}}let p=yLe(n.params.ateLoopSize),E=UM(S=>{let g=S,{x:K,y:w}=g.toAffine(),q=K,V=w,R=r.neg(w),X=q,re=V,ee=r.ONE,le=[];for(let Be of p){let xe=[];({Rx:X,Ry:re,Rz:ee}=h(xe,X,re,ee)),Be&&({Rx:X,Ry:re,Rz:ee}=f(xe,X,re,ee,q,Be===-1?R:V)),le.push(xe)}if(n.postPrecompute){let Be=le[le.length-1];n.postPrecompute(X,re,ee,q,V,f.bind(null,Be))}return le});function b(S,g=!1){let K=o.ONE;if(S.length){let w=S[0][0].length;for(let q=0;q<w;q++){K=o.sqr(K);for(let[V,R,X]of S)for(let[re,ee,le]of V[q])K=u(re,ee,le,K,R,X)}}return g?o.finalExponentiate(K):K}function C(S,g=!0){let K=[];GM(a.Point,"pz",S.map(({g1:w})=>w)),GM(l.Point,"pz",S.map(({g2:w})=>w));for(let{g1:w,g2:q}of S){if(w.is0()||q.is0())throw new Error("pairing is not available for ZERO point");w.assertValidity(),q.assertValidity();let V=w.toAffine();K.push([E(q),V.x,V.y])}return b(K,g)}function B(S,g,K=!0){return C([{g1:S,g2:g}],K)}let J=n.randomBytes||x$,G={randomPrivateKey:()=>{let S=tO(t.ORDER);return k$(J(S),t.ORDER)},calcPairingPrecomputes:E};function U(S){if(!Array.isArray(S)||S.length===0)throw new Error("expected non-empty array")}function O(S){return S instanceof a.Point?S:a.Point.fromHex(S)}function v(S){return S instanceof l.Point?S:H.fromHex(S)}function D(S,g){function K(R){return R instanceof S.Point?R:S.Point.fromHex(R)}function w(R){return R instanceof g.Point?R:g.Point.fromHex(R)}function q(R){if(!(R instanceof g.Point))throw new Error(`expected valid message hashed to ${V?"G2":"G1"} curve`);return R}let V=g.Point.Fp.BYTES>S.Point.Fp.BYTES;return{getPublicKey(R){return S.Point.fromPrivateKey(R)},sign(R,X,re){if(re!=null)throw new Error("sign() expects 2 arguments");return q(R).assertValidity(),R.multiply(S.normPrivateKeyToScalar(X))},verify(R,X,re,ee){if(ee!=null)throw new Error("verify() expects 3 arguments");R=w(R),re=K(re);let le=re.negate(),Be=S.Point.BASE,xe=q(X),Pe=R,Te=C(V?[{g1:le,g2:xe},{g1:Be,g2:Pe}]:[{g1:xe,g2:le},{g1:Pe,g2:Be}]);return o.eql(Te,o.ONE)},aggregatePublicKeys(R){U(R),R=R.map(re=>K(re));let X=R.reduce((re,ee)=>re.add(ee),S.Point.ZERO);return X.assertValidity(),X},aggregateSignatures(R){U(R),R=R.map(re=>w(re));let X=R.reduce((re,ee)=>re.add(ee),g.Point.ZERO);return X.assertValidity(),X},hash(R,X){Zo(R);let re=X?{DST:X}:void 0;return g.hashToCurve(R,re)},Signature:V?n.G2.Signature:n.G1.ShortSignature}}let z=D(a,l),j=D(l,a),{ShortSignature:Y}=n.G1,{Signature:H}=n.G2;function I(S,g){return S instanceof a.Point?S:j.hash(Ls("point",S),g?.DST)}function m(S,g){return S instanceof l.Point?S:z.hash(Ls("point",S),g?.DST)}function x(S){return z.getPublicKey(S).toBytes(!0)}function y(S){return j.getPublicKey(S).toBytes(!0)}function A(S,g,K){let w=m(S,K),q=z.sign(w,g);return S instanceof l.Point?q:H.toBytes(q)}function L(S,g,K){let w=I(S,K),q=j.sign(w,g);return S instanceof a.Point?q:Y.toBytes(q)}function F(S,g,K,w){let q=m(g,w);return z.verify(S,q,K)}function N(S,g,K,w){let q=I(g,w);return j.verify(S,q,K)}function M(S){let g=z.aggregatePublicKeys(S);return S[0]instanceof a.Point?g:g.toBytes(!0)}function T(S){let g=z.aggregateSignatures(S);return S[0]instanceof l.Point?g:H.toBytes(g)}function Q(S){let g=j.aggregateSignatures(S);return S[0]instanceof a.Point?g:Y.toBytes(g)}function _(S,g,K,w){if(U(g),K.length!==g.length)throw new Error("amount of public keys and messages should be equal");let q=v(S),V=g.map(ee=>m(ee,w)),R=K.map(O),X=new Map;for(let ee=0;ee<R.length;ee++){let le=R[ee],Be=V[ee],xe=X.get(Be);xe===void 0&&(xe=[],X.set(Be,xe)),xe.push(le)}let re=[];try{for(let[ee,le]of X){let Be=le.reduce((xe,Pe)=>xe.add(Pe));re.push({g1:Be,g2:ee})}return re.push({g1:a.Point.BASE.negate(),g2:q}),o.eql(C(re),o.ONE)}catch{return!1}}return a.Point.BASE.precompute(4),{longSignatures:z,shortSignatures:j,millerLoopBatch:b,pairing:B,pairingBatch:C,verifyBatch:_,curves:{G1:s.Point,G2:c.Point},fields:{Fr:t,Fp:e,Fp2:r,Fp6:i,Fp12:o},params:{ateLoopSize:n.params.ateLoopSize,twistType:n.params.twistType,r:n.params.r,G1b:n.G1.b,G2b:n.G2.b},utils:G,getPublicKey:x,getPublicKeyForShortSignatures:y,sign:A,signShortSignature:L,verify:F,verifyShortSignature:N,aggregatePublicKeys:M,aggregateSignatures:T,aggregateShortSignatures:Q,G1:a,G2:l,Signature:H,ShortSignature:Y}}var f$=BigInt(0),My=BigInt(1),dd=BigInt(2),h$=BigInt(3);function DM(n,e,t,r,i=1,o){let s=BigInt(o===void 0?r:o),a=t**BigInt(r),c=[];for(let l=0;l<i;l++){let u=BigInt(l+1),d=[];for(let h=0,f=My;h<r;h++){let p=(u*f-u)/s%a;d.push(n.pow(e,p)),f*=t}c.push(d)}return c}function bLe(n,e,t){let r=e.pow(t,(n.ORDER-My)/h$),i=e.pow(t,(n.ORDER-My)/dd);function o(h,f){let p=e.mul(e.frobeniusMap(h,1),r),E=e.mul(e.frobeniusMap(f,1),i);return[p,E]}let s=e.pow(t,(n.ORDER**dd-My)/h$),a=e.pow(t,(n.ORDER**dd-My)/dd);if(!e.eql(a,e.neg(e.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(h,f){return[e.mul(h,s),e.neg(f)]}let l=h=>(f,p)=>{let E=p.toAffine(),b=h(E.x,E.y);return f.fromAffine({x:b[0],y:b[1]})},u=l(o),d=l(c);return{psi:o,psi2:c,G2psi:u,G2psi2:d,PSI_X:r,PSI_Y:i,PSI2_X:s,PSI2_Y:a}}function ELe(n){let{ORDER:e}=n,t=JE(e),r=t.create(n.NONRESIDUE||BigInt(-1)),i=t.div(t.ONE,dd),o=DM(t,r,t.ORDER,2)[0],s=({c0:I,c1:m},{c0:x,c1:y})=>({c0:t.add(I,x),c1:t.add(m,y)}),a=({c0:I,c1:m},{c0:x,c1:y})=>({c0:t.sub(I,x),c1:t.sub(m,y)}),c=({c0:I,c1:m},x)=>{if(typeof x=="bigint")return{c0:t.mul(I,x),c1:t.mul(m,x)};let{c0:y,c1:A}=x,L=t.mul(I,y),F=t.mul(m,A),N=t.sub(L,F),M=t.sub(t.mul(t.add(I,m),t.add(y,A)),t.add(L,F));return{c0:N,c1:M}},l=({c0:I,c1:m})=>{let x=t.add(I,m),y=t.sub(I,m),A=t.add(I,I);return{c0:t.mul(x,y),c1:t.mul(A,m)}},u=I=>{if(I.length!==2)throw new Error("invalid tuple");let m=I.map(x=>t.create(x));return{c0:m[0],c1:m[1]}};function d(I,m){return typeof I=="bigint"&&f$<=I&&I<m}let h=e*e,f=u(n.FP2_NONRESIDUE),p={ORDER:h,isLE:t.isLE,NONRESIDUE:f,BITS:kE(h),BYTES:Math.ceil(kE(h)/8),MASK:O0(kE(h)),ZERO:{c0:t.ZERO,c1:t.ZERO},ONE:{c0:t.ONE,c1:t.ZERO},create:I=>I,isValid:({c0:I,c1:m})=>d(I,h)&&d(m,h),is0:({c0:I,c1:m})=>t.is0(I)&&t.is0(m),isValidNot0:I=>!p.is0(I)&&p.isValid(I),eql:({c0:I,c1:m},{c0:x,c1:y})=>t.eql(I,x)&&t.eql(m,y),neg:({c0:I,c1:m})=>({c0:t.neg(I),c1:t.neg(m)}),pow:(I,m)=>CC(p,I,m),invertBatch:I=>ME(p,I),add:s,sub:a,mul:c,sqr:l,addN:s,subN:a,mulN:c,sqrN:l,div:(I,m)=>p.mul(I,typeof m=="bigint"?t.inv(t.create(m)):p.inv(m)),inv:({c0:I,c1:m})=>{let x=t.inv(t.create(I*I+m*m));return{c0:t.mul(x,t.create(I)),c1:t.mul(x,t.create(-m))}},sqrt:I=>{if(n.Fp2sqrt)return n.Fp2sqrt(I);let{c0:m,c1:x}=I;if(t.is0(x))return PC(t,m)===1?p.create({c0:t.sqrt(m),c1:t.ZERO}):p.create({c0:t.ZERO,c1:t.sqrt(t.div(m,r))});let y=t.sqrt(t.sub(t.sqr(m),t.mul(t.sqr(x),r))),A=t.mul(t.add(y,m),i);PC(t,A)===-1&&(A=t.sub(A,y));let F=t.sqrt(A),N=p.create({c0:F,c1:t.div(t.mul(x,i),F)});if(!p.eql(p.sqr(N),I))throw new Error("Cannot find square root");let M=N,T=p.neg(M),{re:Q,im:_}=p.reim(M),{re:S,im:g}=p.reim(T);return _>g||_===g&&Q>S?M:T},isOdd:I=>{let{re:m,im:x}=p.reim(I),y=m%dd,A=m===f$,L=x%dd;return BigInt(y||A&&L)==My},fromBytes(I){if(I.length!==p.BYTES)throw new Error("fromBytes invalid length="+I.length);return{c0:t.fromBytes(I.subarray(0,t.BYTES)),c1:t.fromBytes(I.subarray(t.BYTES))}},toBytes:({c0:I,c1:m})=>so(t.toBytes(I),t.toBytes(m)),cmov:({c0:I,c1:m},{c0:x,c1:y},A)=>({c0:t.cmov(I,x,A),c1:t.cmov(m,y,A)}),reim:({c0:I,c1:m})=>({re:I,im:m}),mulByNonresidue:({c0:I,c1:m})=>p.mul({c0:I,c1:m},f),mulByB:n.Fp2mulByB,fromBigTuple:u,frobeniusMap:({c0:I,c1:m},x)=>({c0:I,c1:t.mul(m,o[x%2])})},E=({c0:I,c1:m,c2:x},{c0:y,c1:A,c2:L})=>({c0:p.add(I,y),c1:p.add(m,A),c2:p.add(x,L)}),b=({c0:I,c1:m,c2:x},{c0:y,c1:A,c2:L})=>({c0:p.sub(I,y),c1:p.sub(m,A),c2:p.sub(x,L)}),C=({c0:I,c1:m,c2:x},y)=>{if(typeof y=="bigint")return{c0:p.mul(I,y),c1:p.mul(m,y),c2:p.mul(x,y)};let{c0:A,c1:L,c2:F}=y,N=p.mul(I,A),M=p.mul(m,L),T=p.mul(x,F);return{c0:p.add(N,p.mulByNonresidue(p.sub(p.mul(p.add(m,x),p.add(L,F)),p.add(M,T)))),c1:p.add(p.sub(p.mul(p.add(I,m),p.add(A,L)),p.add(N,M)),p.mulByNonresidue(T)),c2:p.sub(p.add(M,p.mul(p.add(I,x),p.add(A,F))),p.add(N,T))}},B=({c0:I,c1:m,c2:x})=>{let y=p.sqr(I),A=p.mul(p.mul(I,m),dd),L=p.mul(p.mul(m,x),dd),F=p.sqr(x);return{c0:p.add(p.mulByNonresidue(L),y),c1:p.add(p.mulByNonresidue(F),A),c2:p.sub(p.sub(p.add(p.add(A,p.sqr(p.add(p.sub(I,m),x))),L),y),F)}},[J,G]=DM(p,f,t.ORDER,6,2,3),U={ORDER:p.ORDER,isLE:p.isLE,BITS:3*p.BITS,BYTES:3*p.BYTES,MASK:O0(3*p.BITS),ZERO:{c0:p.ZERO,c1:p.ZERO,c2:p.ZERO},ONE:{c0:p.ONE,c1:p.ZERO,c2:p.ZERO},create:I=>I,isValid:({c0:I,c1:m,c2:x})=>p.isValid(I)&&p.isValid(m)&&p.isValid(x),is0:({c0:I,c1:m,c2:x})=>p.is0(I)&&p.is0(m)&&p.is0(x),isValidNot0:I=>!U.is0(I)&&U.isValid(I),neg:({c0:I,c1:m,c2:x})=>({c0:p.neg(I),c1:p.neg(m),c2:p.neg(x)}),eql:({c0:I,c1:m,c2:x},{c0:y,c1:A,c2:L})=>p.eql(I,y)&&p.eql(m,A)&&p.eql(x,L),sqrt:li,div:(I,m)=>U.mul(I,typeof m=="bigint"?t.inv(t.create(m)):U.inv(m)),pow:(I,m)=>CC(U,I,m),invertBatch:I=>ME(U,I),add:E,sub:b,mul:C,sqr:B,addN:E,subN:b,mulN:C,sqrN:B,inv:({c0:I,c1:m,c2:x})=>{let y=p.sub(p.sqr(I),p.mulByNonresidue(p.mul(x,m))),A=p.sub(p.mulByNonresidue(p.sqr(x)),p.mul(I,m)),L=p.sub(p.sqr(m),p.mul(I,x)),F=p.inv(p.add(p.mulByNonresidue(p.add(p.mul(x,A),p.mul(m,L))),p.mul(I,y)));return{c0:p.mul(F,y),c1:p.mul(F,A),c2:p.mul(F,L)}},fromBytes:I=>{if(I.length!==U.BYTES)throw new Error("fromBytes invalid length="+I.length);return{c0:p.fromBytes(I.subarray(0,p.BYTES)),c1:p.fromBytes(I.subarray(p.BYTES,2*p.BYTES)),c2:p.fromBytes(I.subarray(2*p.BYTES))}},toBytes:({c0:I,c1:m,c2:x})=>so(p.toBytes(I),p.toBytes(m),p.toBytes(x)),cmov:({c0:I,c1:m,c2:x},{c0:y,c1:A,c2:L},F)=>({c0:p.cmov(I,y,F),c1:p.cmov(m,A,F),c2:p.cmov(x,L,F)}),fromBigSix:I=>{if(!Array.isArray(I)||I.length!==6)throw new Error("invalid Fp6 usage");return{c0:p.fromBigTuple(I.slice(0,2)),c1:p.fromBigTuple(I.slice(2,4)),c2:p.fromBigTuple(I.slice(4,6))}},frobeniusMap:({c0:I,c1:m,c2:x},y)=>({c0:p.frobeniusMap(I,y),c1:p.mul(p.frobeniusMap(m,y),J[y%6]),c2:p.mul(p.frobeniusMap(x,y),G[y%6])}),mulByFp2:({c0:I,c1:m,c2:x},y)=>({c0:p.mul(I,y),c1:p.mul(m,y),c2:p.mul(x,y)}),mulByNonresidue:({c0:I,c1:m,c2:x})=>({c0:p.mulByNonresidue(x),c1:I,c2:m}),mul1:({c0:I,c1:m,c2:x},y)=>({c0:p.mulByNonresidue(p.mul(x,y)),c1:p.mul(I,y),c2:p.mul(m,y)}),mul01({c0:I,c1:m,c2:x},y,A){let L=p.mul(I,y),F=p.mul(m,A);return{c0:p.add(p.mulByNonresidue(p.sub(p.mul(p.add(m,x),A),F)),L),c1:p.sub(p.sub(p.mul(p.add(y,A),p.add(I,m)),L),F),c2:p.add(p.sub(p.mul(p.add(I,x),y),L),F)}}},O=DM(p,f,t.ORDER,12,1,6)[0],v=({c0:I,c1:m},{c0:x,c1:y})=>({c0:U.add(I,x),c1:U.add(m,y)}),D=({c0:I,c1:m},{c0:x,c1:y})=>({c0:U.sub(I,x),c1:U.sub(m,y)}),z=({c0:I,c1:m},x)=>{if(typeof x=="bigint")return{c0:U.mul(I,x),c1:U.mul(m,x)};let{c0:y,c1:A}=x,L=U.mul(I,y),F=U.mul(m,A);return{c0:U.add(L,U.mulByNonresidue(F)),c1:U.sub(U.mul(U.add(I,m),U.add(y,A)),U.add(L,F))}},j=({c0:I,c1:m})=>{let x=U.mul(I,m);return{c0:U.sub(U.sub(U.mul(U.add(U.mulByNonresidue(m),I),U.add(I,m)),x),U.mulByNonresidue(x)),c1:U.add(x,x)}};function Y(I,m){let x=p.sqr(I),y=p.sqr(m);return{first:p.add(p.mulByNonresidue(y),x),second:p.sub(p.sub(p.sqr(p.add(I,m)),x),y)}}let H={ORDER:p.ORDER,isLE:U.isLE,BITS:2*U.BITS,BYTES:2*U.BYTES,MASK:O0(2*U.BITS),ZERO:{c0:U.ZERO,c1:U.ZERO},ONE:{c0:U.ONE,c1:U.ZERO},create:I=>I,isValid:({c0:I,c1:m})=>U.isValid(I)&&U.isValid(m),is0:({c0:I,c1:m})=>U.is0(I)&&U.is0(m),isValidNot0:I=>!H.is0(I)&&H.isValid(I),neg:({c0:I,c1:m})=>({c0:U.neg(I),c1:U.neg(m)}),eql:({c0:I,c1:m},{c0:x,c1:y})=>U.eql(I,x)&&U.eql(m,y),sqrt:li,inv:({c0:I,c1:m})=>{let x=U.inv(U.sub(U.sqr(I),U.mulByNonresidue(U.sqr(m))));return{c0:U.mul(I,x),c1:U.neg(U.mul(m,x))}},div:(I,m)=>H.mul(I,typeof m=="bigint"?t.inv(t.create(m)):H.inv(m)),pow:(I,m)=>CC(H,I,m),invertBatch:I=>ME(H,I),add:v,sub:D,mul:z,sqr:j,addN:v,subN:D,mulN:z,sqrN:j,fromBytes:I=>{if(I.length!==H.BYTES)throw new Error("fromBytes invalid length="+I.length);return{c0:U.fromBytes(I.subarray(0,U.BYTES)),c1:U.fromBytes(I.subarray(U.BYTES))}},toBytes:({c0:I,c1:m})=>so(U.toBytes(I),U.toBytes(m)),cmov:({c0:I,c1:m},{c0:x,c1:y},A)=>({c0:U.cmov(I,x,A),c1:U.cmov(m,y,A)}),fromBigTwelve:I=>({c0:U.fromBigSix(I.slice(0,6)),c1:U.fromBigSix(I.slice(6,12))}),frobeniusMap(I,m){let{c0:x,c1:y,c2:A}=U.frobeniusMap(I.c1,m),L=O[m%12];return{c0:U.frobeniusMap(I.c0,m),c1:U.create({c0:p.mul(x,L),c1:p.mul(y,L),c2:p.mul(A,L)})}},mulByFp2:({c0:I,c1:m},x)=>({c0:U.mulByFp2(I,x),c1:U.mulByFp2(m,x)}),conjugate:({c0:I,c1:m})=>({c0:I,c1:U.neg(m)}),mul014:({c0:I,c1:m},x,y,A)=>{let L=U.mul01(I,x,y),F=U.mul1(m,A);return{c0:U.add(U.mulByNonresidue(F),L),c1:U.sub(U.sub(U.mul01(U.add(m,I),x,p.add(y,A)),L),F)}},mul034:({c0:I,c1:m},x,y,A)=>{let L=U.create({c0:p.mul(I.c0,x),c1:p.mul(I.c1,x),c2:p.mul(I.c2,x)}),F=U.mul01(m,y,A),N=U.mul01(U.add(I,m),p.add(x,y),A);return{c0:U.add(U.mulByNonresidue(F),L),c1:U.sub(N,U.add(L,F))}},_cyclotomicSquare:n.Fp12cyclotomicSquare,_cyclotomicExp:n.Fp12cyclotomicExp,finalExponentiate:n.Fp12finalExponentiate};return{Fp:t,Fp2:p,Fp6:U,Fp12:H,Fp4Square:Y}}var ILe=BigInt(0),HM=BigInt(1),ah=BigInt(2),ALe=BigInt(3),H$=BigInt(6),UC=BigInt("4965661367192848881"),xLe=kE(UC),vLe=H$*UC**ah,GC={p:BigInt("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"),n:BigInt("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"),h:HM,a:ILe,b:ALe,Gx:HM,Gy:BigInt(2)},p$=JE(GC.n),J$={c0:BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),c1:BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")},{Fp:GE,Fp2:Fn,Fp6:JM,Fp4Square:TM,Fp12:Rn}=ELe({ORDER:GC.p,FP2_NONRESIDUE:[BigInt(9),HM],Fp2mulByB:n=>Fn.mul(n,J$),Fp12cyclotomicSquare:({c0:n,c1:e})=>{let{c0:t,c1:r,c2:i}=n,{c0:o,c1:s,c2:a}=e,{first:c,second:l}=TM(t,s),{first:u,second:d}=TM(o,i),{first:h,second:f}=TM(r,a),p=Fn.mulByNonresidue(f);return{c0:JM.create({c0:Fn.add(Fn.mul(Fn.sub(c,t),ah),c),c1:Fn.add(Fn.mul(Fn.sub(u,r),ah),u),c2:Fn.add(Fn.mul(Fn.sub(h,i),ah),h)}),c1:JM.create({c0:Fn.add(Fn.mul(Fn.add(p,o),ah),p),c1:Fn.add(Fn.mul(Fn.add(l,s),ah),l),c2:Fn.add(Fn.mul(Fn.add(d,a),ah),d)})}},Fp12cyclotomicExp(n,e){let t=Rn.ONE;for(let r=xLe-1;r>=0;r--)t=Rn._cyclotomicSquare(t),q8e(e,r)&&(t=Rn.mul(t,n));return t},Fp12finalExponentiate:n=>{let e=u=>Rn.conjugate(Rn._cyclotomicExp(u,UC)),t=Rn.mul(Rn.conjugate(n),Rn.inv(n)),r=Rn.mul(Rn.frobeniusMap(t,2),t),i=Rn._cyclotomicSquare(e(r)),o=Rn.mul(Rn._cyclotomicSquare(i),i),s=e(o),a=e(Rn._cyclotomicSquare(s)),c=Rn.mul(Rn.mul(Rn.conjugate(a),s),Rn.conjugate(o)),l=Rn.mul(c,i);return Rn.mul(Rn.frobeniusMap(Rn.mul(Rn.conjugate(r),l),3),Rn.mul(Rn.frobeniusMap(c,2),Rn.mul(Rn.frobeniusMap(l,1),Rn.mul(Rn.mul(c,s),r))))}}),{G2psi:SLe,psi:m$}=bLe(GE,Fn,Fn.NONRESIDUE),BM=Object.freeze({DST:"BN254G2_XMD:SHA-256_SVDW_RO_",encodeDST:"BN254G2_XMD:SHA-256_SVDW_RO_",p:GE.ORDER,m:2,k:128,expand:"xmd",hash:_M}),CLe=(n,e,t,r,i,o)=>{let s=m$(r,i);({Rx:n,Ry:e,Rz:t}=o(n,e,t,s[0],s[1]));let a=m$(s[0],s[1]);o(n,e,t,a[0],Fn.neg(a[1]))},LLe={p:Fn.ORDER,n:GC.n,h:BigInt("0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d"),a:Fn.ZERO,b:J$,Gx:Fn.fromBigTuple([BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")]),Gy:Fn.fromBigTuple([BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")])},F0=wLe({fields:{Fp:GE,Fp2:Fn,Fp6:JM,Fp12:Rn,Fr:p$},G1:{...GC,Fp:GE,htfDefaults:{...BM,m:1,DST:"BN254G2_XMD:SHA-256_SVDW_RO_"},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:li,fromBytes:li,toBytes:li,ShortSignature:{fromBytes:li,fromHex:li,toBytes:li,toRawBytes:li,toHex:li}},G2:{...LLe,Fp:Fn,hEff:BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),htfDefaults:{...BM},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(n,e)=>e.multiplyUnsafe(vLe).equals(SLe(n,e)),mapToCurve:li,fromBytes:li,toBytes:li,Signature:{fromBytes:li,fromHex:li,toBytes:li,toRawBytes:li,toHex:li}},params:{ateLoopSize:UC*H$+ah,r:p$.ORDER,xNegative:!1,twistType:"divisive"},htfDefaults:BM,hash:_M,postPrecompute:CLe});mLe({a:BigInt(0),b:BigInt(3),Fp:GE,n:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),Gx:BigInt(1),Gy:BigInt(2),h:BigInt(1),hash:_M});var KC="groth16",RLe="auth",DLe="authV2",TLe="authV3",BLe="authV3-8-32",PLe=new TextDecoder,g$=BigInt(0),y$=F0.fields.Fp2,w$=F0.fields.Fp12;async function rO(n,e,t){let r=await T8e(t),i=new TextDecoder().decode(n),o=JSON.parse(i),s=await r.calculateWTNSBin(o,0),{proof:a,publicSignals:c}=await EC.prove(e,s);return{proof:a,pub_signals:c}}var[qM,kLe]=[F0.G1.ProjectivePoint,F0.G2.ProjectivePoint],vC=([n,e])=>qM.fromAffine({x:BigInt(n),y:BigInt(e)}),SC=([[n,e],[t,r]])=>kLe.fromAffine({x:y$.fromBigTuple([BigInt(n),BigInt(e)]),y:y$.fromBigTuple([BigInt(t),BigInt(r)])});async function iO(n,e,t,r){if(r(e.pub_signals).challenge!==yI(n))throw new Error("challenge is not equal to message hash");let o=JSON.parse(PLe.decode(t));return oO(e,o)}function oO(n,e){if(!e.IC)throw new Error("verification file doesn't exist for circuit");let{proof:t,pub_signals:r}=n;if(r.length+1!==e.IC.length)throw new Error(`Invalid number of public signals, expected ${e.IC.length-1} but got ${r.length}`);let i=qM.ZERO;for(let s=0;s<r.length;s++){if(BigInt(r[s])<g$||BigInt(r[s])>=F0.G1.CURVE.n)throw new Error(`Input value is not in the field ${F0.G1.CURVE.n}`);if(BigInt(r[s])!==g$){let[a,c]=e.IC[s+1].map(BigInt);i=i.add(qM.fromAffine({x:a,y:c}).multiply(BigInt(r[s])))}}i=i.add(vC(e.IC[0]));let o=F0.pairingBatch([{g1:vC(t.pi_a).negate(),g2:SC(t.pi_b)},{g1:i,g2:SC(e.vk_gamma_2)},{g1:vC(t.pi_c),g2:SC(e.vk_delta_2)},{g1:vC(e.vk_alpha_1),g2:SC(e.vk_beta_2)}]);return w$.eql(o,w$.ONE)}var VM=class{methodAlg;constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}unmarshall(e){let t={};if(e.length!=3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return t.challenge=BigInt(e[0]),t.userState=BigInt(e[1]),t.userId=$e.fromBigInt(BigInt(e[2])),t}async verify(e,t,r){return iO(e,t,r,this.unmarshall)}prove(e,t,r){return rO(e,t,r)}},QM=new VM(new fd(KC,RLe)),zM=class n{methodAlg;static curveName="bn128";constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}async verify(e,t,r){return iO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await rO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await DE(n.curveName)).terminate()}unmarshall(e){if(e.length!==3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return{userID:$e.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},YM=new zM(new fd(KC,DLe)),MC=class n{methodAlg;static curveName="bn128";constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}async verify(e,t,r){return iO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await rO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await DE(n.curveName)).terminate()}unmarshall(e){if(e.length!==3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return{userID:$e.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},jM=new MC(new fd(KC,TLe)),WM=new MC(new fd(KC,BLe));KE(QM.methodAlg,()=>QM);KE(YM.methodAlg,()=>YM);KE(jM.methodAlg,()=>jM);KE(WM.methodAlg,()=>WM);var N0={registerProvingMethod:KE,getProvingMethod:I$,provingMethodGroth16AuthInstance:QM,provingMethodGroth16AuthV2Instance:YM,provingMethodGroth16AuthV3Instance:jM,provingMethodGroth16AuthV3_8_32Instance:WM};var q$="unknown circuit ID. can't verify msg sender",HC="sender of message is not used for jwz token creation",V$="message was packed with unsupported circuit",Q$="message proof is invalid",z$="message state verification failed",Y$="unknown proving method algorithm";var{getProvingMethod:MLe}=N0,sO=class{constructor(e){this.dataPrepareFunc=e}prepare(e,t,r){return this.dataPrepareFunc(e,t,r)}},aO=class{constructor(e){this.stateVerificationFunc=e}verify(e,t,r){return this.stateVerificationFunc(e,t,r)}},cO=class{constructor(e,t,r={acceptedStateTransitionDelay:L5}){this.provingParamsMap=e;this.verificationParamsMap=t;this._opts=r;let i=Array.from(this.provingParamsMap.keys()).map(s=>s.split(":")[1]),o=Array.from(this.verificationParamsMap.keys()).map(s=>s.split(":")[1]);this.supportedCircuitIds=[...new Set([...i,...o])]}supportedProtocolVersions=["iden3comm/v1"];supportedAlgorithms=["groth16"];supportedCircuitIds;packMessage(e,t){return this.pack(Fe.encode(JSON.stringify(e)),t)}async pack(e,t){let r=await MLe(t.provingMethodAlg),i=this.provingParamsMap.get(t.provingMethodAlg.toString());if(!i)throw new Error(Y$);let o=new ch(r,dt.decode(e),(a,c)=>i?.dataPreparer?.prepare(a,t.senderDID,c));o.setHeader(Ha.Type,"application/iden3-zkp-json");let s=await o.prove(i.provingKey,i.wasm);return Fe.encode(s)}async unpack(e){let t=await ch.parse(dt.decode(e)),r=new fd(t.alg,t.circuitId),i=this.verificationParamsMap.get(r.toString());if(!i?.key)throw new Error(V$);if(!await t.verify(i?.key))throw new Error(Q$);if(!await i?.verificationFn?.verify(t.circuitId,t.zkProof.pub_signals,this._opts))throw new Error(z$);let a=JSON.parse(t.getPayload());return OLe(t,a),a}mediaType(){return"application/iden3-zkp-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(",")};circuitIds=${this.supportedCircuitIds.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=Ss(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;let s=this.supportedCircuitIds,a=!i?.length||i.some(u=>s.includes(u)),c=this.supportedAlgorithms;return(!o?.length||o.some(u=>c.includes(u)))&&a}},OLe=async(n,e)=>{switch(n.circuitId){case"authV2":case"authV3-8-32":case"authV3":{if(!e.from)throw new Error(HC);let t=(n.circuitId==="authV2"?new _s:new C0).pubSignalsUnmarshal(Fe.encode(JSON.stringify(n.zkProof.pub_signals))),r=Se.parseFromId(t.userID),i=await n.getMessageHash();if(vt.bytesToInt(i.reverse())!==t.challenge)throw new Error(HC);if(e.from!==r.string())throw new Error(HC)}break;default:throw new Error(q$)}};var j$=(r=>(r.Pending="pending",r.Completed="completed",r.Rejected="rejected",r))(j$||{});var lO=(t=>(t.AUTHV2="authV2",t.ETH_IDENTITY="ethIdentity",t))(lO||{});var W$=(e=>(e.FeatureType="feature-type",e))(W$||{}),Z$=(i=>(i.Accept="accept",i.Protocol="protocol",i.GoalCode="goal-code",i.Header="header",i))(Z$||{});var Nl=N0.provingMethodGroth16AuthV2Instance.methodAlg,Fi=class{nextMessageHandler;setNext(e){return this.nextMessageHandler=e,e}async handle(e,t){return t.allowExpiredMessages||vr(e),this.nextMessageHandler?this.nextMessageHandler.handle(e,t):Promise.reject("Message handler not provided or message not supported")}},uO=class{constructor(e){this._params=e;this.registerHandlers(e.messageHandlers)}messageHandler;registerHandlers(e){if(!e.length)return;let[t,...r]=e,i=t;for(let o of r){let s=i;for(;s.nextMessageHandler;)s=s.nextMessageHandler;s.setNext(o)}this.messageHandler?this.messageHandler.setNext(t):this.messageHandler=t}async handleMessage(e,t){let{unpackedMediaType:r,unpackedMessage:i}=await this._params.packageManager.unpack(e);if(!this.messageHandler)return Promise.reject(new Error("Message handler not provided"));r==="application/iden3-zkp-json"&&(t.messageProvingMethodAlg=await Oc(e));let o=await this.messageHandler.handle(i,t);if(!o)return null;let s={},a=t?.senderDid;return r==="application/iden3-zkp-json"&&a?(s={senderDID:a,provingMethodAlg:await Oc(e)},this._params.packageManager.packMessage(r,o,s)):this._params.packageManager.packMessage("application/iden3comm-plain-json",o,s)}};async function Oc(n){try{let e=dt.decode(n);return(await ch.parse(e)).method.methodAlg}catch{return Nl}}var FLe=n=>n.reduce((e,t)=>{let r=t.query.groupId;if(!r)return e;let i=e.get(r);if(!i){let s=Uc(12),c=new DataView(s.buffer).getUint32(0);return e.set(r,{query:t.query,linkNonce:c}),e}let o=H8(i.query.credentialSubject,t.query.credentialSubject);return e.set(r,{...i,query:{skipClaimRevocationCheck:i.query.skipClaimRevocationCheck||t.query.skipClaimRevocationCheck,...i.query,credentialSubject:o}}),e},new Map),Ny=async(n,e,t,r,i)=>{let o=e??[],s=FLe(o),a=new Map,c=[];for(let l of o){let u;try{if(!i.supportedCircuits.includes(l.circuitId)){if(l.optional)continue;throw new Error(`Circuit ${l.circuitId} is not allowed`)}let h=l.query,f=h.groupId,p=s.get(f);if(f){if(!p)throw new Error(`Invalid group id ${h.groupId}`);let b=p.query;if(!a.has(f)){let C=await r.findCredentialByProofQuery(n,p.query);if(!C.cred){if(l.optional)continue;throw new Error(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+`${JSON.stringify(b)}`)}a.set(f,C)}}let E=a.get(f);u=await r.generateProof(l,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h.skipClaimRevocationCheck,credential:E?.cred,credentialRevocationStatus:E?.revStatus,linkNonce:p?.linkNonce?BigInt(p.linkNonce):void 0})}catch(d){let h=[qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,qe.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,qe.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED];if(d instanceof Error&&(h.includes(d.message)||d.message.includes(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY))&&l.optional)continue;throw d}c.push(u)}return c},dO=async(n,e,t)=>{switch(t.acceptProfile||(t.acceptProfile=hE),t.acceptProfile.env){case"application/iden3-zkp-json":if(!t.acceptProfile.circuits)throw new Error("Circuit not specified in accept profile");for(let r of t.acceptProfile.circuits){if(!t.supportedCircuits.includes(r))throw new Error(`Circuit ${r} is not supported`);if(!t.senderAddress)throw new Error("Sender address is not provided");let i=X$(t.senderAddress,t.zkpResponses),o=await e.generateAuthProof(r,n,{challenge:i});return{authProof:{authMethod:"authV2",zkp:o}}}throw new Error("Auth method is not supported");case"application/iden3comm-signed-json":if(!t.acceptProfile.alg||t.acceptProfile.alg.length===0)throw new Error("Algorithm not specified");if(t.acceptProfile.alg[0]==="ES256K-R")return{authProof:{authMethod:"ethIdentity",userDid:n}};throw new Error(`Algorithm ${t.acceptProfile.alg[0]} not supported`);default:throw new Error("Accept env not supported")}},qE=n=>{let e=n.id,t=n.pub_signals,r="0x";if(t.length===0)return{requestId:e,zkProofEncoded:r,metadata:r};let i=L0(n.proof),o=QS(t,i.a,i.b,i.c);return{requestId:e,zkProofEncoded:o,metadata:r}},X$=(n,e)=>{let t=e.map(r=>{let i=qE(r);return{requestId:i.requestId,proof:i.zkProofEncoded,metadata:i.metadata}});return BigInt(An.keccak256(new An.AbiCoder().encode(["address","(uint256 requestId,bytes proof,bytes metadata)[]"],[n,t])))&BigInt("0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")},NLe=n=>new An.AbiCoder().encode(["tuple(string key,bytes value)[]"],[n]),vr=n=>{if(n?.expires_time&&n.expires_time<Ct(new Date))throw new Error("Message expired")},na=(n,e,t)=>{if(n==="application/iden3comm-signed-json"||n==="application/iden3comm-encrypted-json"){if(!e)throw new Error(`packer options are required for ${n}`);return e}if(n==="application/iden3comm-plain-json")return{};if(n==="application/iden3-zkp-json"){let r={provingMethodAlg:e?.provingMethodAlg||t?.provingMethodAlg||Nl,senderDID:e?.senderDID||t?.senderDID};if(!r.senderDID)throw new Error("senderDID is required for ZKPMessage");return r}throw new Error(`unsupported media type ${n}`)};function ULe(n,e,t,r){return _$(n,"",e,t,r)}function _$(n,e,t,r,i){let o=Ft();return{id:o,thid:o,from:t,typ:"application/iden3comm-plain-json",type:ut.AUTHORIZATION_REQUEST_MESSAGE_TYPE,body:{accept:i?.accept,reason:n,message:e,callbackUrl:r,scope:i?.scope??[]},created_time:Ct(new Date),expires_time:i?.expires_time?Ct(i.expires_time):void 0,attachments:i?.attachments}}var fO=class extends Fi{constructor(t,r){super();this._packerMgr=t;this._proofService=r}_supportedCircuits=["credentialAtomicQueryV3-beta.1","credentialAtomicQuerySigV2","credentialAtomicQueryMTPV2","linkedMultiQuery10-beta.1"];handle(t,r){switch(t.type){case ut.AUTHORIZATION_REQUEST_MESSAGE_TYPE:return this.handleAuthRequest(t,r);case ut.AUTHORIZATION_RESPONSE_MESSAGE_TYPE:return this.handleAuthResponse(t,r);default:return super.handle(t,r)}}async parseAuthorizationRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==ut.AUTHORIZATION_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i.body.scope=i.body.scope||[],i}async handleAuthRequest(t,r){if(t.type!==ut.AUTHORIZATION_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for authorization request");let i=t.to?Se.parse(t.to):r.senderDid,o=Ft();if(!t.from)throw new Error("auth request should contain from field");let s=ut.AUTHORIZATION_RESPONSE_MESSAGE_TYPE,a=this.getSupportedMediaTypeByProfile(r,t.body.accept),c=Se.parse(t.from),l=await Ny(i,t?.body.scope,c,this._proofService,{mediaType:a,supportedCircuits:this._supportedCircuits});return{id:o,typ:a,type:s,thid:t.thid??o,body:{message:t?.body?.message,scope:l},from:i.string(),to:t.from}}async handleAuthorizationRequest(t,r,i){let o=await this.parseAuthorizationRequest(r);i?.allowExpiredMessages||vr(o),i||(i={mediaType:"application/iden3-zkp-json"});let s=await this.handleAuthRequest(o,{senderDid:t,mediaType:i.mediaType}),a=Fe.encode(JSON.stringify(s)),c=na(i.mediaType,i.packerOptions,{provingMethodAlg:this.getDefaultProvingMethodAlg(i.preferredAuthProvingMethod,o.body.accept),senderDID:t}),l=dt.decode(await this._packerMgr.pack(i.mediaType,a,c));return{authRequest:o,authResponse:s,token:l}}async handleAuthResponse(t,r){let i=r.request;if(t.type!==ut.AUTHORIZATION_RESPONSE_MESSAGE_TYPE)throw new Error("Invalid message type for authorization response");if((i.body.message??"")!==(t.body.message??""))throw new Error("message for signing from request is not presented in response");if(i.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${i.from}, given ${t.to}`);this.verifyAuthRequest(i);let o=i.body.scope||[],s=t.body.scope||[];if(!t.from)throw new Error("proof response doesn't contain from field");let a=new Map;for(let c of o){let l=c.query.groupId,u=s.find(E=>E.id.toString()===c.id.toString());if(!u)throw new Error(`proof is not given for requestId ${c.id}`);let d=u.circuitId;if(d!==c.circuitId)throw new Error(`proof is not given for requested circuit expected: ${c.circuitId}, given ${d}`);let h=c.params??{};h.verifierDid=Se.parse(i.from);let f=[r.acceptedProofGenerationDelay,r.acceptedStateTransitionDelay].some(E=>E!==void 0)?{acceptedProofGenerationDelay:r.acceptedProofGenerationDelay,acceptedStateTransitionDelay:r.acceptedStateTransitionDelay}:void 0,{linkID:p}=await this._proofService.verifyZKPResponse(u,{query:c.query,sender:t.from,params:h,opts:f});p&&l&&a.set(l,[...a.get(l)??[],{linkID:p,requestId:u.id}])}for(let[c,l]of a.entries())if(l.some(u=>u.linkID!==l[0].linkID))throw new Error(`Link id validation failed for group ${c}, request linkID to requestIds info: ${JSON.stringify(l)}`);return t}async handleAuthorizationResponse(t,r,i){i?.allowExpiredMessages||vr(t);let o=await this.handleAuthResponse(t,{request:r,acceptedStateTransitionDelay:i?.acceptedStateTransitionDelay,acceptedProofGenerationDelay:i?.acceptedProofGenerationDelay});return{request:r,response:o}}verifyAuthRequest(t){let r={},i=t.body.scope||[];for(let o of i){let s=o.query.groupId;if(s){let a=r[s]??[];for(let c of a){if(c.query.type!==o.query.type)throw new Error("all requests in the group should have the same type");if(c.query.context!==o.query.context)throw new Error("all requests in the group should have the same context");let l=o.query.allowedIssuers,u=c.query.allowedIssuers;if(!(l.includes("*")||l.every(d=>u.includes(d))))throw new Error("all requests in the group should have the same issuer")}r[s]=[...r[s]??[],o]}}}getSupportedMediaTypeByProfile(t,r){let i;if(!r?.length)return t.mediaType||"application/iden3-zkp-json";let o=[];for(let s of r){let{env:a}=Ss(s);this._packerMgr.isProfileSupported(a,s)&&o.push(a)}if(!o.length)throw new Error("no packer with profile which meets `accept` header requirements");return i=o.includes("application/iden3-zkp-json")?"application/iden3-zkp-json":o[0],t.mediaType&&o.includes(t.mediaType)&&(i=t.mediaType),i}getDefaultProvingMethodAlg(t,r){if(t&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",pE(t))&&(!r?.length||mE(r,t)))return t;if(r?.length){let i=N0.provingMethodGroth16AuthV3_8_32Instance.methodAlg;if(mE(r,i)&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",pE(i)))return i;let o=N0.provingMethodGroth16AuthV3Instance.methodAlg;if(mE(r,o)&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",pE(o)))return o}return Nl}};var $$=[{inputs:[],name:"MAX_SMT_DEPTH",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"key",type:"uint256"}],name:"getNode",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatus",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatusByIdAndState",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256[][]",name:"nodes",type:"uint256[][]"}],name:"saveNodes",outputs:[],stateMutability:"nonpayable",type:"function"}];var VE=class n{constructor(e,t,r){this._config=e;this._signer=r;this._provider=new jt(e.url);let i=new Ln(t,$$,this._provider);this._signer&&(this._signer=this._signer.connect(this._provider),i=i.connect(this._signer)),this._contract=i,this._transactionService=new $s(this._provider)}_contract;_provider;_transactionService;async getRevocationStatusByIdAndState(e,t,r){let i=await this._contract.getRevocationStatusByIdAndState(e,t,r),o=n.convertIssuerInfo(i.issuer),s=n.convertSmtProofToProof(i.mtp);return{issuer:o,mtp:s}}async getRevocationStatus(e,t){let r=await this._contract.getRevocationStatus(e,t),i=n.convertIssuerInfo(r.issuer),o=n.convertSmtProofToProof(r.mtp);return{issuer:i,mtp:o}}async saveNodes(e){if(!this._signer)throw new Error("No signer provided");let t=await this._provider.getFeeData(),r=this._config.maxFeePerGas?BigInt(this._config.maxFeePerGas):t.maxFeePerGas,i=this._config.maxPriorityFeePerGas?BigInt(this._config.maxPriorityFeePerGas):t.maxPriorityFeePerGas,o=await this._contract.saveNodes.estimateGas(e),s=await this._contract.saveNodes.populateTransaction(e),a={to:s.to,data:s.data,gasLimit:o,maxFeePerGas:r,maxPriorityFeePerGas:i},{txnReceipt:c}=await this._transactionService.sendTransactionRequest(this._signer,a);return c}static convertIssuerInfo(e){let[t,r,i,o]=e.map(s=>be.fromBigInt(s).hex());return{state:t,claimsTreeRoot:r,revocationTreeRoot:i,rootOfRoots:o}}static convertSmtProofToProof(e){let t,r=e.siblings?.map(i=>i.toString());return e.auxExistence&&(t={key:e.auxIndex.toString(),value:e.auxValue.toString()}),Bt.fromJSON({existence:e.existence,node_aux:t,siblings:r})}};function KLe(n){return typeof n=="object"&&n!==null&&"errorArgs"in n&&Array.isArray(n.errorArgs)}function HLe(n){return(KLe(n)?n.errorArgs[0]:void 0)||(n instanceof Error?n.message:"")}function Uy(n,e){return HLe(n).includes(e)}function QE(n){return Uy(n,qe.ERRORS.IDENTITY_DOES_NOT_EXIST)||Uy(n,qe.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR)}function hO(n){return Uy(n,qe.ERRORS.STATE_DOES_NOT_EXIST)||Uy(n,qe.ERRORS.STATE_DOES_NOT_EXIST_CUSTOM_ERROR)}function pO(n){return Uy(n,qe.ERRORS.ROOT_DOES_NOT_EXIST)||Uy(n,qe.ERRORS.ROOT_DOES_NOT_EXIST_CUSTOM_ERROR)}var mO=class{constructor(e,t){this._configs=e;this._stateStorage=new zE(e,t?.stateStorageOptions)}_stateStorage;async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");return this.getRevocationOnChain(e,t.issuerDID)}async getRevocationOnChain(e,t){let{contractAddress:r,chainId:i,revocationNonce:o,stateHex:s}=this.extractCredentialStatusInfo(e);if(o!==e.revocationNonce)throw new Error("revocationNonce does not match");let a=Se.idFromDID(t),c;try{let h=await this._stateStorage.getLatestStateById(a.bigInt());if(!h.state)throw new Error("state contract returned empty state");c=h.state}catch(h){if(!QE(h))throw h;if(!s)throw new Error("latest state not found and state parameter is not present in credentialStatus.id");let f=be.fromHex(s).bigInt();if(!tl(t,f))throw new Error(`latest state not found and state parameter ${s} is not genesis state`);c=f}let l=Se.idFromDID(t);return await this._getOnChainRevocationStorageForIssuer(i,r).getRevocationStatusByIdAndState(l.bigInt(),c,o)}extractCredentialStatusInfo(e){if(!e.id)throw new Error("credentialStatus id is empty");if(e.id.split("/").length!==2)throw new Error("invalid credentialStatus id");let r=new URL(e.id),i=r.searchParams.get("state")||"",o=r.searchParams.get("contractAddress");if(!o)throw new Error("contractAddress not found in credentialStatus.id field");let s=o.split(":");if(s.length!=2)throw new Error("invalid contract address encoding. should be chainId:contractAddress");let a=parseInt(s[0],10),c=s[1],l=r.searchParams.get("revocationNonce")||e.revocationNonce;if(l==null)throw new Error("revocationNonce not found in credentialStatus id field");let u=typeof l=="number"?l:parseInt(l,10);return{contractAddress:c,chainId:a,revocationNonce:u,stateHex:i}}networkByChainId(e){let t=this._configs.find(r=>r.chainId===e);if(!t)throw new Error(`chainId "${e}" not supported`);return t}_getOnChainRevocationStorageForIssuer(e,t){let r=this.networkByChainId(e);return new VE(r,t)}};var U0=class{async resolve(e){let r=await(await fetch(e.id)).json();return JC(r)}},JC=({issuer:n,mtp:e})=>({mtp:Bt.fromJSON(e),issuer:n});var G0=class n{constructor(e=Ue,t=[]){this.hash=e;this.children=t}nodeType(){return this.children.length===2?1:this.children.length===3&&this.children[2].hex()===be.fromBigInt(BigInt(1)).hex()?2:this.children.length===3?3:0}toJSON(){return{hash:this.hash.hex(),children:this.children.map(e=>e.hex())}}static fromHex(e){return new n(be.fromHex(e.hash),e.children.map(t=>be.fromHex(t)))}};var gO=class{constructor(e){this._state=e}async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");try{return await this.getStatus(e,t.issuerDID,t.issuerData,t.issuerGenesisState)}catch(r){if(e?.statusIssuer?.type==="SparseMerkleTreeProof")try{return await new U0().resolve(e.statusIssuer)}catch(i){throw new Error(`can't fetch revocation status from backup endpoint: ${i?.message}`)}throw new Error(`can't fetch revocation status: ${r?.message}`)}}async getStatus(e,t,r,i){let o=Se.idFromDID(t),s;try{let u=await this._state.getLatestStateById(o.bigInt());if(!u.state)throw new Error("state contract returned empty state");s=u.state}catch(u){if(!QE(u))throw u;let d=this.extractState(e.id);if(!d)return this.getRevocationStatusFromIssuerData(t,r,i);let h=be.fromHex(d).bigInt(),f=rp(t);if(!f&&!tl(t,h))throw new Error(`latest state not found and state parameter ${d} is not genesis state`);if(f)throw new Error("State must be published for Ethereum based identity");s=h}let a=e.id.split("/node")[0],c=be.fromBigInt(BigInt(e.revocationNonce??0)),l=be.fromBigInt(s);return await this.getRevocationStatusFromRHS(c,l,a)}getRevocationStatusFromIssuerData(e,t,r){if(r&&tl(e,r.value.bigInt()))return{mtp:new Bt,issuer:{state:r.value.hex(),revocationTreeRoot:r.revocationTreeRoot.hex(),rootOfRoots:r.rootOfRoots.hex(),claimsTreeRoot:r.claimsTreeRoot.hex()}};if(t&&tl(e,t.state.value))return{mtp:new Bt,issuer:{state:t.state.value,revocationTreeRoot:t.state.revocationTreeRoot,rootOfRoots:t.state.rootOfRoots,claimsTreeRoot:t.state.claimsTreeRoot}};throw new Error("issuer data / genesis state param is empty")}async getRevocationStatusFromRHS(e,t,r){if(!r)throw new Error("HTTP reverse hash service URL is not specified");let o=(await(await fetch(`${r}/node/${t.hex()}`)).json())?.node;if(o.children.length!==3)throw new Error("state should has tree children");let s=t.hex(),[a,c,l]=o.children,u=be.fromHex(c);return{mtp:await this.rhsGenerateProof(u,e,`${r}/node`),issuer:{state:s,claimsTreeRoot:a,revocationTreeRoot:c,rootOfRoots:l}}}async rhsGenerateProof(e,t,r){let i=!1,o=[],s,a=()=>new Bt({siblings:o,existence:i,nodeAux:s}),c=e;for(let l=0;l<t.bytes.length*8;l++){if(c.bytes.every(f=>f===0))return a();let d=(await(await fetch(`${r}/${c.hex()}`)).json())?.node,h=G0.fromHex(d);switch(h.nodeType()){case 2:return t.bytes.every((f,p)=>f===h.children[0].bytes[p])?(i=!0,a()):(s={key:h.children[0],value:h.children[1]},a());case 1:tw(t.bytes,l)?(c=h.children[1],o.push(h.children[0])):(c=h.children[0],o.push(h.children[1]));break;default:throw new Error(`found unexpected node type in tree ${h.hash.hex()}`)}}throw new Error("tree depth is too high")}extractState(e){return new URL(e).searchParams.get("state")}};function JLe(n,e){let t=Se.parse(n),r=Se.idFromDID(t),{method:i,blockchain:o,networkId:s}=Se.decodePartsFromId(r),a=vt.hexToBytes(e),c=vt.bytesToInt(a),l=Hc(i,o,s);return eee(Se.idFromDID(t).bigInt(),c,l)}function eee(n,e,t){let r=$e.idGenesisFromIdenState(t,e);return n.toString()===r.bigInt().toString()}var YE=class{resolvers=new Map;register(e,t){this.resolvers.set(e,t)}get(e){return this.resolvers.get(e)}};var jE=class{async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");if(!t?.userDID)throw new Error("UserDID is not set in options");if(typeof e.revocationNonce!="number")throw new Error("Revocation nonce is not set in credential status");let r=t.userDID.string(),i=t.issuerDID.string(),o=qLe(r,i,e.revocationNonce),a=await(await fetch(e.id,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})).json();return JC(a.body)}};function qLe(n,e,t){return{id:Ft(),typ:"application/iden3comm-plain-json",type:ut.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE,body:{revocation_nonce:t},thid:Ft(),from:n,to:e}}var WE=class{_publishers=new Map;register(e,...t){let r=this._publishers.get(e)??[];r.push(...t),this._publishers.set(e,r)}get(e){return this._publishers.get(e)}},yO=class{constructor(e){this._storage=e}async publish(e){if(!["Iden3OnchainSparseMerkleTreeProof2023"].includes(e.credentialStatusType))throw new Error(`On-chain publishing is not supported for credential status type ${e.credentialStatusType}`);let t=e.nodes.map(o=>o.children.map(s=>s.bigInt())),r=this._storage.saveNodes(t),i=e.onChain?.publishMode??"sync";switch(e.onChain?.txCallback&&(i="callback"),i){case"sync":await r;break;case"callback":{if(!e.onChain?.txCallback)throw new Error('txCallback is required for publishMode "callback"');let o=e.onChain?.txCallback;r.then(s=>o(s));break}case"async":{let o=Yw.getInstance();r.then(s=>o.publish(ZR.TX_RECEIPT_ACCEPTED,s));break}default:throw new Error(`Invalid publishMode: ${i}`)}}},K0=class{async publish(e){if(!["Iden3ReverseSparseMerkleTreeProof"].includes(e.credentialStatusType))throw new Error(`On-chain publishing is not supported for credential status type ${e.credentialStatusType}`);let t=e.nodes.map(i=>i.toJSON()),r=await fetch(e.rhsUrl+"/node",{method:"post",body:JSON.stringify(t)});if(r.status!==200)throw new Error(`Failed to publish credential status. Status: ${r.status}`)}};var wO=class{constructor(e){this.didResolverUrl=e}async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");let r=`${this.didResolverUrl}/1.0/credential-status/${encodeURIComponent(t.issuerDID.string())}`;return await(await fetch(r,{method:"POST",body:JSON.stringify(e)})).json()}};var bO=class{constructor(e,t){this._storage=e;this._credentialStatusResolverRegistry=t;this._credentialStatusResolverRegistry||(this._credentialStatusResolverRegistry=new YE,this._credentialStatusResolverRegistry.register("SparseMerkleTreeProof",new U0),this._credentialStatusResolverRegistry.register("Iden3commRevocationStatusV1.0",new jE))}async getAuthBJJCredential(e){let t=await this._storage.credential.findCredentialsByQuery({context:qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:qe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]});if(!t.length)throw new Error(qe.ERRORS.NO_AUTH_CRED_FOUND);for(let r=0;r<t.length;r++){let i=t[r];if(!(await this.getRevocationStatusFromCredential(i)).mtp.existence)return i}throw new Error("all auth bjj credentials are revoked")}async getAllAuthBJJCredentials(e){return this._storage.credential.findCredentialsByQuery({context:qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:qe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]})}async getRevocationStatusFromCredential(e){let t=e.getIden3SparseMerkleTreeProof(),r=e.getBJJSignature2021Proof(),i=t?t.issuerData.state:r?.issuerData.state,o=Se.parse(e.issuer),s=Vu(o,e),a={issuerGenesisState:i,issuerDID:o,userDID:s};return this.getRevocationStatus(e.credentialStatus,a)}async getRevocationStatus(e,t){let r=this._credentialStatusResolverRegistry?.get(e.type);if(!r)throw new Error(`credential status resolver does not exist for ${e.type} type`);return r.resolve(e,t)}createCredential=(e,t,r)=>{if(!r.$metadata.uris.jsonLdContext)throw new Error("jsonLdContext is missing is the schema");let i={...t};return i.context=i.context??[],i.displayMethod?.type==="Iden3BasicDisplayMethodV1"&&!i.context.includes(qe.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)&&i.context.push(qe.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD),i.context.push(r.$metadata.uris.jsonLdContext),i.expiration=i.expiration?i.expiration*1e3:void 0,i.id=i.id?i.id:`urn:${Ft()}`,i.issuanceDate=i.issuanceDate?i.issuanceDate*1e3:Date.now(),Gr.fromCredentialRequest(e,i)};async findById(e){return this._storage.credential.findCredentialById(e)}async findByContextType(e,t){return this._storage.credential.findCredentialsByQuery({context:e,type:t})}async save(e){return this._storage.credential.saveCredential(e)}async saveAll(e){return this._storage.credential.saveAllCredentials(e)}async remove(e){return this._storage.credential.removeCredential(e)}async list(){return this._storage.credential.listCredentials()}async findByQuery(e){return this._storage.credential.findCredentialsByQuery(e)}async filterByCredentialSubject(e,t){return e.filter(r=>r.credentialSubject.id===t.string())}async findNonRevokedCredential(e){for(let t of e){let r=await this.getRevocationStatusFromCredential(t);if(!r.mtp.existence)return{cred:t,revStatus:r}}throw new Error(qe.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED)}};async function qC(n,e,t,r){let i=await VC(r,e,n);await new K0().publish({nodes:i,credentialStatusType:"Iden3ReverseSparseMerkleTreeProof",rhsUrl:t})}async function VC(n,e,t){let r=new EO;return n&&await QLe(r,e,n),await VLe(r,e),t.bytes.every(i=>i===0)||r.addProofNode(new G0(t,[await e.claimsTree.root(),await e.revocationTree.root(),await e.rootsTree.root()])),r.nodes}async function VLe(n,e){let t=e.rootsTree,r=e.claimsTree;return n.addKey(t,(await r.root()).bigInt())}async function QLe(n,e,t){let r=e.revocationTree;for(let i of t)await n.addKey(r,BigInt(i))}var EO=class{constructor(e=[],t=new Map){this.nodes=e;this.seen=t}async addKey(e,t){let{value:r,siblings:i}=await e.get(t),o=be.fromBigInt(t),s=be.fromBigInt(r),a=new qc(o,s),c=await zLe(i,a);for(let l of c)this.seen.get(l.hash.hex())||(this.nodes.push(l),this.seen.set(l.hash.hex(),!0))}addProofNode(e){let t=e.hash.hex();this.seen.get(t)||(this.nodes.push(e),this.seen.set(t,!0))}};async function zLe(n,e){if(e.type!==sa)throw new Error("node is not a leaf");let t=await e.getKey(),r=n.length,i=new Array(r+1);for(let a=0;a<i.length;a++)i[a]=new G0;i[r].hash=t;let o=be.fromBigInt(BigInt(1));i[r].children=[e.entry[0],e.entry[1],o];let s=e.entry[0];for(let a=r-1;a>=0;a--){let c=tw(s.bytes,a);i[a].children=new Array(2),c?(i[a].children[0]=n[a],i[a].children[1]=t):(i[a].children[0]=t,i[a].children[1]=n[a]),i[a].hash=hh([i[a].children[0].bigInt(),i[a].children[1].bigInt()]),t=i[a].hash}return i}var IO=class n extends Fi{constructor(t,r){super();this._packerMgr=t;this.opts=r}async handle(t,r){switch(t.type){case ut.CREDENTIAL_OFFER_MESSAGE_TYPE:{let i=await this.handleOfferMessage(t,r);if(Array.isArray(i)){let o=this.opts?.credentialWallet;if(!o)throw new Error("Credential wallet is not provided");return await o.saveAll(i),null}return i}case ut.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE:return this.handleFetchRequest(t);case ut.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:return this.handleIssuanceResponseMsg(t);case ut.CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE:{let i=await this.handleOnchainOfferMessage(t);if(Array.isArray(i)){let o=this.opts?.credentialWallet;if(!o)throw new Error("Credential wallet is not provided");return await o.saveAll(i),null}return i}default:return super.handle(t,r)}}async handleOnchainOfferMessage(t){if(!this.opts?.onchainIssuer)throw new Error("onchain issuer is not provided");let r=[];for(let i of t.body.credentials){let o=Se.parse(t.from),s=Se.parse(t.to),a=await this.opts.onchainIssuer.getCredential(o,s,BigInt(i.id));r.push(a)}return r}async handleOfferMessage(t,r){r.mediaType||(r.mediaType="application/iden3-zkp-json");let i=[];for(let o of t.body.credentials){let s=Ft(),a={id:s,typ:r.mediaType,type:ut.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE,thid:t.thid??s,body:{id:o.id},from:t.to,to:t.from},c=Fe.encode(JSON.stringify(a)),l=Se.parse(t.to),u=na(r.mediaType,r.packerOptions,{senderDID:l}),d=dt.decode(await this._packerMgr.pack(r.mediaType,c,u));try{if(!t?.body?.url)throw new Error("could not fetch W3C credential, body url is missing");let f=await(await fetch(t.body.url,{method:"post",headers:{"Content-Type":"application/x-www-form-urlencoded",...r.headers},body:d})).arrayBuffer();if(!f.byteLength)throw new Error(`could not fetch , ${o?.id}, response is empty`);let{unpackedMessage:p}=await this._packerMgr.unpack(new Uint8Array(f));if(p.type!==ut.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE)return p;i.push(Gr.fromJSON(p.body.credential))}catch(h){throw new Error(`could not fetch protocol message for credential offer id: , ${o?.id}, error: ${h.message??h}`)}}return i}async handleCredentialOffer(t,r){let i=await n.unpackMessage(this._packerMgr,t,ut.CREDENTIAL_OFFER_MESSAGE_TYPE);r?.allowExpiredMessages||vr(i);let o=r?.mediaType||"application/iden3-zkp-json",s=na(o,r?.packerOptions,{provingMethodAlg:r?.messageProvingMethodAlg||await Oc(t),senderDID:Se.parse(i.to)}),a=await this.handleOfferMessage(i,{mediaType:o,headers:r?.headers,packerOptions:s});if(Array.isArray(a))return a;throw new Error("invalid protocol message response")}async handleOnchainOffer(t){let r=await n.unpackMessage(this._packerMgr,t,ut.CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE);return this.handleOnchainOfferMessage(r)}async handleFetchRequest(t){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");let r=Se.parse(t.to),i=Se.parse(t.from),o=t.body?.id;if(!o)throw new Error("invalid credential id in fetch request body");if(!this.opts?.credentialWallet)throw new Error("please, provide credential wallet in options");let s=await this.opts.credentialWallet.findById(o);if(!s)throw new Error("credential not found");if(Vu(r,s).string()!==i.string())throw new Error("credential subject is not a sender DID");return{id:Ft(),type:ut.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE,typ:t.typ??"application/iden3comm-plain-json",thid:t.thid??Ft(),body:{credential:s},from:t.to,to:t.from}}async handleCredentialFetchRequest(t,r){let i=await n.unpackMessage(this._packerMgr,t,ut.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);r?.allowExpiredMessages||vr(i);let o=await this.handleFetchRequest(i);return this._packerMgr.pack("application/iden3comm-plain-json",Fe.encode(JSON.stringify(o)),{})}async handleIssuanceResponseMsg(t){if(!this.opts?.credentialWallet)throw new Error("please provide credential wallet in options");if(!t.body?.credential)throw new Error("credential is missing in issuance response message");if(!(t.body.credential instanceof Gr))throw new Error("credential object is not properly unmarshaled");return await this.opts.credentialWallet.save(t.body.credential),null}async handleIssuanceResponseMessage(t,r){let i=await n.unpackMessage(this._packerMgr,t,ut.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);return r?.allowExpiredMessages||vr(i),i.body.credential=Gr.fromJSON(i.body.credential),await this.handleIssuanceResponseMsg(i),Uint8Array.from([])}static async unpackMessage(t,r,i){let{unpackedMessage:o}=await t.unpack(r),s=o;if(o.type!==i)throw new Error("Invalid message type");return s}};var AO=class extends Fi{constructor(t,r,i){super();this._packerMgr=t;this._proofService=r;this._zkpVerifier=i}_supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1","authV2","credentialAtomicQueryV3-beta.1","linkedMultiQuery10-beta.1"];async handle(t,r){switch(t.type){case ut.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE:{let i=t,o=await this.handleContractInvoke(i,r);return this.createContractInvokeResponse(i,o)}default:return super.handle(t,r)}}async handleContractInvoke(t,r){if(t.type!==ut.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for contract invoke request");let{senderDid:i,ethSigner:o,challenge:s}=r;if(!r.ethSigner)throw new Error("Can't sign transaction. Provide Signer in options.");let{chain_id:a}=t.body.transaction_data;if(!Object.keys(ra).find(f=>ra[f]===a))throw new Error(`Invalid chain id ${a}`);let l=t.from?Se.parse(t.from):void 0,{scope:u=[]}=t.body,d=await Ny(i,u,l,this._proofService,{ethSigner:o,challenge:s??vt.bytesToInt(Ui(await o.getAddress())),supportedCircuits:this._supportedCircuits});switch(t.body.transaction_data.method_id.replace("0x","")){case"ade09fcd":{let f=await this._zkpVerifier.submitZKPResponseV2(o,t.body.transaction_data,d),p=new Map;for(let[E,b]of f)p.set(E,{responses:b});return t.body.transaction_data.txHash=f.keys().next().value,p}case"b68967e2":{let f=await this._zkpVerifier.submitZKPResponse(o,t.body.transaction_data,d),p=new Map;for(let[E,b]of f)p.set(E,{responses:[b]});return t.body.transaction_data.txHash=f.keys().next().value,p}case"06c86a91":{if(!t.to)throw new Error("failed message. empty 'to' field");let f=this.getFirstSupportedProfile(ut.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE,t.body.accept),p=Se.parse(t.to),{authProof:E}=await dO(p,this._proofService,{supportedCircuits:this._supportedCircuits,acceptProfile:f,senderAddress:await o.getAddress(),zkpResponses:d}),b=await this._zkpVerifier.submitResponse(o,t.body.transaction_data,d,E);return t.body.transaction_data.txHash=b.keys().next().value,b}default:throw new Error("Not supported method id. Only 'b68967e2, ade09fcd and 06c86a91 are supported.'")}}getFirstSupportedProfile(t,r){if(r?.length)for(let i of r){let o=Ss(i),s=Number(t.split("/").at(-2));if(!(o.protocolVersion!=="iden3comm/v1"||o.protocolVersion==="iden3comm/v1"&&(s<1||s>=2))&&this._packerMgr.isProfileSupported(o.env,i))return o}return hE}async parseContractInvokeRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==ut.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i.body.scope=i.body.scope||[],i}async createContractInvokeResponse(t,r){let i={id:t.id,thid:t.thid,type:ut.CONTRACT_INVOKE_RESPONSE_MESSAGE_TYPE,from:t.to,to:t.from,body:{transaction_data:t.body.transaction_data,scope:[]},created_time:Ct(new Date)};for(let[o,s]of r){for(let a of s.responses)i.body.scope.push({txHash:o,...a});i.body={...i.body,crossChainProof:s.crossChainProof,authProof:s.authProof}}return i}async handleContractInvokeRequest(t,r,i){let o=await this.parseContractInvokeRequest(r);if(i.allowExpiredMessages||vr(o),o.body.transaction_data.method_id!=="b68967e2")throw new Error("please use handle method to work with other method ids");if(o.type!==ut.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for contract invoke request");let{ethSigner:s,challenge:a}=i;if(!s)throw new Error("Can't sign transaction. Provide Signer in options.");let{chain_id:c}=o.body.transaction_data;if(!Object.keys(ra).find(h=>ra[h]===c))throw new Error(`Invalid chain id ${c}`);let u=o.from?Se.parse(o.from):void 0,d=await Ny(t,o?.body?.scope,u,this._proofService,{ethSigner:s,challenge:a,supportedCircuits:this._supportedCircuits});return this._zkpVerifier.submitZKPResponse(s,o.body.transaction_data,d)}};var xO=class{constructor(e){this._options=e}async refreshCredential(e,t){if(!e.refreshService)throw new Error("refreshService not specified for W3CCredential");if(e.refreshService.type!=="Iden3RefreshService2023")throw new Error(`refresh service type ${e.refreshService.type} is not supported`);let r=e.credentialSubject.id;if(!r)throw new Error("self credentials do not support refresh");let i=Se.parse(r),o=t?.mediaType||"application/iden3-zkp-json",s=t?.packerOptions??{senderDID:i,provingMethodAlg:Nl},a={id:Ft(),typ:"application/iden3-zkp-json",type:ut.CREDENTIAL_REFRESH_MESSAGE_TYPE,thid:Ft(),body:{id:e.id,reason:t?.reason??"credential is expired"},from:r,to:e.issuer},c=Fe.encode(JSON.stringify(a)),l=await this._options.packageManager.pack(o,c,s),u=await fetch(e.refreshService.id,{method:"post",headers:{"Content-Type":"application/json"},body:l.buffer});if(u.status!==200)throw new Error(`could not refresh W3C credential, return status ${u.status}`);let d=await u.json();if(!d.body?.credential)throw new Error("no credential in CredentialIssuanceMessage response");return Gr.fromJSON(d.body.credential)}};var vO=class extends Fi{constructor(t,r){super();this._packerMgr=t;this._identityWallet=r}handle(t,r){if(!r.senderDid)throw new Error("DID is required");if(!r.mediaType)throw new Error("mediaType is required");switch(t.type){case ut.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE:return this.handleRevocationStatusRequestMessage(t,r);default:return super.handle(t,r)}}async handleRevocationStatusRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body?.revocation_nonce)throw new Error("failed request. empty 'revocation_nonce' field");let i=Se.parse(t.to),o=await this._identityWallet.generateNonRevocationMtpWithNonce(i,BigInt(t.body.revocation_nonce),r.treeState),s=o.treeState,a={issuer:{state:s?.state.string(),claimsTreeRoot:s.claimsRoot.string(),revocationTreeRoot:s.revocationRoot.string(),rootOfRoots:s.rootOfRoots.string()},mtp:o.proof},c=Ft();return{id:c,typ:"application/iden3comm-plain-json",type:ut.REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE,thid:t.thid??c,body:a,from:r.senderDid.string(),to:t.from}}async parseRevocationStatusRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==ut.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handleRevocationStatusRequest(t,r,i){i||(i={mediaType:"application/iden3comm-plain-json"});let o=await this.parseRevocationStatusRequest(r);i.allowExpiredMessages||vr(o);let s=await this.handleRevocationStatusRequestMessage(o,{senderDid:t,mediaType:i.mediaType,packerOptions:i.packerOptions,treeState:i.treeState});if(!o.to)throw new Error("failed request. empty 'to' field");let a=Se.parse(o.to),c=na(i.mediaType,i.packerOptions,{senderDID:a,provingMethodAlg:i.packerOptions?.provingMethodAlg||await Oc(r)});return this._packerMgr.pack(i.mediaType,Fe.encode(JSON.stringify(s)),c)}};function YLe(n,e,t){let r=Ft();return{id:r,thid:r,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:ut.PROPOSAL_REQUEST_MESSAGE_TYPE,body:{credentials:t.credentials,did_doc:t.did_doc},created_time:Ct(new Date),expires_time:t?.expires_time?Ct(t.expires_time):void 0,attachments:t.attachments}}function jLe(n,e,t,r){let i=Ft();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:ut.PROPOSAL_MESSAGE_TYPE,body:{proposals:t||[]},created_time:Ct(new Date),expires_time:r?.expires_time?Ct(r.expires_time):void 0}}var SO=class extends Fi{constructor(t,r,i){super();this._packerMgr=t;this._identityWallet=r;this._params=i}async handle(t,r){switch(t.type){case ut.PROPOSAL_REQUEST_MESSAGE_TYPE:return await this.handleProposalRequestMessage(t,r);default:return super.handle(t,r)}}async parseProposalRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==ut.PROPOSAL_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handleProposalRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body?.credentials?.length)throw new Error("failed request. no 'credentials' in body");let i,o;for(let s=0;s<t.body.credentials.length;s++){let a=t.body.credentials[s],c=[];try{c=await this._identityWallet.credentialWallet.findByQuery({credentialSubject:{id:{$eq:t.from}},type:a.type,context:a.context,allowedIssuers:[t.to]})}catch(u){if(u.message!=="no credential satisfied query")throw u}if(c.length){let u=Ft();i||(i={id:u,typ:this._params.packerParams.mediaType,type:ut.CREDENTIAL_OFFER_MESSAGE_TYPE,thid:t.thid??u,body:{url:this._params.agentUrl,credentials:[]},from:t.to,to:t.from}),i.body.credentials.push(...c.map(d=>({id:d.id,description:""})));continue}let l=await this._params.proposalResolverFn(a.context,a.type,{msg:t});if(!l)throw new Error(`can't resolve Proposal for type: ${a.type}, context: ${a.context}`);if(!o){let u=Ft();o={id:u,typ:this._params.packerParams.mediaType,type:ut.PROPOSAL_MESSAGE_TYPE,thid:t.thid??u,body:{proposals:[]},from:t.to,to:t.from}}o.body?.proposals.push(l)}return o??i}async handleProposalRequest(t,r){let i=await this.parseProposalRequest(t);if(!i.from)throw new Error("failed request. empty 'from' field");r?.allowExpiredMessages||vr(i);let o=Se.parse(i.from),s=await this.handleProposalRequestMessage(i),a=Fe.encode(JSON.stringify(s)),c=na(this._params.packerParams.mediaType,this._params.packerParams.packerOptions,{provingMethodAlg:await Oc(t),senderDID:o});return this._packerMgr.pack(this._params.packerParams.mediaType,a,c)}async handleProposal(t,r){if(r?.allowExpiredMessages||vr(t),r?.proposalRequest&&r.proposalRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.proposalRequest.from}, given ${t.to}`);return{proposal:t}}};function tee(n,e,t,r,i){let o=Ft();return{id:o,thid:o,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:ut.PAYMENT_REQUEST_MESSAGE_TYPE,body:{agent:t,payments:r},created_time:Ct(new Date),expires_time:i?.expires_time?Ct(i.expires_time):void 0}}function nee(n,e,t,r){let i=Ft();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:ut.PAYMENT_MESSAGE_TYPE,body:{payments:t},created_time:Ct(new Date),expires_time:r?.expires_time?Ct(r.expires_time):void 0}}var CO=class extends Fi{constructor(t,r){super();this._packerMgr=t;this._params=r}async handle(t,r){switch(t.type){case ut.PAYMENT_REQUEST_MESSAGE_TYPE:return await this.handlePaymentRequestMessage(t,r);case ut.PAYMENT_MESSAGE_TYPE:return await this.handlePayment(t,r),null;default:return super.handle(t,r)}}async parsePaymentRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==ut.PAYMENT_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handlePaymentRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body.payments?.length)throw new Error("failed request. no 'payments' in body");if(!r.paymentHandler)throw new Error("please provide payment handler in context");let i=Se.parse(t.to),o=Se.parse(t.from),s=[];for(let p=0;p<t.body.payments.length;p++){let{data:E}=t.body.payments[p],b=Array.isArray(E)?E.find(C=>C.type==="Iden3PaymentRequestCryptoV1"?C.id===r.nonce:C.nonce===r.nonce):E;if(!b)throw new Error(`failed request. no payment in request for nonce ${r.nonce}`);switch(b.type){case"Iden3PaymentRequestCryptoV1":s.push(await this.handleIden3PaymentRequestCryptoV1(b,r.paymentHandler));break;case"Iden3PaymentRailsRequestV1":s.push(await this.handleIden3PaymentRailsRequestV1(b,r.paymentHandler));break;case"Iden3PaymentRailsERC20RequestV1":s.push(await this.handleIden3PaymentRailsERC20RequestV1(b,r.paymentHandler,r.erc20TokenApproveHandler));break;case"Iden3PaymentRailsSolanaRequestV1":s.push(await this.handleIden3PaymentRailsSolanaRequestV1(b,r.paymentHandler));break;case"Iden3PaymentRailsSolanaSPLRequestV1":s.push(await this.handleIden3PaymentRailsSolanaSPLRequestV1({...b,type:"Iden3PaymentRailsSolanaSPLRequestV1"},r.paymentHandler));break}}let a=nee(i,o,s),c=r?.mediaType||this._params.packerParams.mediaType||"application/iden3-zkp-json",l=na(c,r?.packerOptions||this._params.packerParams,{senderDID:i,provingMethodAlg:r.messageProvingMethodAlg}),u=await this.packMessage(a,i,c,l),h=await(await fetch(t.body.agent,{method:"POST",body:u.buffer,headers:{"Content-Type":this._params.packerParams.mediaType==="application/iden3comm-plain-json"?"application/json":"application/octet-stream"}})).arrayBuffer();if(!h.byteLength)return null;let{unpackedMessage:f}=await this._packerMgr.unpack(new Uint8Array(h));return f}async handlePaymentRequest(t,r){let i=await this.parsePaymentRequest(t);if(!i.from)throw new Error("failed request. empty 'from' field");if(!i.to)throw new Error("failed request. empty 'to' field");r?.allowExpiredMessages||vr(i);let o=r.mediaType||this._params.packerParams.mediaType||"application/iden3-zkp-json";r.packerOptions||(r.packerOptions=this._params.packerParams.packerOptions),r.mediaType=o;let s=Se.parse(i.to);r.packerOptions=na(o,r.packerOptions,{provingMethodAlg:await Oc(t),senderDID:s});let a=await this.handlePaymentRequestMessage(i,r);return a?this.packMessage(a,s,r.mediaType||"application/iden3-zkp-json",r.packerOptions):null}async handlePayment(t,r){if(r?.allowExpiredMessages||vr(t),r.paymentRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.paymentRequest.from}, given ${t.to}`);if(!t.body.payments.length)throw new Error("failed request. empty 'payments' field in body");if(!r.paymentValidationHandler)throw new Error("please provide payment validation handler in options");for(let i=0;i<t.body.payments.length;i++){let o=t.body.payments[i],s=o.type==="Iden3PaymentCryptoV1"?o.id:o.nonce,c=r.paymentRequest.body.payments.map(l=>Array.isArray(l.data)?l.data:[l.data]).flat().find(l=>l.type==="Iden3PaymentRequestCryptoV1"?l.id===s:l.nonce===s);if(!c)throw new Error(`can't find payment request for payment ${o.type==="Iden3PaymentCryptoV1"?"id":"nonce"} ${s}`);await r.paymentValidationHandler(o.paymentData.txId,c)}}async createPaymentRailsV1(t,r,i,o,s,a){let c=[];for(let l=0;l<s.length;l++){let{credentials:u,description:d}=s[l],h=[];for(let f=0;f<s[l].options.length;f++){let{nonce:p,amount:E,chainId:b,optionId:C,expirationDate:B}=s[l].options[f],J=this._params.multiChainPaymentConfig?.find(z=>z.chainId===b);if(!J)throw new Error(`failed request. no config for chain ${b}`);let{recipient:G,paymentRails:U,options:O}=J,v=O.find(z=>z.id===C);if(!v)throw new Error(`failed request. no option for id ${C}`);if((v.type==="Iden3PaymentRailsERC20RequestV1"||v.type==="Iden3PaymentRailsSolanaSPLRequestV1")&&!v.contractAddress)throw new Error(`failed request. no token address for option id ${C}`);let D=B??new Date(new Date().setHours(new Date().getHours()+1));if(v.type==="Iden3PaymentRailsSolanaRequestV1"||v.type==="Iden3PaymentRailsSolanaSPLRequestV1"){if(!a?.solSigner)throw new Error(`please provide solana signer in context for ${v.type} payment type`);let z=await UB(a.solSigner,v,b,U,G,BigInt(E),D,p);h.push(z)}else{let z=await GB(o,v,b,U,G,BigInt(E),D,p);h.push(z)}}c.push({data:h,credentials:u,description:d})}return tee(t,r,i,c)}async packMessage(t,r,i,o){let s=Fe.encode(JSON.stringify(t)),a=i==="application/iden3comm-signed-json"?o:{provingMethodAlg:o?.provingMethodAlg||Nl};return await this._packerMgr.pack(i,s,{senderDID:r,...a})}async handleIden3PaymentRequestCryptoV1(t,r){if(t.expiration&&new Date(t.expiration)<new Date)throw new Error("failed request. expired request");let i=await r(t);return{id:t.id,"@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentCryptoV1",type:"Iden3PaymentCryptoV1",paymentData:{txId:i}}}async handleIden3PaymentRailsRequestV1(t,r){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");let i=await D3(t,this._params.documentResolver);if(this._params.allowedSigners&&!this._params.allowedSigners.includes(i))throw new Error("failed request. signer is not in the allowed signers list");let o=await r(t),s=Array.isArray(t.proof)?t.proof[0]:t.proof;return{nonce:t.nonce,type:"Iden3PaymentRailsV1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsV1",paymentData:{txId:o,chainId:s.eip712.domain.chainId}}}async handleIden3PaymentRailsSolanaRequestV1(t,r){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");if(!await R3(t,this._params.documentResolver))throw new Error("failed request. invalid Solana payment request signature");let o=Array.isArray(t.proof)?t.proof[0]:t.proof,s=o.verificationMethod.split(":").slice(-1)[0];if(this._params.allowedSigners&&!this._params.allowedSigners.includes(s))throw new Error("failed request. signer is not in the allowed signers list");let a=await r(t);return{nonce:t.nonce,type:"Iden3PaymentRailsSolanaV1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsSolanaV1",paymentData:{txId:a,chainId:o.domain.chainId}}}async handleIden3PaymentRailsSolanaSPLRequestV1(t,r){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");if(!await R3(t,this._params.documentResolver))throw new Error("failed request. invalid Solana payment request signature");let o=Array.isArray(t.proof)?t.proof[0]:t.proof,s=o.verificationMethod.split(":").slice(-1)[0];if(this._params.allowedSigners&&!this._params.allowedSigners.includes(s))throw new Error("failed request. signer is not in the allowed signers list");let a=await r(t);return{nonce:t.nonce,type:"Iden3PaymentRailsSolanaSPLV1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsSolanaSPLV1",paymentData:{txId:a,chainId:o.domain.chainId,tokenAddress:t.tokenAddress}}}async handleIden3PaymentRailsERC20RequestV1(t,r,i){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");let o=await D3(t,this._params.documentResolver);if(this._params.allowedSigners&&!this._params.allowedSigners.includes(o))throw new Error("failed request. signer is not in the allowed signers list");if(!t.features?.includes("EIP-2612")&&!i)throw new Error("please provide erc20TokenApproveHandler in context for ERC-20 payment type");i&&await i(t);let s=await r(t),a=Array.isArray(t.proof)?t.proof[0]:t.proof;return{nonce:t.nonce,type:"Iden3PaymentRailsERC20V1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsERC20V1",paymentData:{txId:s,chainId:a.eip712.domain.chainId,tokenAddress:t.tokenAddress}}}};function WLe(n,e){let t=Ft();return{id:t,thid:t,typ:"application/iden3comm-plain-json",type:ut.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE,body:{queries:n},from:e?.from,to:e?.to,created_time:Ct(new Date),expires_time:e?.expires_time}}function ree(n,e){let t=Ft();return{id:t,typ:"application/iden3comm-plain-json",thid:t,type:ut.DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE,body:{disclosures:n},from:e?.from,to:e?.to,created_time:Ct(new Date),expires_time:e?.expires_time}}var LO=class extends Fi{constructor(t){super();this._options=t;let r=["id","typ","type","thid","body","from","to","created_time","expires_time"];t.headers||(t.headers=r)}async handle(t,r){switch(t.type){case ut.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE:return await this.handleDiscoveryQuery(t,r);default:return super.handle(t,r)}}async handleDiscoveryQuery(t,r){r?.allowExpiredMessages||vr(t);let i=[];for(let o of t.body.queries)i.push(...this.handleQuery(o));return Promise.resolve(ree(i,{to:t.from,from:t.to,expires_time:r?.disclosureExpiresDate?Ct(r.disclosureExpiresDate):void 0}))}handleQuery(t){let r=[];switch(t["feature-type"]){case"accept":r=this.handleAcceptQuery();break;case"protocol":r=this.handleProtocolQuery();break;case"goal-code":r=this.handleGoalCodeQuery();break;case"header":r=this.handleHeaderQuery();break}return this.handleMatch(r,t.match)}handleAcceptQuery(){return this._options.packageManager.getSupportedProfiles().map(r=>({"feature-type":"accept",id:r}))}handleProtocolQuery(){return this._options.protocols?.map(t=>({"feature-type":"protocol",id:t}))??[]}handleGoalCodeQuery(){return this._options.goalCodes?.map(t=>({"feature-type":"goal-code",id:t}))??[]}handleHeaderQuery(){return this._options.headers?.map(t=>({"feature-type":"header",id:t}))??[]}handleMatch(t,r){if(!r||r==="*")return t;let i=this.wildcardToRegExp(r);return t.filter(o=>i.test(o.id))}wildcardToRegExp(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`)}};function ZLe(n,e,t){return{id:Ft(),pthid:n,typ:"application/iden3comm-plain-json",type:ut.PROBLEM_REPORT_MESSAGE_TYPE,ack:t?.ack,body:{code:e,comment:t?.comment,args:t?.args,escalate_to:t?.escalate_to},from:t?.from,to:t?.to}}var hd={url:"http://localhost:8545",defaultGasLimit:6e5,minGasPrice:"0",maxGasPrice:"100000000000",confirmationBlockCount:5,confirmationTimeout:6e5,contractAddress:"",receiptTimeout:6e5,rpcResponseTimeout:5e3,waitReceiptCycleTime:3e4,waitBlockCycleTime:3e3},zE=class{constructor(e,t){this.ethConfig=e;let r=Array.isArray(e)?e[0]:e;this.provider=new jt(r.url),this.stateContract=new Ln(r.contractAddress,x5,this.provider),this._transactionService=new $s(this.getRpcProvider()),this._latestStateCacheOptions={ttl:t?.latestStateCacheOptions?.ttl??Zr.DEFAULT_PROOF_VERIFY_DELAY/2,maxSize:t?.latestStateCacheOptions?.maxSize??Xm},this._stateCacheOptions={notReplacedTtl:t?.stateCacheOptions?.notReplacedTtl??Zr.DEFAULT_PROOF_VERIFY_DELAY/2,replacedTtl:t?.stateCacheOptions?.replacedTtl??Zr.DEFAULT_PROOF_VERIFY_DELAY,maxSize:t?.stateCacheOptions?.maxSize??Xm},this._rootCacheOptions={replacedTtl:t?.rootCacheOptions?.replacedTtl??Zr.DEFAULT_AUTH_VERIFY_DELAY,notReplacedTtl:t?.rootCacheOptions?.notReplacedTtl??Zr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.rootCacheOptions?.maxSize??Xm},this._gistProofCacheOptions={ttl:Zr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.gistProofCacheOptions?.maxSize??Xm},this._latestStateResolveCache=t?.latestStateCacheOptions?.cache??Iy({maxSize:this._latestStateCacheOptions.maxSize,ttl:this._latestStateCacheOptions.ttl}),this._stateResolveCache=t?.stateCacheOptions?.cache??Iy({maxSize:this._stateCacheOptions.maxSize,ttl:this._stateCacheOptions.replacedTtl}),this._rootResolveCache=t?.rootCacheOptions?.cache??Iy({maxSize:this._rootCacheOptions.maxSize,ttl:this._rootCacheOptions.replacedTtl}),this._gistProofResolveCache=t?.gistProofCacheOptions?.cache??Iy({maxSize:this._gistProofCacheOptions.maxSize,ttl:this._gistProofCacheOptions.ttl}),this._disableCache=t?.disableCache??!1}stateContract;provider;_transactionService;_latestStateResolveCache;_stateResolveCache;_rootResolveCache;_gistProofResolveCache;_latestStateCacheOptions;_stateCacheOptions;_rootCacheOptions;_gistProofCacheOptions;_disableCache=!1;async getLatestStateById(e){let t=this.getLatestStateCacheKey(e);if(!this._disableCache){let s=await this._latestStateResolveCache?.get(t);if(s)return s}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=await r.getStateInfoById(e),o={id:BigInt(i[0]),state:BigInt(i[1]),replacedByState:BigInt(i[2]),createdAtTimestamp:BigInt(i[3]),replacedAtTimestamp:BigInt(i[4]),createdAtBlock:BigInt(i[5]),replacedAtBlock:BigInt(i[6])};return!this._disableCache&&await this._latestStateResolveCache?.set(t,o,this._latestStateCacheOptions.ttl),o}async getStateInfoByIdAndState(e,t){let r=this.getStateCacheKey(e,t);if(!this._disableCache){let c=await this._stateResolveCache?.get(r);if(c)return c}let{stateContract:i}=this.getStateContractAndProviderForId(e),o=await i.getStateInfoByIdAndState(e,t),s={id:BigInt(o[0]),state:BigInt(o[1]),replacedByState:BigInt(o[2]),createdAtTimestamp:BigInt(o[3]),replacedAtTimestamp:BigInt(o[4]),createdAtBlock:BigInt(o[5]),replacedAtBlock:BigInt(o[6])},a=s.replacedAtTimestamp===0n?this._stateCacheOptions.notReplacedTtl:this._stateCacheOptions.replacedTtl;return!this._disableCache&&await this._stateResolveCache?.set(r,s,a),s}async publishState(e,t){let r=new cE;r.pubSignalsUnmarshal(Fe.encode(JSON.stringify(e.pub_signals)));let{userId:i,oldUserState:o,newUserState:s,isOldStateGenesis:a}=r,{stateContract:c,provider:l}=this.getStateContractAndProviderForId(i.bigInt()),u=c.connect(t),d=L0(e.proof),h=[i.bigInt().toString(),o.bigInt().toString(),s.bigInt().toString(),a,d.a,d.b,d.c],f=await l.getFeeData(),p=hd.maxFeePerGas?BigInt(hd.maxFeePerGas):f.maxFeePerGas,E=hd.maxPriorityFeePerGas?BigInt(hd.maxPriorityFeePerGas):f.maxPriorityFeePerGas,b=await u.transitState.estimateGas(...h),C=await u.transitState.populateTransaction(...h),B={to:C.to,data:C.data,gasLimit:b,maxFeePerGas:p,maxPriorityFeePerGas:E},{txnHash:J}=await this._transactionService.sendTransactionRequest(t,B);return J}async publishStateGeneric(e,t){let{userId:r,oldUserState:i,newUserState:o,isOldStateGenesis:s,methodId:a,methodParams:c}=t,{stateContract:l,provider:u}=this.getStateContractAndProviderForId(r.bigInt()),d=l.connect(e),h=await u.getFeeData(),f=hd.maxFeePerGas?BigInt(hd.maxFeePerGas):h.maxFeePerGas,p=hd.maxPriorityFeePerGas?BigInt(hd.maxPriorityFeePerGas):h.maxPriorityFeePerGas,E=[r.bigInt().toString(),i.bigInt().toString(),o.bigInt().toString(),s,a,c],b=await d.transitStateGeneric.estimateGas(...E),C=await d.transitStateGeneric.populateTransaction(...E),B={to:C.to,data:C.data,gasLimit:b,maxFeePerGas:f,maxPriorityFeePerGas:p},{txnHash:J}=await this._transactionService.sendTransactionRequest(e,B);return J}async getGISTProof(e){let t=this.getGistProofCacheKey(e);if(!this._disableCache){let s=await this._gistProofResolveCache?.get(t);if(s)return s}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=await r.getGISTProof(e),o={root:BigInt(i.root.toString()),existence:i.existence,siblings:i.siblings?.map(s=>BigInt(s.toString())),index:BigInt(i.index.toString()),value:BigInt(i.value.toString()),auxExistence:i.auxExistence,auxIndex:BigInt(i.auxIndex.toString()),auxValue:BigInt(i.auxValue.toString())};return!this._disableCache&&await this._gistProofResolveCache?.set(t,o,this._gistProofCacheOptions.ttl),o}async getGISTRootInfo(e,t){let r=this.getRootCacheKey(e);if(!this._disableCache){let c=await this._rootResolveCache?.get(r);if(c)return c}let{stateContract:i}=this.getStateContractAndProviderForId(t),o=await i.getGISTRootInfo(e),s={root:BigInt(o.root.toString()),replacedByRoot:BigInt(o.replacedByRoot.toString()),createdAtTimestamp:BigInt(o.createdAtTimestamp.toString()),replacedAtTimestamp:BigInt(o.replacedAtTimestamp.toString()),createdAtBlock:BigInt(o.createdAtBlock.toString()),replacedAtBlock:BigInt(o.replacedAtBlock.toString())},a=s.replacedAtTimestamp==0n?this._rootCacheOptions.notReplacedTtl:this._rootCacheOptions.replacedTtl;return!this._disableCache&&await this._rootResolveCache?.set(r,s,a),s}getRpcProvider(){return this.provider}enableCache(){this._disableCache=!1}disableCache(){this._disableCache=!0}getStateContractAndProviderForId(e){let t=$e.fromBigInt(e),r=Vy(Se.blockchainFromId(t),Se.networkIdFromId(t)),i=this.networkByChainId(r),o=new jt(i.url);return{stateContract:new Ln(i.contractAddress,x5,o),provider:o}}networkByChainId(e){let r=(Array.isArray(this.ethConfig)?this.ethConfig:[this.ethConfig]).find(i=>i.chainId===e);if(!r)throw new Error(`chainId "${e}" not supported`);return r}getGistProofCacheKey(e){return`gist-${e.toString()}`}getLatestStateCacheKey(e){return`latest-${e.toString()}`}getStateCacheKey(e,t){return`${e.toString()}-${t.toString()}`}getRootCacheKey(e){return e.toString()}};var RO=[{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[{internalType:"string",name:"message",type:"string"},{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256",name:"linkID",type:"uint256"},{internalType:"uint64",name:"requestIdToCompare",type:"uint64"},{internalType:"uint256",name:"linkIdToCompare",type:"uint256"}],name:"LinkedProofError",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint64",name:"requestId",type:"uint64"},{indexed:!0,internalType:"address",name:"requestOwner",type:"address"},{indexed:!1,internalType:"string",name:"metadata",type:"string"},{indexed:!1,internalType:"address",name:"validator",type:"address"},{indexed:!1,internalType:"bytes",name:"data",type:"bytes"}],name:"ZKPRequestSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint64",name:"requestId",type:"uint64"},{indexed:!0,internalType:"address",name:"caller",type:"address"}],name:"ZKPResponseSubmitted",type:"event"},{inputs:[],name:"REQUESTS_RETURN_LIMIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"acceptOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"addValidatorToWhitelist",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"disableZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"enableZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getProofStatus",outputs:[{components:[{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"uint256",name:"blockTimestamp",type:"uint256"}],internalType:"struct IZKPVerifier.ProofStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"string",name:"key",type:"string"}],name:"getProofStorageField",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getRequestOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getZKPRequest",outputs:[{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest",name:"zkpRequest",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"startIndex",type:"uint256"},{internalType:"uint256",name:"length",type:"uint256"}],name:"getZKPRequests",outputs:[{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getZKPRequestsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IStateCrossChain",name:"stateCrossChain",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"}],name:"isProofVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"isWhitelistedValidator",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"isZKPRequestEnabled",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pendingOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"removeValidatorFromWhitelist",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"requestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"address",name:"requestOwner",type:"address"}],name:"setRequestOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest",name:"request",type:"tuple"}],name:"setZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256[]",name:"inputs",type:"uint256[]"},{internalType:"uint256[2]",name:"a",type:"uint256[2]"},{internalType:"uint256[2][2]",name:"b",type:"uint256[2][2]"},{internalType:"uint256[2]",name:"c",type:"uint256[2]"}],name:"submitZKPResponse",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"bytes",name:"zkProof",type:"bytes"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct ZKPResponse[]",name:"responses",type:"tuple[]"},{internalType:"bytes",name:"crossChainProof",type:"bytes"}],name:"submitZKPResponseV2",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64[]",name:"requestIds",type:"uint64[]"}],name:"verifyLinkedProofs",outputs:[],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256[]",name:"inputs",type:"uint256[]"},{internalType:"uint256[2]",name:"a",type:"uint256[2]"},{internalType:"uint256[2][2]",name:"b",type:"uint256[2][2]"},{internalType:"uint256[2]",name:"c",type:"uint256[2]"},{internalType:"address",name:"sender",type:"address"}],name:"verifyZKPResponse",outputs:[{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"inputValue",type:"uint256"}],internalType:"struct ICircuitValidator.KeyToInputValue[]",name:"",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"}];var DO=[{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"address",name:"userAddress",type:"address"}],name:"areMultiRequestProofsVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"groupID",type:"uint256"}],name:"getGroupedRequests",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.RequestInfo[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getGroupsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"}],name:"getMultiRequest",outputs:[{components:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"uint256[]",name:"requestIds",type:"uint256[]"},{internalType:"uint256[]",name:"groupIds",type:"uint256[]"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.MultiRequest",name:"multiRequest",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"address",name:"userAddress",type:"address"}],name:"getMultiRequestProofsStatus",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct IVerifier.RequestProofStatus[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"}],name:"getRequest",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.RequestInfo",name:"request",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"requestId",type:"uint256"}],name:"getRequestProofStatus",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct IVerifier.RequestProofStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRequestsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"address",name:"sender",type:"address"},{internalType:"string",name:"responseFieldName",type:"string"}],name:"getResponseFieldValue",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"address",name:"sender",type:"address"}],name:"getResponseFields",outputs:[{components:[{internalType:"string",name:"name",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct IRequestValidator.ResponseField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"groupId",type:"uint256"}],name:"groupIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"requestId",type:"uint256"}],name:"isRequestProofVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"}],name:"multiRequestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"}],name:"requestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"string",name:"authMethod",type:"string"},{internalType:"contract IAuthValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"}],internalType:"struct IVerifier.AuthMethod",name:"authMethod",type:"tuple"}],name:"setAuthMethod",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"uint256[]",name:"requestIds",type:"uint256[]"},{internalType:"uint256[]",name:"groupIds",type:"uint256[]"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.MultiRequest",name:"multiRequest",type:"tuple"}],name:"setMultiRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.Request[]",name:"requests",type:"tuple[]"}],name:"setRequests",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"string",name:"authMethod",type:"string"},{internalType:"bytes",name:"proof",type:"bytes"}],internalType:"struct IVerifier.AuthResponse",name:"authResponse",type:"tuple"},{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bytes",name:"proof",type:"bytes"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.Response[]",name:"responses",type:"tuple[]"},{internalType:"bytes",name:"crossChainProofs",type:"bytes"}],name:"submitResponse",outputs:[],stateMutability:"nonpayable",type:"function"}];var TO=10000000n,iee=(r=>(r.SubmitZKPResponseV1="b68967e2",r.SubmitZKPResponseV2="ade09fcd",r.SubmitResponse="06c86a91",r))(iee||{}),oee=function(n){return[{authMethod:n.authProof.raw.authMethod,proof:n.authProof.encoded},n.proofs.map(e=>({requestId:e.requestId,proof:e.encoded,metadata:e.metadata})),n.crossChainProof.encoded]},BO=class n{constructor(e,t){this._configs=e;this._opts=t}static _supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1"];static _supportedCircuitsPubSignalsMap={credentialAtomicQueryMTPV2OnChain:_1,credentialAtomicQuerySigV2OnChain:sE,"credentialAtomicQueryV3OnChain-beta.1":iE,authV2:_s};static async prepareTxArgsSubmitV1(e,t){if(e.method_id.replace("0x","")!=="b68967e2")throw new Error("prepareTxArgsSubmitV1 function doesn't implement requested method id. Only '0xb68967e2' is supported.");let r=t.id,i=t.pub_signals,o=L0(t.proof);return[r,i,o.a,o.b,o.c]}async prepareTxArgsSubmitV1(e,t){return n.prepareTxArgsSubmitV1(e,t)}async submitZKPResponse(e,t,r){let i=this._configs.find(d=>d.chainId==t.chain_id);if(!i)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="b68967e2")throw new Error("submitZKPResponse function doesn't implement requested method id. Only '0xb68967e2' is supported.");let o=new jt(i.url,i.chainId);e=e.connect(o);let s=new Map,a=await o.getFeeData(),c=i.maxFeePerGas?BigInt(i.maxFeePerGas):a.maxFeePerGas,l=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,u=new Ln(t.contract_address,RO);for(let d of r){let h=await this.prepareTxArgsSubmitV1(t,d),f=await u.submitZKPResponse.populateTransaction(...h),p={to:t.contract_address,data:f.data,maxFeePerGas:c,maxPriorityFeePerGas:l},E;try{E=await e.estimateGas(p)}catch{E=TO}p.gasLimit=E;let b=new $s(o),{txnHash:C}=await b.sendTransactionRequest(e,p);s.set(C,d)}return s}async submitZKPResponseV2(e,t,r){let i=this._configs.find(b=>b.chainId==t.chain_id);if(!i)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="ade09fcd")throw new Error("submitZKPResponseV2 function doesn't implement requested method id. Only '0xade09fcd' is supported.");if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");let o=new jt(i.url,i.chainId);e=e.connect(o);let s=await this.prepareTxArgsSubmitV2(t,r),a=await o.getFeeData(),c=i.maxFeePerGas?BigInt(i.maxFeePerGas):a.maxFeePerGas,l=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,d=await new Ln(t.contract_address,RO).submitZKPResponseV2.populateTransaction(...s),h={to:t.contract_address,data:d.data,maxFeePerGas:c,maxPriorityFeePerGas:l},f;try{f=await e.estimateGas(h)}catch{f=TO}h.gasLimit=f;let p=new $s(o),{txnHash:E}=await p.sendTransactionRequest(e,h);return new Map().set(E,r)}async submitResponse(e,t,r,i){let o=this._configs.find(C=>C.chainId==t.chain_id);if(!o)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="06c86a91")throw new Error("submitResponse function doesn't implement requested method id. Only '0x06c86a91' is supported.");if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");let s=new jt(o.url,o.chainId);e=e.connect(s);let a=await this.prepareTxArgsSubmit(t,r,i),c=await s.getFeeData(),l=o.maxFeePerGas?BigInt(o.maxFeePerGas):c.maxFeePerGas,u=o.maxPriorityFeePerGas?BigInt(o.maxPriorityFeePerGas):c.maxPriorityFeePerGas,h=await new Ln(t.contract_address,DO).submitResponse.populateTransaction(...a.txDataArgs),f={to:t.contract_address,data:h.data,maxFeePerGas:l,maxPriorityFeePerGas:u},p;try{p=await e.estimateGas(f)}catch{p=TO}f.gasLimit=p;let E=new $s(s),{txnHash:b}=await E.sendTransactionRequest(e,f);return new Map().set(b,{authProof:a.result.authProof.raw,crossChainProof:a.result.crossChainProof.raw,responses:a.result.proofs.map(C=>C.proof)})}static async prepareTxArgsSubmit(e,t,r,i){if(t.method_id.replace("0x","")!=="06c86a91")throw new Error("submit cross chain doesn't implement requested method id. Only '0x06c86a91' is supported.");let o=[],s=[],a=[],c="0x",l="";switch(i.authMethod){case"authV2":{let f=L0(i.zkp.proof);l=QS(i.zkp.pub_signals,f.a,f.b,f.c);break}case"ethIdentity":{l=see(i.userDid);break}default:throw new Error("auth proof must use method AuthV2 or ethIdentity")}for(let f of r){this.checkSupportedCircuit(f.circuitId);let{requestId:p,zkProofEncoded:E,metadata:b}=qE(f);a.push({proof:f,requestId:p,encoded:E,metadata:b})}let u=r.map(f=>({circuitId:f.circuitId,pub_signals:f.pub_signals}));i.authMethod=="authV2"&&u.push({circuitId:i.zkp.circuitId,pub_signals:i.zkp.pub_signals});for(let f of u){let{gistUpdateResolutions:p,stateUpdateResolutions:E}=this.getUpdateResolutions(e,t.chain_id,f.circuitId,f.pub_signals);p.length>0&&o.push(...await Promise.all(p)),E.length>0&&s.push(...await Promise.all(E))}let d=o.length||s.length?this.packCrossChainProofs(o,s):c,h={authProof:{raw:i,encoded:l},proofs:a,crossChainProof:{raw:{globalStateProofs:o||[],identityStateProofs:s||[]},encoded:d}};return{result:h,txDataArgs:oee(h)}}async prepareTxArgsSubmit(e,t,r){if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");return n.prepareTxArgsSubmit(this._opts.didResolverUrl,e,t,r)}static checkSupportedCircuit(e){if(!this._supportedCircuits.includes(e))throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`)}static getCrossChainResolvers(e,t,r,i){return[...new Set(e.map(o=>JSON.stringify({id:o.id.string(),[r]:r==="gist"?o.root?.string():o.state?.string()})))].reduce((o,s)=>{let a=JSON.parse(s),c=$e.fromString(a.id),l=Qy(Se.parseFromId(c));if(t===l)return o;let u=this.resolveDidDocumentEip712MessageAndSignature(Se.parseFromId($e.fromString(a.id)),i,{[r]:be.fromString(a[r])});return[...o,u]},[])}static async prepareTxArgsSubmitV2(e,t,r){if(t.method_id.replace("0x","")!=="ade09fcd")throw new Error("submit cross chain doesn't implement requested method id. Only '0xade09fcd' is supported.");let i=[],o=[],s=[],a="0x";for(let l of r){this.checkSupportedCircuit(l.circuitId);let{requestId:u,zkProofEncoded:d,metadata:h}=qE(l);s.push({requestId:u,zkProof:d,data:h});let{gistUpdateResolutions:f,stateUpdateResolutions:p}=this.getUpdateResolutions(e,t.chain_id,l.circuitId,l.pub_signals);f.length>0&&i.push(...await Promise.all(f)),p.length>0&&o.push(...await Promise.all(p))}let c=i.length||o.length?this.packCrossChainProofs(i,o):a;return[s,c]}async prepareTxArgsSubmitV2(e,t){if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");return n.prepareTxArgsSubmitV2(this._opts.didResolverUrl,e,t)}static getUpdateResolutions(e,t,r,i){let o=this.getOnChainGistRootStatePubSignals(r,i),s=this.getCrossChainResolvers(o.gists,t,"gist",e),a=this.getCrossChainResolvers(o.states,t,"state",e);return{gistUpdateResolutions:s,stateUpdateResolutions:a}}static packCrossChainProofs(e,t){let r=[];for(let i of e)r.push({proofType:"globalStateProof",proof:this.packGlobalStateMsg(i)});for(let i of t)r.push({proofType:"stateProof",proof:this.packIdentityStateMsg(i)});return new An.AbiCoder().encode(["tuple(string proofType,bytes proof)[]"],[r])}static packGlobalStateMsg(e){return new An.AbiCoder().encode(["tuple(tuple(uint256 timestamp,bytes2 idType,uint256 root,uint256 replacedAtTimestamp) globalStateMsg,bytes signature,)"],[e])}static packIdentityStateMsg(e){return new An.AbiCoder().encode(["tuple(tuple(uint256 timestamp,uint256 id,uint256 state,uint256 replacedAtTimestamp) idStateMsg,bytes signature,)"],[e])}static getOnChainGistRootStatePubSignals(e,t){let r=this._supportedCircuitsPubSignalsMap[e];if(!r)throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`);let i=new r,o=Fe.encode(JSON.stringify(t));return i.pubSignalsUnmarshal(o),i.getStatesInfo()}static async resolveDidDocumentEip712MessageAndSignature(e,t,r){let i=await ip(e,t,{...r,signature:"EthereumEip712Signature2021"});if(!i.didResolutionMetadata.proof?.length)throw new Error("No proof found in resolved DID document");let o=i.didResolutionMetadata.proof[0].eip712.message,s=i.didResolutionMetadata.proof[0].proofValue;return r?.gist&&!r.state?{globalStateMsg:{timestamp:o.timestamp,idType:o.idType,root:o.root,replacedAtTimestamp:o.replacedAtTimestamp},signature:s}:{idStateMsg:{timestamp:o.timestamp,id:o.id,state:o.state,replacedAtTimestamp:o.replacedAtTimestamp},signature:s}}},see=n=>`0x${Lr(vt.intToBytes(Se.idFromDID(n).bigInt()))}`;var PO=[{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"},{internalType:"uint256",name:"_credentialId",type:"uint256"}],name:"getCredential",outputs:[{components:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"string[]",name:"context",type:"string[]"},{internalType:"string",name:"_type",type:"string"},{internalType:"uint64",name:"issuanceDate",type:"uint64"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.CredentialSchema",name:"credentialSchema",type:"tuple"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.DisplayMethod",name:"displayMethod",type:"tuple"}],internalType:"struct INonMerklizedIssuer.CredentialData",name:"",type:"tuple"},{internalType:"uint256[8]",name:"",type:"uint256[8]"},{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct INonMerklizedIssuer.SubjectField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCredentialAdapterVersion",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"}],name:"getUserCredentialIds",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"}];var kO=[{inputs:[],name:"CREDENTIAL_ADAPTER_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"}],name:"getClaimProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getClaimProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"}],name:"getClaimProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getClaimsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"},{internalType:"uint256",name:"_credentialId",type:"uint256"}],name:"getCredential",outputs:[{components:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"string[]",name:"context",type:"string[]"},{internalType:"string",name:"_type",type:"string"},{internalType:"uint64",name:"issuanceDate",type:"uint64"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.CredentialSchema",name:"credentialSchema",type:"tuple"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.DisplayMethod",name:"displayMethod",type:"tuple"}],internalType:"struct INonMerklizedIssuer.CredentialData",name:"",type:"tuple"},{internalType:"uint256[8]",name:"",type:"uint256[8]"},{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct INonMerklizedIssuer.SubjectField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCredentialAdapterVersion",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getIsOldStateGenesis",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedClaimsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedRevocationsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedRootsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedState",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"}],name:"getRevocationProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getRevocationProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"}],name:"getRevocationProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatus",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatusByIdAndState",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRevocationsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"rootsTreeRoot",type:"uint256"}],name:"getRootProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getRootProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"rootsTreeRoot",type:"uint256"}],name:"getRootProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"state",type:"uint256"}],name:"getRootsByState",outputs:[{components:[{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.Roots",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRootsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getSmtDepth",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"}],name:"getUserCredentialIds",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_stateContractAddr",type:"address"},{internalType:"bytes2",name:"idType",type:"bytes2"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],Gy=class{static abi=kO;static createInterface(){return new dc(kO)}static connect(e,t){return new Ln(e,kO,t)}};var ZE=class{_contract;_contractAddress;_chainId;_issuerDid;_merklizationOptions;constructor(e,t,r){if(!e.chainId)throw new Error("Chain ID is required");this._chainId=e.chainId,this._contractAddress=An.getAddress(An.hexlify($e.ethAddressFromId(Se.idFromDID(t)))),this._contract=Gy.connect(this._contractAddress,new An.JsonRpcProvider(e.url)),this._issuerDid=t,this._merklizationOptions=r?.merklizationOptions}async isInterfaceSupported(){let e=[{name:"Interface detection ERC-165",value:"0x01ffc9a7"},{name:"Interface non-merklized issuer",value:"0x58874949"},{name:"Interface get credential",value:"0x5d1ca631"}],r=(await Promise.all(e.map(async i=>await this._contract.supportsInterface(i.value)?null:i.name))).filter(i=>i!==null);if(r.length>0)throw new Error(`Unsupported interfaces: ${r.join(", ")}`)}async getCredential(e,t){let[r,i,o]=await this._contract.getCredential(e.bigInt(),t);return{credentialData:r,coreClaimBigInts:i,credentialSubjectFields:o}}async getUserCredentialsIds(e){return this._contract.getUserCredentialIds(e.bigInt())}async convertOnChainInfoToW3CCredential(e,t,r){let i=new Or().unMarshalJson(JSON.stringify(t.map(l=>l.toString()))),o=await this.convertCredentialSubject(i,e.context,e._type,r),s={id:this.credentialId(e.id),credentialSchema:e.credentialSchema.id,type:e._type,credentialSubject:o,expiration:i.getExpirationDate()?.getTime(),displayMethod:this.convertDisplayMethod(e.displayMethod),context:e.context,revocationOpts:{id:this._contractAddress,nonce:Number(i.getRevocationNonce()),type:"Iden3OnchainSparseMerkleTreeProof2023"},issuanceDate:ia(Number(e.issuanceDate)).getTime()},a=await this.existenceProof(i),c=Gr.fromCredentialRequest(this._issuerDid,s);return c.proof=[a],c}credentialId(e){return`urn:iden3:onchain:${this._chainId}:${this._contractAddress}:${e}`}async convertCredentialSubject(e,t,r,i){let o=JSON.stringify({"@context":t}),s={};for(let l of i){let u=await Ur.newTypeFromContext(o,`${r}.${l.key}`,this._merklizationOptions);switch(u){case"http://www.w3.org/2001/XMLSchema#boolean":{switch(l.rawValue.toString()){case"18586133768512220936620570745912940619677854269274689475585506675881198879027":s[l.key]=!0;break;case"19014214495641488759237505126948346942972912379615652741039992445865937985820":s[l.key]=!1;break}break}case("http://www.w3.org/2001/XMLSchema#nonNegativeInteger","http://www.w3.org/2001/XMLSchema#nonPositiveInteger","http://www.w3.org/2001/XMLSchema#negativeInteger","http://www.w3.org/2001/XMLSchema#positiveInteger"):{s[l.key]=l.value.toString();break}case"http://www.w3.org/2001/XMLSchema#integer":{s[l.key]=Number(l.value);break}case"http://www.w3.org/2001/XMLSchema#string":{this.validateSourceValue(u,l.value,l.rawValue),s[l.key]=l.rawValue;break}case"http://www.w3.org/2001/XMLSchema#dateTime":{let d=BigInt(l.rawValue),h=ia(Number(d)).toISOString();this.validateSourceValue(u,l.value,h),s[l.key]=h;break}case"http://www.w3.org/2001/XMLSchema#double":{let d=Number(l.rawValue);this.validateSourceValue(u,l.value,d),s[l.key]=d;break}default:throw new Error(`Unsupported data type ${u}`)}}s.type=r;let a=e.getId(),c=Se.parseFromId(a);return s.id=c.string(),s}async existenceProof(e){let[t,r]=await this._contract.getClaimProofWithStateInfo(e.hIndex());if(!t.existence)throw new Error("Claim does not exist");let i=be.fromBigInt(r.state),o=be.fromBigInt(r.claimsRoot),s=be.fromBigInt(r.revocationsRoot),a=be.fromBigInt(r.rootsRoot),c=new Bt({siblings:t.siblings.map(l=>be.fromBigInt(l)),existence:t.existence,nodeAux:t.auxExistence?{key:be.fromBigInt(t.auxIndex),value:be.fromBigInt(t.auxValue)}:void 0});return new mc({issuerData:{id:this._issuerDid,state:{value:i,claimsTreeRoot:o,revocationTreeRoot:s,rootOfRoots:a}},mtp:c,coreClaim:e})}async validateSourceValue(e,t,r){if(await Sl.hashValue(e,r)!==t)throw new Error(`Invalid source value for ${e} type`)}convertDisplayMethod(e){if(!(!e.id||!e._type))switch(e._type){case"Iden3BasicDisplayMethodV1":return{id:e.id,type:"Iden3BasicDisplayMethodV1"};default:throw new Error(`Unsupported display method type ${e._type}`)}}};var MO=class{_ethConnectionConfig;_onchainIssuerOptions;constructor(e,t){this._ethConnectionConfig=e,this._onchainIssuerOptions=t}async getCredential(e,t,r){let{contract:i,connection:o}=this.getContractConnection(e),s=await i.getCredentialAdapterVersion();switch(s){case"0.0.1":{let a=new ZE(o,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});await a.isInterfaceSupported();let{credentialData:c,coreClaimBigInts:l,credentialSubjectFields:u}=await a.getCredential(Se.idFromDID(t),r);return await a.convertOnChainInfoToW3CCredential(c,l,u)}default:throw new Error(`Unsupported adapter version ${s}`)}}async getUserCredentialIds(e,t){let{contract:r,connection:i}=this.getContractConnection(e),o=await r.getCredentialAdapterVersion();switch(o){case"0.0.1":{let s=new ZE(i,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});return await s.isInterfaceSupported(),await s.getUserCredentialsIds(Se.idFromDID(t))}default:throw new Error(`Unsupported adapter version ${o}`)}}getContractConnection(e){let t=Se.idFromDID(e),r=Qy(e),i=An.getAddress(An.hexlify($e.ethAddressFromId(t))),o=this._ethConnectionConfig.find(a=>a.chainId===r);if(!o)throw new Error(`No connection found for chain ID ${r}`);if(!o.url)throw new Error(`No URL found for chain ID ${r}`);return{contract:new Ln(i,PO,new An.JsonRpcProvider(o.url)),connection:o}}};var OO=class{constructor(e){this.resolverUrl=e}async getLatestStateById(e){return this.getStateInfo(e)}async getStateInfoByIdAndState(e,t){return this.getStateInfo(e,t)}async getGISTProof(e){let{didDocument:t}=await ip(Se.parseFromId($e.fromBigInt(e)),this.resolverUrl),{global:r}=this.getIden3StateInfo2023(t);if(!r)throw new Error("GIST root not found");let{proof:i}=r;if(!i)throw new Error("GIST proof not found");return{root:r.root,existence:i.existence,siblings:i.siblings?.map(o=>BigInt(o)),index:BigInt(0),value:BigInt(0),auxExistence:!!i.node_aux,auxIndex:i.node_aux?BigInt(i.node_aux.key):BigInt(0),auxValue:i.node_aux?BigInt(i.node_aux.value):BigInt(0)}}async getGISTRootInfo(e,t){let{didDocument:r}=await ip(Se.parseFromId($e.fromBigInt(t)),this.resolverUrl,{gist:be.fromBigInt(e)}),{global:i}=this.getIden3StateInfo2023(r);if(!i)throw new Error("GIST root not found");return i}getRpcProvider(){return new jt}publishState(){throw new Error("publishState method not implemented.")}publishStateGeneric(){throw new Error("publishStateGeneric method not implemented.")}async getStateInfo(e,t){let r=t?{state:be.fromBigInt(t)}:void 0,{didDocument:i}=await ip(Se.parseFromId($e.fromBigInt(e)),this.resolverUrl,r),{info:o,published:s}=this.getIden3StateInfo2023(i);if(!o&&!s)throw new Error(qe.ERRORS.STATE_DOES_NOT_EXIST);if(!o)throw new Error("State info not found");return o.id=e,o.state=r?.state?.bigInt(),{...o}}getIden3StateInfo2023(e){let t=e.verificationMethod?.find(r=>r.type==="Iden3StateInfo2023");if(!t)throw new Error("Iden3StateInfo2023 verification method not found");return t}};var aee=[{inputs:[],name:"ECDSAInvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"length",type:"uint256"}],name:"ECDSAInvalidSignatureLength",type:"error"},{inputs:[{internalType:"bytes32",name:"s",type:"bytes32"}],name:"ECDSAInvalidSignatureS",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"allowance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientAllowance",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC20InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC20InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC20InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"}],name:"ERC20InvalidSpender",type:"error"},{inputs:[{internalType:"uint256",name:"deadline",type:"uint256"}],name:"ERC2612ExpiredSignature",type:"error"},{inputs:[{internalType:"address",name:"signer",type:"address"},{internalType:"address",name:"owner",type:"address"}],name:"ERC2612InvalidSigner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"currentNonce",type:"uint256"}],name:"InvalidAccountNonce",type:"error"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[],name:"DOMAIN_SEPARATOR",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"nonces",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],name:"permit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];var cee=[{inputs:[{internalType:"uint256",name:"initialSupply",type:"uint256"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"allowance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientAllowance",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC20InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC20InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC20InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"}],name:"ERC20InvalidSpender",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];async function oRe(n,e,t,r,i){let o=new Ln(e,aee,n),s=await o.nonces(await n.getAddress()),a=await o.eip712Domain(),c={name:a[1],version:a[2],chainId:a[3],verifyingContract:e},l={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:await n.getAddress(),spender:t,value:r,nonce:s,deadline:i};return n.signTypedData(c,l,u)}async function sRe(n,e){return new Ln(n,cee,e).decimals()}var pee=(t=>(t.NotDefinedQueryKey="not defined query key",t.NotDefinedComparator="not defined comparator",t))(pee||{}),mee=(o=>(o[o.BigInt=0]="BigInt",o[o.Boolean=1]="Boolean",o[o.Double=2]="Double",o[o.DateTime=3]="DateTime",o[o.String=4]="String",o))(mee||{}),FO=[!0,1,"true"],NO=[!1,0,"false"],lee=(n,e)=>Array.isArray(n)&&Array.isArray(e)?n.length===e.length&&n.every((t,r)=>t===e[r]):!Array.isArray(n)&&Array.isArray(e)?e.includes(n):Array.isArray(n)&&!Array.isArray(e)?n.includes(e):(n=n,e=e,FO.includes(n)&&FO.includes(e)||NO.includes(n)&&NO.includes(e)?!0:n===e),uee=(n,e)=>yee(n,e,(r,i)=>{switch(wee(r.toString())){case 0:case 1:return BigInt(r)>BigInt(i);case 3:return Date.parse(r.toString())>Date.parse(i.toString());case 2:case 4:default:return r>i}}),dee=(n,e)=>yee(n,e,(r,i)=>{switch(wee(r.toString())){case 0:case 1:return BigInt(r)>=BigInt(i);case 3:return Date.parse(r.toString())>=Date.parse(i.toString());case 2:case 4:default:return r>=i}}),aRe=(n,e)=>!!(FO.includes(e)&&typeof n<"u"||NO.includes(e)&&(n===void 0||Array.isArray(n)&&!n.length)),fee=(n,e)=>Array.isArray(n)&&Array.isArray(e)?n.every(t=>e.includes(t)):!Array.isArray(n)&&Array.isArray(e)?e.includes(n):Array.isArray(n)&&!Array.isArray(e)?n.includes(e):!1,hee=(n,e)=>{if(!Array.isArray(e)||e.length!==2)throw new Error("$between/$nonbetween operator value should be 2 elements array");let[t,r]=e.map(BigInt),i=o=>o>=t&&o<=r;return Array.isArray(n)?n.map(BigInt).every(i):i(BigInt(n))},Ul={$noop:()=>!0,$sd:()=>!0,$exists:(n,e)=>aRe(n,e),$eq:(n,e)=>lee(n,e),$in:(n,e)=>fee(n,e),$nin:(n,e)=>!fee(n,e),$gt:(n,e)=>uee(n,e),$lt:(n,e)=>!dee(n,e),$ne:(n,e)=>!lee(n,e),$gte:(n,e)=>dee(n,e),$lte:(n,e)=>!uee(n,e),$between:(n,e)=>hee(n,e),$nonbetween:(n,e)=>!hee(n,e)},gee=(n,e,t=null)=>{let r=e.split("."),i=n;for(let o of r){if(i==null)return t;i=i[o]}return i},Fc=class{constructor(e,t,r,i=!1){this.path=e;this.operatorFunc=t;this.value=r;this.isReverseParams=i}execute(e){if(!this.operatorFunc)throw new Error("not defined comparator");let t=gee(e,this.path);return t==null&&this.operatorFunc!==Ul.$exists?!1:this.isReverseParams?this.operatorFunc(this.value,t):this.operatorFunc(t,this.value)}},UO=n=>Object.keys(n).reduce((e,t)=>{let r=n[t];switch(t){case"claimId":return e.concat(new Fc("id",Ul.$eq,r));case"allowedIssuers":return(r||["*"]).includes("*")?e:e.concat(new Fc("issuer",Ul.$in,r));case"type":return e.concat(new Fc("type",Ul.$in,r,!0));case"context":return e.concat(new Fc("@context",Ul.$in,r,!0));case"credentialSubjectId":return e.concat(new Fc("credentialSubject.id",Ul.$eq,r));case"schema":return e.concat(new Fc("credentialSchema.id",Ul.$eq,r));case"credentialSubject":{let i=Object.keys(r).reduce((o,s)=>{let a=r[s];if(typeof a=="object"&&Object.keys(a).length===0)return o.concat([new Fc(`credentialSubject.${s}`,Ul.$noop,null)]);let c=Object.keys(a).map(l=>{let u=a[l],d=`credentialSubject.${s}`;return new Fc(d,Ul[l],u)});return o.concat(c)},[]);return e.concat(i)}case"proofType":case"groupId":case"skipClaimRevocationCheck":return e;default:throw new Error(`${t} : not defined query key`)}},[]),yee=(n,e,t)=>Array.isArray(n)&&Array.isArray(e)?n.every((r,i)=>t(r,e[i])):!Array.isArray(n)&&Array.isArray(e)?e.every(r=>t(n,r)):Array.isArray(n)&&!Array.isArray(e)?n.every(r=>t(r,e)):t(n,e),cRe=/^[+-]?\d+$/,lRe=/^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$/,uRe=/^([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))$/,dRe=/^(true)|(false)$/,fRe=/^\d{4}-\d{2}-\d{2}$/,wee=n=>cRe.test(n)?0:lRe.test(n)?2:uRe.test(n)||fRe.test(n)?3:dRe.test(n)?1:4;var GO=class{constructor(e){this._localStorageKey=e;localStorage.getItem(this._localStorageKey)||localStorage.setItem(e,JSON.stringify([]))}async save(e,t,r="id"){if(localStorage){let i=localStorage.getItem(this._localStorageKey),o=[];i&&(o=JSON.parse(i));let s=o.findIndex(a=>a[r]===e);s===-1?o.push(t):o[s]=t,localStorage.setItem(this._localStorageKey,JSON.stringify(o))}}async get(e,t="id"){let r=localStorage.getItem(this._localStorageKey),i=[];return r&&(i=JSON.parse(r)),i.find(o=>o[t]===e)}async load(){let e=localStorage.getItem(this._localStorageKey);return e&&JSON.parse(e)}async delete(e,t="id"){let r=localStorage.getItem(this._localStorageKey),i=[];r&&(i=JSON.parse(r));let o=i.filter(s=>s[t]!==e);if(i.length===o.length)throw new Error(`item not found to delete: ${e}`);localStorage.setItem(this._localStorageKey,JSON.stringify(o))}};var KO=class n{constructor(e){this._mtDepth=e}static storageKeyMeta="merkle-tree-meta";async createIdentityMerkleTrees(e){e||(e=`${Ft()}`);let t=localStorage.getItem(n.storageKeyMeta);if(t){let i=JSON.parse(t);if(i.find(c=>c.treeId===`${e}+${c.type}`))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let s=i.filter(c=>c.identifier===e);if(s.length>0)return s;let a=dE(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify([...i,...a])),[...i,...a]}let r=dE(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify(r)),r}async getIdentityMerkleTreesInfo(e){let t=localStorage.getItem(n.storageKeyMeta);if(t)return JSON.parse(t).filter(i=>i.identifier===e);throw new Error(`Merkle tree meta not found for identifier ${e}`)}async getMerkleTreeByIdentifierAndType(e,t){let r=this.getMeta(e,t);return new aa(new $y(Vc(r.treeId)),!0,this._mtDepth)}getMeta(e,t){let r=localStorage.getItem(n.storageKeyMeta),i=new Error(`Merkle tree not found for identifier ${e} and type ${t}`);if(!r)throw i;let s=JSON.parse(r).filter(a=>a.identifier===e&&a.type===t)[0];if(!s)throw i;return s}async addToMerkleTree(e,t,r,i){let o=this.getMeta(e,t);await new aa(new $y(Vc(o.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=localStorage.getItem(n.storageKeyMeta);if(!r)throw new Error(`Merkle tree meta not found for identifier ${e}`);let i=JSON.parse(r),o=i.filter(a=>a.identifier===e).map(a=>({...a,identifier:t}));if(o.length===0)throw new Error(`Merkle tree meta not found for identifier ${e}`);let s=[...i.filter(a=>a.identifier!==e),...o];localStorage.setItem(n.storageKeyMeta,JSON.stringify(s))}};var HO=class{constructor(e){this._storageKey=e;this._store=Ad(`${e}-db`,e)}_store;async save(e,t,r="id"){return xd(e,t,this._store)}async get(e,t="id"){return Jc(e,this._store)}async load(){return JF(this._store)}async delete(e,t="id"){return bI(e,this._store)}};var JO=class n{constructor(e){this._mtDepth=e;this._merkleTreeMetaStore=Ad(`${n.storageKeyMeta}-db`,n.storageKeyMeta),this._bindingStore=Ad(`${n.storageBindingKeyMeta}-db`,n.storageBindingKeyMeta)}static storageKeyMeta="merkle-tree-meta";static storageBindingKeyMeta="binding-did";_merkleTreeMetaStore;_bindingStore;async createIdentityMerkleTrees(e){if(e||(e=`${Ft()}`),await Jc(e,this._bindingStore))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let r=dE(e);return await xd(e,r,this._merkleTreeMetaStore),r}async getIdentityMerkleTreesInfo(e){let t=await Jc(e,this._merkleTreeMetaStore);if(t)return t;throw new Error(`Merkle tree meta not found for identifier ${e}`)}async getMerkleTreeByIdentifierAndType(e,t){let r=await Jc(e,this._merkleTreeMetaStore),i=new Error(`Merkle tree not found for identifier ${e} and type ${t}`);if(!r)throw i;let o=r.find(s=>s.identifier===e&&s.type===t);if(!o)throw i;return new aa(new ew(Vc(o.treeId)),!0,this._mtDepth)}async addToMerkleTree(e,t,r,i){let o=await Jc(e,this._merkleTreeMetaStore);if(!o)throw new Error(`Merkle tree meta not found for identifier ${e}`);let s=o.find(c=>c.identifier===e&&c.type===t);if(!s)throw new Error(`Merkle tree not found for identifier ${e} and type ${t}`);await new aa(new ew(Vc(s.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=await Jc(e,this._merkleTreeMetaStore);if(!r||!r?.length)throw new Error(`Merkle tree meta not found for identifier ${e}`);let i=r.map(o=>({...o,identifier:t}));await bI(e,this._merkleTreeMetaStore),await xd(t,i,this._merkleTreeMetaStore),await xd(e,t,this._bindingStore)}};var qO=class{constructor(e){this._dataSource=e}static storageKey="circuits";async loadCircuitData(e){let t=await this._dataSource.get(e.toString(),"circuitId");if(!t)throw new Error(`item not found: ${e}`);return t}async saveCircuitData(e,t){await this._dataSource.save(e.toString(),t,"circuitId")}};var VO=class{constructor(e){this._dataSource=e}static storageKey="credentials";async listCredentials(){return(await this._dataSource.load()).filter(t=>t!==void 0).map(t=>t&&Gr.fromJSON(t))}async saveCredential(e){return this._dataSource.save(e.id,e.toJSON())}async saveAllCredentials(e){for(let t of e)await this.saveCredential(t)}async removeCredential(e){return this._dataSource.delete(e)}async findCredentialById(e){let t=await this._dataSource.get(e);return t&&Gr.fromJSON(t)}async findCredentialsByQuery(e){let t=UO(e);return(await this._dataSource.load()).filter(o=>t.every(s=>s.execute(o))).filter(o=>o!==void 0).map(o=>Gr.fromJSON(o))}};var QO=class{constructor(e,t){this._identityDataSource=e;this._profileDataSource=t}static identitiesStorageKey="identities";static profilesStorageKey="profiles";async saveProfile(e){let r=(await this._profileDataSource.load()).filter(o=>o.genesisIdentifier===e.genesisIdentifier),i=r.length?[...r,e]:[e];for(let o=0;o<i.length;o++){let s=i[o];await this._profileDataSource.save(s.id,s)}}async getProfileByVerifier(e){return this._profileDataSource.get(e,"verifier")}async getProfilesByVerifier(e,t){return(await this._profileDataSource.load()).filter(r=>r.verifier===e&&(!t||t.every(i=>r.tags?.includes(i))))}async getProfileById(e){return this._profileDataSource.get(e)}async getProfilesByGenesisIdentifier(e){return(await this._profileDataSource.load()).filter(t=>t.genesisIdentifier===e)}async getAllIdentities(){return this._identityDataSource.load()}async saveIdentity(e){return this._identityDataSource.save(e.did,e,"did")}async getIdentity(e){return this._identityDataSource.get(e,"did")}};var zO=class{constructor(e){this.opts=e;this._verificationKeyPath=this.opts.verificationFileName??this._verificationKeyPath,this._provingKeyPath=this.opts.provingFileName??this._provingKeyPath,this._wasmFilePath=this.opts.wasmFileName??this._wasmFilePath}_verificationKeyPath="verification_key.json";_provingKeyPath="circuit_final.zkey";_wasmFilePath="circuit.wasm";_fs=null;_browserNotSupportedError=new Error("File system operations are not supported in browser environment");async getFs(){return this._fs?this._fs:(this._fs={existsSync:()=>{throw this._browserNotSupportedError},readFileSync:()=>{throw this._browserNotSupportedError},writeFileSync:()=>{throw this._browserNotSupportedError},mkdirSync:()=>{throw this._browserNotSupportedError}},this._fs)}async loadCircuitData(e){let t=await this.loadCircuitFile(e,this._verificationKeyPath),r=await this.loadCircuitFile(e,this._provingKeyPath),i=await this.loadCircuitFile(e,this._wasmFilePath);return{circuitId:e,wasm:i,provingKey:r,verificationKey:t}}async loadCircuitFile(e,t){let r=`${this.opts.dirname}/${e}/${t}`,i=await this.getFs();if(i.existsSync(r)){let o=i.readFileSync(r);return new Uint8Array(o)}return null}async writeCircuitFile(e,t,r,i){let o=`${this.opts.dirname}/${e}`,s=`${o}/${t}`,a=await this.getFs();a.mkdirSync(o,{recursive:!0}),a.writeFileSync(s,r,i)}async saveCircuitData(e,t){t.verificationKey&&await this.writeCircuitFile(e,this._verificationKeyPath,t.verificationKey,"utf-8"),t.provingKey&&await this.writeCircuitFile(e,this._provingKeyPath,t.provingKey),t.wasm&&await this.writeCircuitFile(e,this._wasmFilePath,t.wasm)}};var Gl=n=>{if(!n){let e=Nn.hash(new Array(3).fill(0n));return{proof:new Bt,treeState:{state:be.fromBigInt(e),claimsRoot:Ue,revocationRoot:Ue,rootOfRoots:Ue}}}return{proof:n.mtp,treeState:b5(n.issuer.state,n.issuer.claimsTreeRoot,n.issuer.revocationTreeRoot,n.issuer.rootOfRoots)}},lh=n=>{let e=!1,t;n.existence?e=!0:n.auxExistence&&(t={key:be.fromBigInt(n.auxIndex),value:be.fromBigInt(n.auxValue)});let r=n.siblings.map(s=>be.fromBigInt(s)),i=new Bt({siblings:r,nodeAux:t,existence:e});return{root:be.fromBigInt(n.root),proof:i}},QC=n=>{if(!n)return[{operator:dn.$noop,fieldName:""}];let e=[],t=Object.entries(n);if(!t.length)throw new Error("query must have at least 1 predicate");for(let[r,i]of t){let o=Object.entries(i);if(o.length===0){e.push({operator:dn.$sd,fieldName:r});continue}for(let[a,c]of o){if(!dn[a])throw new Error("operator is not supported by lib");let l=dn[a];e.push({operator:l,fieldName:r,operatorValue:c})}}return e},zC=async(n,e,t,r)=>{let i={...n,slotIndex:0,merklizedSchema:!1,datatype:"",claimPathKey:BigInt(0),values:[],path:new Ur};if(!n.fieldName&&n.operator!==0)throw new Error("query must have a field name if operator is not $noop");if(n.fieldName&&(i.datatype=await Ur.newTypeFromContext(e,`${t}.${n.fieldName}`,r)),await x2(JSON.parse(e),r,t)||(i.merklizedSchema=!0),!i.merklizedSchema)i.slotIndex=await A2(n.fieldName,t,Fe.encode(e));else try{let s=await UT(e,t,n.fieldName,r);i.claimPathKey=await s.mtEntry(),i.path=s}catch(s){throw new Error(`field does not exist in the schema ${s.message}`)}if(n.operatorValue!==void 0){if(!I5(i.datatype,n.operator))throw new Error(`operator ${n.operator} is not supported for datatype ${i.datatype}`);if((n.operator===0||n.operator===16)&&n.operatorValue)throw new Error(`operator value should be undefined for ${n.operator} operator`);let s;switch(n.operator){case 0:case 16:s=[];break;case 11:s=hRe(n.operatorValue);break;default:s=await YC(n.operatorValue,i.datatype)}i.values=s}return i},XE=async(n,e,t,r)=>{let i=QC(t);return Promise.all(i.map(o=>zC(o,e,n,r)))},YC=async(n,e)=>{let t=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)t[r]=await Sl.hashValue(e,n[r]);else t[0]=await Sl.hashValue(e,n);return t},hRe=n=>{if(typeof n=="boolean")return[BigInt(n)];throw new Error("exists operator value must be true or false")};async function WO(n,e){e=e||{};let t;try{t=await WebAssembly.compile(n)}catch(u){throw new Error(u)}let r="",i="",o=await WebAssembly.instantiate(t,{runtime:{exceptionHandler:function(u){let d;throw u==1?d=`Signal not found.
|
|
423
|
+
`);for(let d=0;d<l.length;d++){let h=B8e(BigInt(l[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(MM(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 u=(o*this.witnessSize).toString(16);r[c]=parseInt(u.slice(0,8),16),r[c+1]=parseInt(u.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 B8e(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 MM(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 P8e(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 k8e(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 Py=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function OC(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function OM(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function Zo(n,...e){if(!OC(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function M8e(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");OM(n.outputLen),OM(n.blockLen)}function LC(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function O8e(n,e){Zo(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function RC(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function vM(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Fl(n,e){return n<<32-e|n>>>e}var A$=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",F8e=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function NE(n){if(Zo(n),A$)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=F8e[n[t]];return e}var ld={_0:48,_9:57,A:65,F:70,a:97,f:102};function n$(n){if(n>=ld._0&&n<=ld._9)return n-ld._0;if(n>=ld.A&&n<=ld.F)return n-(ld.A-10);if(n>=ld.a&&n<=ld.f)return n-(ld.a-10)}function ZM(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(A$)return Uint8Array.fromHex(n);let e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let i=0,o=0;i<t;i++,o+=2){let s=n$(n.charCodeAt(o)),a=n$(n.charCodeAt(o+1));if(s===void 0||a===void 0){let c=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[i]=s*16+a}return r}function FC(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function XM(n){return typeof n=="string"&&(n=FC(n)),Zo(n),n}function so(...n){let e=0;for(let r=0;r<n.length;r++){let i=n[r];Zo(i),e+=i.length}let t=new Uint8Array(e);for(let r=0,i=0;r<n.length;r++){let o=n[r];t.set(o,i),i+=o.length}return t}var DC=class{};function N8e(n){let e=r=>n().update(XM(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function x$(n=32){if(Py&&typeof Py.getRandomValues=="function")return Py.getRandomValues(new Uint8Array(n));if(Py&&typeof Py.randomBytes=="function")return Uint8Array.from(Py.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}function U8e(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);let i=BigInt(32),o=BigInt(4294967295),s=Number(t>>i&o),a=Number(t&o),c=r?4:0,l=r?0:4;n.setUint32(e+c,s,r),n.setUint32(e+l,a,r)}function G8e(n,e,t){return n&e^~n&t}function K8e(n,e,t){return n&e^n&t^e&t}var FM=class extends DC{constructor(e,t,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=vM(this.buffer)}update(e){LC(this),e=XM(e),Zo(e);let{view:t,buffer:r,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=vM(e);for(;i<=o-s;s+=i)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){LC(this),O8e(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,RC(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)t[d]=0;U8e(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=vM(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},ih=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),H8e=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),oh=new Uint32Array(64),NM=class extends FM{constructor(e=32){super(64,e,8,!1),this.A=ih[0]|0,this.B=ih[1]|0,this.C=ih[2]|0,this.D=ih[3]|0,this.E=ih[4]|0,this.F=ih[5]|0,this.G=ih[6]|0,this.H=ih[7]|0}get(){let{A:e,B:t,C:r,D:i,E:o,F:s,G:a,H:c}=this;return[e,t,r,i,o,s,a,c]}set(e,t,r,i,o,s,a,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)oh[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=oh[d-15],f=oh[d-2],p=Fl(h,7)^Fl(h,18)^h>>>3,E=Fl(f,17)^Fl(f,19)^f>>>10;oh[d]=E+oh[d-7]+p+oh[d-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let h=Fl(a,6)^Fl(a,11)^Fl(a,25),f=u+h+G8e(a,c,l)+H8e[d]+oh[d]|0,E=(Fl(r,2)^Fl(r,13)^Fl(r,22))+K8e(r,i,o)|0;u=l,l=c,c=a,a=s+f|0,s=o,o=i,i=r,r=f+E|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,i,o,s,a,c,l,u)}roundClean(){RC(oh)}destroy(){this.set(0,0,0,0,0,0,0,0),RC(this.buffer)}},_M=N8e(()=>new NM);var $M=BigInt(0),TC=BigInt(1);function BC(n,e){if(typeof e!="boolean")throw new Error(n+" boolean expected, got "+e)}function IC(n){let e=n.toString(16);return e.length&1?"0"+e:e}function v$(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?$M:BigInt("0x"+n)}function HE(n){return v$(NE(n))}function S$(n){return Zo(n),v$(NE(Uint8Array.from(n).reverse()))}function eO(n,e){return ZM(n.toString(16).padStart(e*2,"0"))}function C$(n,e){return eO(n,e).reverse()}function Ls(n,e,t){let r;if(typeof e=="string")try{r=ZM(e)}catch(o){throw new Error(n+" must be hex string or Uint8Array, cause: "+o)}else if(OC(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");let i=r.length;if(typeof t=="number"&&i!==t)throw new Error(n+" of length "+t+" expected, got "+i);return r}var SM=n=>typeof n=="bigint"&&$M<=n;function L$(n,e,t){return SM(n)&&SM(e)&&SM(t)&&e<=n&&n<t}function J8e(n,e,t,r){if(!L$(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function kE(n){let e;for(e=0;n>$M;n>>=TC,e+=1);return e}function q8e(n,e){return n>>BigInt(e)&TC}var O0=n=>(TC<<BigInt(n))-TC;function V8e(n,e,t){if(typeof n!="number"||n<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=f=>new Uint8Array(f),i=f=>Uint8Array.of(f),o=r(n),s=r(n),a=0,c=()=>{o.fill(1),s.fill(0),a=0},l=(...f)=>t(s,o,...f),u=(f=r(0))=>{s=l(i(0),f),o=l(),f.length!==0&&(s=l(i(1),f),o=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<e;){o=l();let E=o.slice();p.push(E),f+=o.length}return so(...p)};return(f,p)=>{c(),u(f);let E;for(;!(E=p(d()));)u();return c(),E}}function Q8e(n){return typeof n=="function"&&Number.isSafeInteger(n.outputLen)}function NC(n,e,t={}){if(!n||typeof n!="object")throw new Error("expected valid options object");function r(i,o,s){let a=n[i];if(s&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([i,o])=>r(i,o,!1)),Object.entries(t).forEach(([i,o])=>r(i,o,!0))}var li=()=>{throw new Error("not implemented")};function UM(n){let e=new WeakMap;return(t,...r)=>{let i=e.get(t);if(i!==void 0)return i;let o=n(t,...r);return e.set(t,o),o}}var ta=BigInt(0),Wo=BigInt(1),k0=BigInt(2),z8e=BigInt(3),R$=BigInt(4),D$=BigInt(5),T$=BigInt(8);function Mc(n,e){let t=n%e;return t>=ta?t:e+t}function r$(n,e){if(n===ta)throw new Error("invert: expected non-zero number");if(e<=ta)throw new Error("invert: expected positive modulus, got "+e);let t=Mc(n,e),r=e,i=ta,o=Wo;for(;t!==ta;){let a=r/t,c=r%t,l=i-o*a;r=t,t=c,i=o,o=l}if(r!==Wo)throw new Error("invert: does not exist");return Mc(i,e)}function B$(n,e){let t=(n.ORDER+Wo)/R$,r=n.pow(e,t);if(!n.eql(n.sqr(r),e))throw new Error("Cannot find square root");return r}function Y8e(n,e){let t=(n.ORDER-D$)/T$,r=n.mul(e,k0),i=n.pow(r,t),o=n.mul(e,i),s=n.mul(n.mul(o,k0),i),a=n.mul(o,n.sub(s,n.ONE));if(!n.eql(n.sqr(a),e))throw new Error("Cannot find square root");return a}function j8e(n){if(n<BigInt(3))throw new Error("sqrt is not defined for small field");let e=n-Wo,t=0;for(;e%k0===ta;)e/=k0,t++;let r=k0,i=JE(n);for(;PC(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return B$;let o=i.pow(r,e),s=(e+Wo)/k0;return function(c,l){if(c.is0(l))return l;if(PC(c,l)!==1)throw new Error("Cannot find square root");let u=t,d=c.mul(c.ONE,o),h=c.pow(l,e),f=c.pow(l,s);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let p=1,E=c.sqr(h);for(;!c.eql(E,c.ONE);)if(p++,E=c.sqr(E),p===u)throw new Error("Cannot find square root");let b=Wo<<BigInt(u-p-1),C=c.pow(d,b);u=p,d=c.sqr(C),h=c.mul(h,d),f=c.mul(f,C)}return f}}function W8e(n){return n%R$===z8e?B$:n%T$===D$?Y8e:j8e(n)}var Z8e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function X8e(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=Z8e.reduce((r,i)=>(r[i]="function",r),e);return NC(n,t),n}function CC(n,e,t){if(t<ta)throw new Error("invalid exponent, negatives unsupported");if(t===ta)return n.ONE;if(t===Wo)return e;let r=n.ONE,i=e;for(;t>ta;)t&Wo&&(r=n.mul(r,i)),i=n.sqr(i),t>>=Wo;return r}function ME(n,e,t=!1){let r=new Array(e.length).fill(t?n.ZERO:void 0),i=e.reduce((s,a,c)=>n.is0(a)?s:(r[c]=s,n.mul(s,a)),n.ONE),o=n.inv(i);return e.reduceRight((s,a,c)=>n.is0(a)?s:(r[c]=n.mul(s,r[c]),n.mul(s,a)),o),r}function PC(n,e){let t=(n.ORDER-Wo)/k0,r=n.pow(e,t),i=n.eql(r,n.ONE),o=n.eql(r,n.ZERO),s=n.eql(r,n.neg(n.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function _8e(n,e){e!==void 0&&OM(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function JE(n,e,t=!1,r={}){if(n<=ta)throw new Error("invalid field: expected ORDER > 0, got "+n);let i,o;if(typeof e=="object"&&e!=null){if(r.sqrt||t)throw new Error("cannot specify opts in two arguments");let u=e;u.BITS&&(i=u.BITS),u.sqrt&&(o=u.sqrt),typeof u.isLE=="boolean"&&(t=u.isLE)}else typeof e=="number"&&(i=e),r.sqrt&&(o=r.sqrt);let{nBitLength:s,nByteLength:a}=_8e(n,i);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c,l=Object.freeze({ORDER:n,isLE:t,BITS:s,BYTES:a,MASK:O0(s),ZERO:ta,ONE:Wo,create:u=>Mc(u,n),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return ta<=u&&u<n},is0:u=>u===ta,isValidNot0:u=>!l.is0(u)&&l.isValid(u),isOdd:u=>(u&Wo)===Wo,neg:u=>Mc(-u,n),eql:(u,d)=>u===d,sqr:u=>Mc(u*u,n),add:(u,d)=>Mc(u+d,n),sub:(u,d)=>Mc(u-d,n),mul:(u,d)=>Mc(u*d,n),pow:(u,d)=>CC(l,u,d),div:(u,d)=>Mc(u*r$(d,n),n),sqrN:u=>u*u,addN:(u,d)=>u+d,subN:(u,d)=>u-d,mulN:(u,d)=>u*d,inv:u=>r$(u,n),sqrt:o||(u=>(c||(c=W8e(n)),c(l,u))),toBytes:u=>t?C$(u,a):eO(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return t?S$(u):HE(u)},invertBatch:u=>ME(l,u),cmov:(u,d,h)=>h?d:u});return Object.freeze(l)}function P$(n){if(typeof n!="bigint")throw new Error("field order must be bigint");let e=n.toString(2).length;return Math.ceil(e/8)}function tO(n){let e=P$(n);return e+Math.ceil(e/2)}function k$(n,e,t=!1){let r=n.length,i=P$(e),o=tO(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let s=t?S$(n):HE(n),a=Mc(s,e-Wo)+Wo;return t?C$(a,i):eO(a,i)}var Fy=BigInt(0),M0=BigInt(1);function OE(n,e){let t=e.negate();return n?t:e}function GM(n,e,t){let r=s=>s.pz,i=ME(n.Fp,t.map(r));return t.map((s,a)=>s.toAffine(i[a])).map(n.fromAffine)}function M$(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function CM(n,e){M$(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),i=2**n,o=O0(n),s=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function i$(n,e,t){let{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=t,a=Number(n&i),c=n>>s;a>r&&(a-=o,c+=M0);let l=e*r,u=l+Math.abs(a)-1,d=a===0,h=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:l}}function $8e(n,e){if(!Array.isArray(n))throw new Error("array expected");n.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function eLe(n,e){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}var LM=new WeakMap,O$=new WeakMap;function RM(n){return O$.get(n)||1}function o$(n){if(n!==Fy)throw new Error("invalid wNAF")}function tLe(n,e){return{constTimeNegate:OE,hasPrecomputes(t){return RM(t)!==1},unsafeLadder(t,r,i=n.ZERO){let o=t;for(;r>Fy;)r&M0&&(i=i.add(o)),o=o.double(),r>>=M0;return i},precomputeWindow(t,r){let{windows:i,windowSize:o}=CM(r,e),s=[],a=t,c=a;for(let l=0;l<i;l++){c=a,s.push(c);for(let u=1;u<o;u++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(t,r,i){let o=n.ZERO,s=n.BASE,a=CM(t,e);for(let c=0;c<a.windows;c++){let{nextN:l,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:p}=i$(i,c,a);i=l,d?s=s.add(OE(f,r[p])):o=o.add(OE(h,r[u]))}return o$(i),{p:o,f:s}},wNAFUnsafe(t,r,i,o=n.ZERO){let s=CM(t,e);for(let a=0;a<s.windows&&i!==Fy;a++){let{nextN:c,offset:l,isZero:u,isNeg:d}=i$(i,a,s);if(i=c,!u){let h=r[l];o=o.add(d?h.negate():h)}}return o$(i),o},getPrecomputes(t,r,i){let o=LM.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof i=="function"&&(o=i(o)),LM.set(r,o))),o},wNAFCached(t,r,i){let o=RM(t);return this.wNAF(o,this.getPrecomputes(o,t,i),r)},wNAFCachedUnsafe(t,r,i,o){let s=RM(t);return s===1?this.unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,i),r,o)},setWindowSize(t,r){M$(r,e),O$.set(t,r),LM.delete(t)}}}function nLe(n,e,t,r){let i=e,o=n.ZERO,s=n.ZERO;for(;t>Fy||r>Fy;)t&M0&&(o=o.add(i)),r&M0&&(s=s.add(i)),i=i.double(),t>>=M0,r>>=M0;return{p1:o,p2:s}}function rLe(n,e,t,r){$8e(t,n),eLe(r,e);let i=t.length,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=n.ZERO,a=kE(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=O0(c),u=new Array(Number(l)+1).fill(s),d=Math.floor((e.BITS-1)/c)*c,h=s;for(let f=d;f>=0;f-=c){u.fill(s);for(let E=0;E<o;E++){let b=r[E],C=Number(b>>BigInt(f)&l);u[C]=u[C].add(t[E])}let p=s;for(let E=u.length-1,b=s;E>0;E--)b=b.add(u[E]),p=p.add(b);if(h=h.add(p),f!==0)for(let E=0;E<c;E++)h=h.double()}return h}function s$(n,e){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return X8e(e),e}else return JE(n)}function iLe(n,e,t={}){if(!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let a of["p","n","h"]){let c=e[a];if(!(typeof c=="bigint"&&c>Fy))throw new Error(`CURVE.${a} must be positive bigint`)}let r=s$(e.p,t.Fp),i=s$(e.n,t.Fn),s=["Gx","Gy","a","b"];for(let a of s)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:i}}var oLe=HE;function sh(n,e){if(UE(n),UE(e),n<0||n>=1<<8*e)throw new Error("invalid I2OSP input: "+n);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=n&255,n>>>=8;return new Uint8Array(t)}function sLe(n,e){let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function UE(n){if(!Number.isSafeInteger(n))throw new Error("number expected")}function aLe(n,e,t,r){Zo(n),Zo(e),UE(t),e.length>255&&(e=r(so(FC("H2C-OVERSIZE-DST-"),e)));let{outputLen:i,blockLen:o}=r,s=Math.ceil(t/i);if(t>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=so(e,sh(e.length,1)),c=sh(0,o),l=sh(t,2),u=new Array(s),d=r(so(c,n,l,sh(0,1),a));u[0]=r(so(d,sh(1,1),a));for(let f=1;f<=s;f++){let p=[sLe(d,u[f-1]),sh(f+1,1),a];u[f]=r(so(...p))}return so(...u).slice(0,t)}function cLe(n,e,t,r,i){if(Zo(n),Zo(e),UE(t),e.length>255){let o=Math.ceil(2*r/8);e=i.create({dkLen:o}).update(FC("H2C-OVERSIZE-DST-")).update(e).digest()}if(t>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:t}).update(n).update(sh(t,2)).update(e).update(sh(e.length,1)).digest()}function a$(n,e,t){NC(t,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:s,expand:a,DST:c}=t;if(!OC(c)&&typeof c!="string")throw new Error("DST must be string or uint8array");if(!Q8e(t.hash))throw new Error("expected valid hash");Zo(n),UE(e);let l=typeof c=="string"?FC(c):c,u=r.toString(2).length,d=Math.ceil((u+i)/8),h=e*o*d,f;if(a==="xmd")f=aLe(n,l,h,s);else if(a==="xof")f=cLe(n,l,h,i,s);else if(a==="_internal_pass")f=n;else throw new Error('expand must be "xmd" or "xof"');let p=new Array(e);for(let E=0;E<e;E++){let b=new Array(o);for(let C=0;C<o;C++){let B=d*(C+E*o),J=f.subarray(B,B+d);b[C]=Mc(oLe(J),r)}p[E]=b}return p}function c$(n,e,t){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function r(o){return n.fromAffine(e(o))}function i(o){let s=o.clearCofactor();return s.equals(n.ZERO)?n.ZERO:(s.assertValidity(),s)}return{defaults:t,hashToCurve(o,s){let a=t.DST?t.DST:{},c=Object.assign({},t,a,s),l=a$(o,2,c),u=r(l[0]),d=r(l[1]);return i(u.add(d))},encodeToCurve(o,s){let a=t.encodeDST?t.encodeDST:{},c=Object.assign({},t,a,s),l=a$(o,1,c);return i(r(l[0]))},mapToCurve(o){if(!Array.isArray(o))throw new Error("expected array of bigints");for(let s of o)if(typeof s!="bigint")throw new Error("expected array of bigints");return i(r(o))}}}var kC=class extends DC{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,M8e(e);let r=XM(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),RC(o)}update(e){return LC(this),this.iHash.update(e),this}digestInto(e){LC(this),Zo(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:r,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},F$=(n,e,t)=>new kC(n,e).update(t).digest();F$.create=(n,e)=>new kC(n,e);function l$(n){n.lowS!==void 0&&BC("lowS",n.lowS),n.prehash!==void 0&&BC("prehash",n.prehash)}var KM=class extends Error{constructor(e=""){super(e)}},ud={Err:KM,_tlv:{encode:(n,e)=>{let{Err:t}=ud;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,i=IC(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?IC(i.length/2|128):"";return IC(n)+o+i+e},decode(n,e){let{Err:t}=ud,r=0;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==n)throw new t("tlv.decode: wrong tlv");let i=e[r++],o=!!(i&128),s=0;if(!o)s=i;else{let c=i&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(r+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(n){let{Err:e}=ud;if(n<FE)throw new e("integer: negative integers are not allowed");let t=IC(n);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(n){let{Err:e}=ud;if(n[0]&128)throw new e("invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return HE(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=ud,i=Ls("signature",n),{v:o,l:s}=r.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,o),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(n){let{_tlv:e,_int:t}=ud,r=e.encode(2,t.encode(n.r)),i=e.encode(2,t.encode(n.s)),o=r+i;return e.encode(48,o)}},FE=BigInt(0),Oy=BigInt(1),lLe=BigInt(2),AC=BigInt(3),uLe=BigInt(4);function N$(n,e,t){function r(i){let o=n.sqr(i),s=n.mul(o,i);return n.add(n.add(s,n.mul(i,e)),t)}return r}function nO(n,e,t){let{BYTES:r}=n;function i(o){let s;if(typeof o=="bigint")s=o;else{let a=Ls("private key",o);if(e){if(!e.includes(a.length*2))throw new Error("invalid private key");let c=new Uint8Array(r);c.set(a,c.length-a.length),a=c}try{s=n.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof o}`)}}if(t&&(s=n.create(s)),!n.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}return i}function U$(n,e={}){let{Fp:t,Fn:r}=iLe("weierstrass",n,e),{h:i,n:o}=n;NC(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:s}=e;if(s&&(!t.is0(n.a)||typeof s.beta!="bigint"||typeof s.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(D,z,j){let{x:Y,y:H}=z.toAffine(),I=t.toBytes(Y);if(BC("isCompressed",j),j){a();let m=!t.isOdd(H);return so(G$(m),I)}else return so(Uint8Array.of(4),I,t.toBytes(H))}function l(D){Zo(D);let z=t.BYTES,j=z+1,Y=2*z+1,H=D.length,I=D[0],m=D.subarray(1);if(H===j&&(I===2||I===3)){let x=t.fromBytes(m);if(!t.isValid(x))throw new Error("bad point: is not on curve, wrong x");let y=h(x),A;try{A=t.sqrt(y)}catch(N){let M=N instanceof Error?": "+N.message:"";throw new Error("bad point: is not on curve, sqrt error"+M)}a();let L=t.isOdd(A);return(I&1)===1!==L&&(A=t.neg(A)),{x,y:A}}else if(H===Y&&I===4){let x=t.fromBytes(m.subarray(z*0,z*1)),y=t.fromBytes(m.subarray(z*1,z*2));if(!f(x,y))throw new Error("bad point: is not on curve");return{x,y}}else throw new Error(`bad point: got length ${H}, expected compressed=${j} or uncompressed=${Y}`)}let u=e.toBytes||c,d=e.fromBytes||l,h=N$(t,n.a,n.b);function f(D,z){let j=t.sqr(z),Y=h(D);return t.eql(j,Y)}if(!f(n.Gx,n.Gy))throw new Error("bad curve params: generator point");let p=t.mul(t.pow(n.a,AC),uLe),E=t.mul(t.sqr(n.b),BigInt(27));if(t.is0(t.add(p,E)))throw new Error("bad curve params: a or b");function b(D,z,j=!1){if(!t.isValid(z)||j&&t.is0(z))throw new Error(`bad point coordinate ${D}`);return z}function C(D){if(!(D instanceof U))throw new Error("ProjectivePoint expected")}let B=UM((D,z)=>{let{px:j,py:Y,pz:H}=D;if(t.eql(H,t.ONE))return{x:j,y:Y};let I=D.is0();z==null&&(z=I?t.ONE:t.inv(H));let m=t.mul(j,z),x=t.mul(Y,z),y=t.mul(H,z);if(I)return{x:t.ZERO,y:t.ZERO};if(!t.eql(y,t.ONE))throw new Error("invZ was invalid");return{x:m,y:x}}),J=UM(D=>{if(D.is0()){if(e.allowInfinityPoint&&!t.is0(D.py))return;throw new Error("bad point: ZERO")}let{x:z,y:j}=D.toAffine();if(!t.isValid(z)||!t.isValid(j))throw new Error("bad point: x or y not field elements");if(!f(z,j))throw new Error("bad point: equation left != right");if(!D.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function G(D,z,j,Y,H){return j=new U(t.mul(j.px,D),j.py,j.pz),z=OE(Y,z),j=OE(H,j),z.add(j)}class U{constructor(z,j,Y){this.px=b("x",z),this.py=b("y",j,!0),this.pz=b("z",Y),Object.freeze(this)}static fromAffine(z){let{x:j,y:Y}=z||{};if(!z||!t.isValid(j)||!t.isValid(Y))throw new Error("invalid affine point");if(z instanceof U)throw new Error("projective point not allowed");return t.is0(j)&&t.is0(Y)?U.ZERO:new U(j,Y,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(z){return GM(U,"pz",z)}static fromBytes(z){return Zo(z),U.fromHex(z)}static fromHex(z){let j=U.fromAffine(d(Ls("pointHex",z)));return j.assertValidity(),j}static fromPrivateKey(z){let j=nO(r,e.allowedPrivateKeyLengths,e.wrapPrivateKey);return U.BASE.multiply(j(z))}static msm(z,j){return rLe(U,r,z,j)}precompute(z=8,j=!0){return v.setWindowSize(this,z),j||this.multiply(AC),this}_setWindowSize(z){this.precompute(z)}assertValidity(){J(this)}hasEvenY(){let{y:z}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(z)}equals(z){C(z);let{px:j,py:Y,pz:H}=this,{px:I,py:m,pz:x}=z,y=t.eql(t.mul(j,x),t.mul(I,H)),A=t.eql(t.mul(Y,x),t.mul(m,H));return y&&A}negate(){return new U(this.px,t.neg(this.py),this.pz)}double(){let{a:z,b:j}=n,Y=t.mul(j,AC),{px:H,py:I,pz:m}=this,x=t.ZERO,y=t.ZERO,A=t.ZERO,L=t.mul(H,H),F=t.mul(I,I),N=t.mul(m,m),M=t.mul(H,I);return M=t.add(M,M),A=t.mul(H,m),A=t.add(A,A),x=t.mul(z,A),y=t.mul(Y,N),y=t.add(x,y),x=t.sub(F,y),y=t.add(F,y),y=t.mul(x,y),x=t.mul(M,x),A=t.mul(Y,A),N=t.mul(z,N),M=t.sub(L,N),M=t.mul(z,M),M=t.add(M,A),A=t.add(L,L),L=t.add(A,L),L=t.add(L,N),L=t.mul(L,M),y=t.add(y,L),N=t.mul(I,m),N=t.add(N,N),L=t.mul(N,M),x=t.sub(x,L),A=t.mul(N,F),A=t.add(A,A),A=t.add(A,A),new U(x,y,A)}add(z){C(z);let{px:j,py:Y,pz:H}=this,{px:I,py:m,pz:x}=z,y=t.ZERO,A=t.ZERO,L=t.ZERO,F=n.a,N=t.mul(n.b,AC),M=t.mul(j,I),T=t.mul(Y,m),Q=t.mul(H,x),_=t.add(j,Y),S=t.add(I,m);_=t.mul(_,S),S=t.add(M,T),_=t.sub(_,S),S=t.add(j,H);let g=t.add(I,x);return S=t.mul(S,g),g=t.add(M,Q),S=t.sub(S,g),g=t.add(Y,H),y=t.add(m,x),g=t.mul(g,y),y=t.add(T,Q),g=t.sub(g,y),L=t.mul(F,S),y=t.mul(N,Q),L=t.add(y,L),y=t.sub(T,L),L=t.add(T,L),A=t.mul(y,L),T=t.add(M,M),T=t.add(T,M),Q=t.mul(F,Q),S=t.mul(N,S),T=t.add(T,Q),Q=t.sub(M,Q),Q=t.mul(F,Q),S=t.add(S,Q),M=t.mul(T,S),A=t.add(A,M),M=t.mul(g,S),y=t.mul(_,y),y=t.sub(y,M),M=t.mul(_,T),L=t.mul(g,L),L=t.add(L,M),new U(y,A,L)}subtract(z){return this.add(z.negate())}is0(){return this.equals(U.ZERO)}multiply(z){let{endo:j}=e;if(!r.isValidNot0(z))throw new Error("invalid scalar: out of range");let Y,H,I=m=>v.wNAFCached(this,m,U.normalizeZ);if(j){let{k1neg:m,k1:x,k2neg:y,k2:A}=j.splitScalar(z),{p:L,f:F}=I(x),{p:N,f:M}=I(A);H=F.add(M),Y=G(j.beta,L,N,m,y)}else{let{p:m,f:x}=I(z);Y=m,H=x}return U.normalizeZ([Y,H])[0]}multiplyUnsafe(z){let{endo:j}=e,Y=this;if(!r.isValid(z))throw new Error("invalid scalar: out of range");if(z===FE||Y.is0())return U.ZERO;if(z===Oy)return Y;if(v.hasPrecomputes(this))return this.multiply(z);if(j){let{k1neg:H,k1:I,k2neg:m,k2:x}=j.splitScalar(z),{p1:y,p2:A}=nLe(U,Y,I,x);return G(j.beta,y,A,H,m)}else return v.wNAFCachedUnsafe(Y,z)}multiplyAndAddUnsafe(z,j,Y){let H=this.multiplyUnsafe(j).add(z.multiplyUnsafe(Y));return H.is0()?void 0:H}toAffine(z){return B(this,z)}isTorsionFree(){let{isTorsionFree:z}=e;return i===Oy?!0:z?z(U,this):v.wNAFCachedUnsafe(this,o).is0()}clearCofactor(){let{clearCofactor:z}=e;return i===Oy?this:z?z(U,this):this.multiplyUnsafe(i)}toBytes(z=!0){return BC("isCompressed",z),this.assertValidity(),u(U,this,z)}toRawBytes(z=!0){return this.toBytes(z)}toHex(z=!0){return NE(this.toBytes(z))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}U.BASE=new U(n.Gx,n.Gy,t.ONE),U.ZERO=new U(t.ZERO,t.ONE,t.ZERO),U.Fp=t,U.Fn=r;let O=r.BITS,v=tLe(U,e.endo?Math.ceil(O/2):O);return U}function u$(n){let{CURVE:e,curveOpts:t}=K$(n),r=U$(e,t);return hLe(n,r)}function G$(n){return Uint8Array.of(n?2:3)}function dLe(n,e,t={}){NC(e,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=e.randomBytes||x$,i=e.hmac||((Y,...H)=>F$(e.hash,Y,so(...H))),{Fp:o,Fn:s}=n,{ORDER:a,BITS:c}=s;function l(Y){let H=a>>Oy;return Y>H}function u(Y){return l(Y)?s.neg(Y):Y}function d(Y,H){if(!s.isValidNot0(H))throw new Error(`invalid signature ${Y}: out of range 1..CURVE.n`)}class h{constructor(H,I,m){d("r",H),d("s",I),this.r=H,this.s=I,m!=null&&(this.recovery=m),Object.freeze(this)}static fromCompact(H){let I=s.BYTES,m=Ls("compactSignature",H,I*2);return new h(s.fromBytes(m.subarray(0,I)),s.fromBytes(m.subarray(I,I*2)))}static fromDER(H){let{r:I,s:m}=ud.toSig(Ls("DER",H));return new h(I,m)}assertValidity(){}addRecoveryBit(H){return new h(this.r,this.s,H)}recoverPublicKey(H){let I=o.ORDER,{r:m,s:x,recovery:y}=this;if(y==null||![0,1,2,3].includes(y))throw new Error("recovery id invalid");if(a*lLe<I&&y>1)throw new Error("recovery id is ambiguous for h>1 curve");let L=y===2||y===3?m+a:m;if(!o.isValid(L))throw new Error("recovery id 2 or 3 invalid");let F=o.toBytes(L),N=n.fromHex(so(G$((y&1)===0),F)),M=s.inv(L),T=J(Ls("msgHash",H)),Q=s.create(-T*M),_=s.create(x*M),S=n.BASE.multiplyUnsafe(Q).add(N.multiplyUnsafe(_));if(S.is0())throw new Error("point at infinify");return S.assertValidity(),S}hasHighS(){return l(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,s.neg(this.s),this.recovery):this}toBytes(H){if(H==="compact")return so(s.toBytes(this.r),s.toBytes(this.s));if(H==="der")return ZM(ud.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return NE(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return NE(this.toBytes("compact"))}}let f=nO(s,t.allowedPrivateKeyLengths,t.wrapPrivateKey),p={isValidPrivateKey(Y){try{return f(Y),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let Y=a;return k$(r(tO(Y)),Y)},precompute(Y=8,H=n.BASE){return H.precompute(Y,!1)}};function E(Y,H=!0){return n.fromPrivateKey(Y).toBytes(H)}function b(Y){if(typeof Y=="bigint")return!1;if(Y instanceof n)return!0;let I=Ls("key",Y).length,m=o.BYTES,x=m+1,y=2*m+1;if(!(t.allowedPrivateKeyLengths||s.BYTES===x))return I===x||I===y}function C(Y,H,I=!0){if(b(Y)===!0)throw new Error("first arg must be private key");if(b(H)===!1)throw new Error("second arg must be public key");return n.fromHex(H).multiply(f(Y)).toBytes(I)}let B=e.bits2int||function(Y){if(Y.length>8192)throw new Error("input is too large");let H=HE(Y),I=Y.length*8-c;return I>0?H>>BigInt(I):H},J=e.bits2int_modN||function(Y){return s.create(B(Y))},G=O0(c);function U(Y){return J8e("num < 2^"+c,Y,FE,G),s.toBytes(Y)}function O(Y,H,I=v){if(["recovered","canonical"].some(_=>_ in I))throw new Error("sign() legacy options not supported");let{hash:m}=e,{lowS:x,prehash:y,extraEntropy:A}=I;x==null&&(x=!0),Y=Ls("msgHash",Y),l$(I),y&&(Y=Ls("prehashed msgHash",m(Y)));let L=J(Y),F=f(H),N=[U(F),U(L)];if(A!=null&&A!==!1){let _=A===!0?r(o.BYTES):A;N.push(Ls("extraEntropy",_))}let M=so(...N),T=L;function Q(_){let S=B(_);if(!s.isValidNot0(S))return;let g=s.inv(S),K=n.BASE.multiply(S).toAffine(),w=s.create(K.x);if(w===FE)return;let q=s.create(g*s.create(T+w*F));if(q===FE)return;let V=(K.x===w?0:2)|Number(K.y&Oy),R=q;return x&&l(q)&&(R=u(q),V^=1),new h(w,R,V)}return{seed:M,k2sig:Q}}let v={lowS:e.lowS,prehash:!1},D={lowS:e.lowS,prehash:!1};function z(Y,H,I=v){let{seed:m,k2sig:x}=O(Y,H,I);return V8e(e.hash.outputLen,s.BYTES,i)(m,x)}n.BASE.precompute(8);function j(Y,H,I,m=D){let x=Y;H=Ls("msgHash",H),I=Ls("publicKey",I),l$(m);let{lowS:y,prehash:A,format:L}=m;if("strict"in m)throw new Error("options.strict was renamed to lowS");if(L!==void 0&&!["compact","der","js"].includes(L))throw new Error('format must be "compact", "der" or "js"');let F=typeof x=="string"||OC(x),N=!F&&!L&&typeof x=="object"&&x!==null&&typeof x.r=="bigint"&&typeof x.s=="bigint";if(!F&&!N)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let M,T;try{if(N)if(L===void 0||L==="js")M=new h(x.r,x.s);else throw new Error("invalid format");if(F){try{L!=="compact"&&(M=h.fromDER(x))}catch(R){if(!(R instanceof ud.Err))throw R}!M&&L!=="der"&&(M=h.fromCompact(x))}T=n.fromHex(I)}catch{return!1}if(!M||y&&M.hasHighS())return!1;A&&(H=e.hash(H));let{r:Q,s:_}=M,S=J(H),g=s.inv(_),K=s.create(S*g),w=s.create(Q*g),q=n.BASE.multiplyUnsafe(K).add(T.multiplyUnsafe(w));return q.is0()?!1:s.create(q.x)===Q}return Object.freeze({getPublicKey:E,getSharedSecret:C,sign:z,verify:j,utils:p,Point:n,Signature:h})}function K$(n){let e={a:n.a,b:n.b,p:n.Fp.ORDER,n:n.n,h:n.h,Gx:n.Gx,Gy:n.Gy},t=n.Fp,r=JE(e.n,n.nBitLength),i={Fp:t,Fn:r,allowedPrivateKeyLengths:n.allowedPrivateKeyLengths,allowInfinityPoint:n.allowInfinityPoint,endo:n.endo,wrapPrivateKey:n.wrapPrivateKey,isTorsionFree:n.isTorsionFree,clearCofactor:n.clearCofactor,fromBytes:n.fromBytes,toBytes:n.toBytes};return{CURVE:e,curveOpts:i}}function fLe(n){let{CURVE:e,curveOpts:t}=K$(n),r={hash:n.hash,hmac:n.hmac,randomBytes:n.randomBytes,lowS:n.lowS,bits2int:n.bits2int,bits2int_modN:n.bits2int_modN};return{CURVE:e,curveOpts:t,ecdsaOpts:r}}function hLe(n,e){let{Fp:t,Fn:r}=e;function i(a){return L$(a,Oy,r.ORDER)}let o=N$(t,n.a,n.b),s=nO(r,n.allowedPrivateKeyLengths,n.wrapPrivateKey);return Object.assign({},{CURVE:n,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:s,weierstrassEquation:o,isWithinCurveOrder:i})}function pLe(n,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:n})}function mLe(n){let{CURVE:e,curveOpts:t,ecdsaOpts:r}=fLe(n),i=U$(e,t),o=dLe(i,r,t);return pLe(n,o)}var gLe=BigInt(0),xC=BigInt(1),d$=BigInt(2),ky=BigInt(3);function yLe(n){let e=[];for(;n>xC;n>>=xC)(n&xC)===gLe?e.unshift(0):(n&ky)===ky?(e.unshift(-1),n+=xC):e.unshift(1);return e}function wLe(n){let{Fp:e,Fr:t,Fp2:r,Fp6:i,Fp12:o}=n.fields,s=u$(n.G1),a=Object.assign(s,c$(s.Point,n.G1.mapToCurve,{...n.htfDefaults,...n.G1.htfDefaults})),c=u$(n.G2),l=Object.assign(c,c$(c.Point,n.G2.mapToCurve,{...n.htfDefaults,...n.G2.htfDefaults})),u;u=(S,g,K,w,q,V)=>o.mul034(w,r.mul(K,V),r.mul(g,q),S);let d=r.div(r.ONE,r.mul(r.ONE,d$));function h(S,g,K,w){let q=r.sqr(K),V=r.sqr(w),R=r.mulByB(r.mul(V,ky)),X=r.mul(R,ky),re=r.sub(r.sub(r.sqr(r.add(K,w)),V),q),ee=r.sub(R,q),le=r.mul(r.sqr(g),ky),Be=r.neg(re);return S.push([ee,le,Be]),g=r.mul(r.mul(r.mul(r.sub(q,X),g),K),d),K=r.sub(r.sqr(r.mul(r.add(q,X),d)),r.mul(r.sqr(R),ky)),w=r.mul(q,re),{Rx:g,Ry:K,Rz:w}}function f(S,g,K,w,q,V){let R=r.sub(K,r.mul(V,w)),X=r.sub(g,r.mul(q,w)),re=r.sub(r.mul(R,q),r.mul(X,V)),ee=r.neg(R),le=X;S.push([re,ee,le]);let Be=r.sqr(X),xe=r.mul(Be,X),Pe=r.mul(Be,g),ct=r.add(r.sub(xe,r.mul(Pe,d$)),r.mul(r.sqr(R),w));return g=r.mul(X,ct),K=r.sub(r.mul(r.sub(Pe,ct),R),r.mul(xe,K)),w=r.mul(w,xe),{Rx:g,Ry:K,Rz:w}}let p=yLe(n.params.ateLoopSize),E=UM(S=>{let g=S,{x:K,y:w}=g.toAffine(),q=K,V=w,R=r.neg(w),X=q,re=V,ee=r.ONE,le=[];for(let Be of p){let xe=[];({Rx:X,Ry:re,Rz:ee}=h(xe,X,re,ee)),Be&&({Rx:X,Ry:re,Rz:ee}=f(xe,X,re,ee,q,Be===-1?R:V)),le.push(xe)}if(n.postPrecompute){let Be=le[le.length-1];n.postPrecompute(X,re,ee,q,V,f.bind(null,Be))}return le});function b(S,g=!1){let K=o.ONE;if(S.length){let w=S[0][0].length;for(let q=0;q<w;q++){K=o.sqr(K);for(let[V,R,X]of S)for(let[re,ee,le]of V[q])K=u(re,ee,le,K,R,X)}}return g?o.finalExponentiate(K):K}function C(S,g=!0){let K=[];GM(a.Point,"pz",S.map(({g1:w})=>w)),GM(l.Point,"pz",S.map(({g2:w})=>w));for(let{g1:w,g2:q}of S){if(w.is0()||q.is0())throw new Error("pairing is not available for ZERO point");w.assertValidity(),q.assertValidity();let V=w.toAffine();K.push([E(q),V.x,V.y])}return b(K,g)}function B(S,g,K=!0){return C([{g1:S,g2:g}],K)}let J=n.randomBytes||x$,G={randomPrivateKey:()=>{let S=tO(t.ORDER);return k$(J(S),t.ORDER)},calcPairingPrecomputes:E};function U(S){if(!Array.isArray(S)||S.length===0)throw new Error("expected non-empty array")}function O(S){return S instanceof a.Point?S:a.Point.fromHex(S)}function v(S){return S instanceof l.Point?S:H.fromHex(S)}function D(S,g){function K(R){return R instanceof S.Point?R:S.Point.fromHex(R)}function w(R){return R instanceof g.Point?R:g.Point.fromHex(R)}function q(R){if(!(R instanceof g.Point))throw new Error(`expected valid message hashed to ${V?"G2":"G1"} curve`);return R}let V=g.Point.Fp.BYTES>S.Point.Fp.BYTES;return{getPublicKey(R){return S.Point.fromPrivateKey(R)},sign(R,X,re){if(re!=null)throw new Error("sign() expects 2 arguments");return q(R).assertValidity(),R.multiply(S.normPrivateKeyToScalar(X))},verify(R,X,re,ee){if(ee!=null)throw new Error("verify() expects 3 arguments");R=w(R),re=K(re);let le=re.negate(),Be=S.Point.BASE,xe=q(X),Pe=R,Te=C(V?[{g1:le,g2:xe},{g1:Be,g2:Pe}]:[{g1:xe,g2:le},{g1:Pe,g2:Be}]);return o.eql(Te,o.ONE)},aggregatePublicKeys(R){U(R),R=R.map(re=>K(re));let X=R.reduce((re,ee)=>re.add(ee),S.Point.ZERO);return X.assertValidity(),X},aggregateSignatures(R){U(R),R=R.map(re=>w(re));let X=R.reduce((re,ee)=>re.add(ee),g.Point.ZERO);return X.assertValidity(),X},hash(R,X){Zo(R);let re=X?{DST:X}:void 0;return g.hashToCurve(R,re)},Signature:V?n.G2.Signature:n.G1.ShortSignature}}let z=D(a,l),j=D(l,a),{ShortSignature:Y}=n.G1,{Signature:H}=n.G2;function I(S,g){return S instanceof a.Point?S:j.hash(Ls("point",S),g?.DST)}function m(S,g){return S instanceof l.Point?S:z.hash(Ls("point",S),g?.DST)}function x(S){return z.getPublicKey(S).toBytes(!0)}function y(S){return j.getPublicKey(S).toBytes(!0)}function A(S,g,K){let w=m(S,K),q=z.sign(w,g);return S instanceof l.Point?q:H.toBytes(q)}function L(S,g,K){let w=I(S,K),q=j.sign(w,g);return S instanceof a.Point?q:Y.toBytes(q)}function F(S,g,K,w){let q=m(g,w);return z.verify(S,q,K)}function N(S,g,K,w){let q=I(g,w);return j.verify(S,q,K)}function M(S){let g=z.aggregatePublicKeys(S);return S[0]instanceof a.Point?g:g.toBytes(!0)}function T(S){let g=z.aggregateSignatures(S);return S[0]instanceof l.Point?g:H.toBytes(g)}function Q(S){let g=j.aggregateSignatures(S);return S[0]instanceof a.Point?g:Y.toBytes(g)}function _(S,g,K,w){if(U(g),K.length!==g.length)throw new Error("amount of public keys and messages should be equal");let q=v(S),V=g.map(ee=>m(ee,w)),R=K.map(O),X=new Map;for(let ee=0;ee<R.length;ee++){let le=R[ee],Be=V[ee],xe=X.get(Be);xe===void 0&&(xe=[],X.set(Be,xe)),xe.push(le)}let re=[];try{for(let[ee,le]of X){let Be=le.reduce((xe,Pe)=>xe.add(Pe));re.push({g1:Be,g2:ee})}return re.push({g1:a.Point.BASE.negate(),g2:q}),o.eql(C(re),o.ONE)}catch{return!1}}return a.Point.BASE.precompute(4),{longSignatures:z,shortSignatures:j,millerLoopBatch:b,pairing:B,pairingBatch:C,verifyBatch:_,curves:{G1:s.Point,G2:c.Point},fields:{Fr:t,Fp:e,Fp2:r,Fp6:i,Fp12:o},params:{ateLoopSize:n.params.ateLoopSize,twistType:n.params.twistType,r:n.params.r,G1b:n.G1.b,G2b:n.G2.b},utils:G,getPublicKey:x,getPublicKeyForShortSignatures:y,sign:A,signShortSignature:L,verify:F,verifyShortSignature:N,aggregatePublicKeys:M,aggregateSignatures:T,aggregateShortSignatures:Q,G1:a,G2:l,Signature:H,ShortSignature:Y}}var f$=BigInt(0),My=BigInt(1),dd=BigInt(2),h$=BigInt(3);function DM(n,e,t,r,i=1,o){let s=BigInt(o===void 0?r:o),a=t**BigInt(r),c=[];for(let l=0;l<i;l++){let u=BigInt(l+1),d=[];for(let h=0,f=My;h<r;h++){let p=(u*f-u)/s%a;d.push(n.pow(e,p)),f*=t}c.push(d)}return c}function bLe(n,e,t){let r=e.pow(t,(n.ORDER-My)/h$),i=e.pow(t,(n.ORDER-My)/dd);function o(h,f){let p=e.mul(e.frobeniusMap(h,1),r),E=e.mul(e.frobeniusMap(f,1),i);return[p,E]}let s=e.pow(t,(n.ORDER**dd-My)/h$),a=e.pow(t,(n.ORDER**dd-My)/dd);if(!e.eql(a,e.neg(e.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(h,f){return[e.mul(h,s),e.neg(f)]}let l=h=>(f,p)=>{let E=p.toAffine(),b=h(E.x,E.y);return f.fromAffine({x:b[0],y:b[1]})},u=l(o),d=l(c);return{psi:o,psi2:c,G2psi:u,G2psi2:d,PSI_X:r,PSI_Y:i,PSI2_X:s,PSI2_Y:a}}function ELe(n){let{ORDER:e}=n,t=JE(e),r=t.create(n.NONRESIDUE||BigInt(-1)),i=t.div(t.ONE,dd),o=DM(t,r,t.ORDER,2)[0],s=({c0:I,c1:m},{c0:x,c1:y})=>({c0:t.add(I,x),c1:t.add(m,y)}),a=({c0:I,c1:m},{c0:x,c1:y})=>({c0:t.sub(I,x),c1:t.sub(m,y)}),c=({c0:I,c1:m},x)=>{if(typeof x=="bigint")return{c0:t.mul(I,x),c1:t.mul(m,x)};let{c0:y,c1:A}=x,L=t.mul(I,y),F=t.mul(m,A),N=t.sub(L,F),M=t.sub(t.mul(t.add(I,m),t.add(y,A)),t.add(L,F));return{c0:N,c1:M}},l=({c0:I,c1:m})=>{let x=t.add(I,m),y=t.sub(I,m),A=t.add(I,I);return{c0:t.mul(x,y),c1:t.mul(A,m)}},u=I=>{if(I.length!==2)throw new Error("invalid tuple");let m=I.map(x=>t.create(x));return{c0:m[0],c1:m[1]}};function d(I,m){return typeof I=="bigint"&&f$<=I&&I<m}let h=e*e,f=u(n.FP2_NONRESIDUE),p={ORDER:h,isLE:t.isLE,NONRESIDUE:f,BITS:kE(h),BYTES:Math.ceil(kE(h)/8),MASK:O0(kE(h)),ZERO:{c0:t.ZERO,c1:t.ZERO},ONE:{c0:t.ONE,c1:t.ZERO},create:I=>I,isValid:({c0:I,c1:m})=>d(I,h)&&d(m,h),is0:({c0:I,c1:m})=>t.is0(I)&&t.is0(m),isValidNot0:I=>!p.is0(I)&&p.isValid(I),eql:({c0:I,c1:m},{c0:x,c1:y})=>t.eql(I,x)&&t.eql(m,y),neg:({c0:I,c1:m})=>({c0:t.neg(I),c1:t.neg(m)}),pow:(I,m)=>CC(p,I,m),invertBatch:I=>ME(p,I),add:s,sub:a,mul:c,sqr:l,addN:s,subN:a,mulN:c,sqrN:l,div:(I,m)=>p.mul(I,typeof m=="bigint"?t.inv(t.create(m)):p.inv(m)),inv:({c0:I,c1:m})=>{let x=t.inv(t.create(I*I+m*m));return{c0:t.mul(x,t.create(I)),c1:t.mul(x,t.create(-m))}},sqrt:I=>{if(n.Fp2sqrt)return n.Fp2sqrt(I);let{c0:m,c1:x}=I;if(t.is0(x))return PC(t,m)===1?p.create({c0:t.sqrt(m),c1:t.ZERO}):p.create({c0:t.ZERO,c1:t.sqrt(t.div(m,r))});let y=t.sqrt(t.sub(t.sqr(m),t.mul(t.sqr(x),r))),A=t.mul(t.add(y,m),i);PC(t,A)===-1&&(A=t.sub(A,y));let F=t.sqrt(A),N=p.create({c0:F,c1:t.div(t.mul(x,i),F)});if(!p.eql(p.sqr(N),I))throw new Error("Cannot find square root");let M=N,T=p.neg(M),{re:Q,im:_}=p.reim(M),{re:S,im:g}=p.reim(T);return _>g||_===g&&Q>S?M:T},isOdd:I=>{let{re:m,im:x}=p.reim(I),y=m%dd,A=m===f$,L=x%dd;return BigInt(y||A&&L)==My},fromBytes(I){if(I.length!==p.BYTES)throw new Error("fromBytes invalid length="+I.length);return{c0:t.fromBytes(I.subarray(0,t.BYTES)),c1:t.fromBytes(I.subarray(t.BYTES))}},toBytes:({c0:I,c1:m})=>so(t.toBytes(I),t.toBytes(m)),cmov:({c0:I,c1:m},{c0:x,c1:y},A)=>({c0:t.cmov(I,x,A),c1:t.cmov(m,y,A)}),reim:({c0:I,c1:m})=>({re:I,im:m}),mulByNonresidue:({c0:I,c1:m})=>p.mul({c0:I,c1:m},f),mulByB:n.Fp2mulByB,fromBigTuple:u,frobeniusMap:({c0:I,c1:m},x)=>({c0:I,c1:t.mul(m,o[x%2])})},E=({c0:I,c1:m,c2:x},{c0:y,c1:A,c2:L})=>({c0:p.add(I,y),c1:p.add(m,A),c2:p.add(x,L)}),b=({c0:I,c1:m,c2:x},{c0:y,c1:A,c2:L})=>({c0:p.sub(I,y),c1:p.sub(m,A),c2:p.sub(x,L)}),C=({c0:I,c1:m,c2:x},y)=>{if(typeof y=="bigint")return{c0:p.mul(I,y),c1:p.mul(m,y),c2:p.mul(x,y)};let{c0:A,c1:L,c2:F}=y,N=p.mul(I,A),M=p.mul(m,L),T=p.mul(x,F);return{c0:p.add(N,p.mulByNonresidue(p.sub(p.mul(p.add(m,x),p.add(L,F)),p.add(M,T)))),c1:p.add(p.sub(p.mul(p.add(I,m),p.add(A,L)),p.add(N,M)),p.mulByNonresidue(T)),c2:p.sub(p.add(M,p.mul(p.add(I,x),p.add(A,F))),p.add(N,T))}},B=({c0:I,c1:m,c2:x})=>{let y=p.sqr(I),A=p.mul(p.mul(I,m),dd),L=p.mul(p.mul(m,x),dd),F=p.sqr(x);return{c0:p.add(p.mulByNonresidue(L),y),c1:p.add(p.mulByNonresidue(F),A),c2:p.sub(p.sub(p.add(p.add(A,p.sqr(p.add(p.sub(I,m),x))),L),y),F)}},[J,G]=DM(p,f,t.ORDER,6,2,3),U={ORDER:p.ORDER,isLE:p.isLE,BITS:3*p.BITS,BYTES:3*p.BYTES,MASK:O0(3*p.BITS),ZERO:{c0:p.ZERO,c1:p.ZERO,c2:p.ZERO},ONE:{c0:p.ONE,c1:p.ZERO,c2:p.ZERO},create:I=>I,isValid:({c0:I,c1:m,c2:x})=>p.isValid(I)&&p.isValid(m)&&p.isValid(x),is0:({c0:I,c1:m,c2:x})=>p.is0(I)&&p.is0(m)&&p.is0(x),isValidNot0:I=>!U.is0(I)&&U.isValid(I),neg:({c0:I,c1:m,c2:x})=>({c0:p.neg(I),c1:p.neg(m),c2:p.neg(x)}),eql:({c0:I,c1:m,c2:x},{c0:y,c1:A,c2:L})=>p.eql(I,y)&&p.eql(m,A)&&p.eql(x,L),sqrt:li,div:(I,m)=>U.mul(I,typeof m=="bigint"?t.inv(t.create(m)):U.inv(m)),pow:(I,m)=>CC(U,I,m),invertBatch:I=>ME(U,I),add:E,sub:b,mul:C,sqr:B,addN:E,subN:b,mulN:C,sqrN:B,inv:({c0:I,c1:m,c2:x})=>{let y=p.sub(p.sqr(I),p.mulByNonresidue(p.mul(x,m))),A=p.sub(p.mulByNonresidue(p.sqr(x)),p.mul(I,m)),L=p.sub(p.sqr(m),p.mul(I,x)),F=p.inv(p.add(p.mulByNonresidue(p.add(p.mul(x,A),p.mul(m,L))),p.mul(I,y)));return{c0:p.mul(F,y),c1:p.mul(F,A),c2:p.mul(F,L)}},fromBytes:I=>{if(I.length!==U.BYTES)throw new Error("fromBytes invalid length="+I.length);return{c0:p.fromBytes(I.subarray(0,p.BYTES)),c1:p.fromBytes(I.subarray(p.BYTES,2*p.BYTES)),c2:p.fromBytes(I.subarray(2*p.BYTES))}},toBytes:({c0:I,c1:m,c2:x})=>so(p.toBytes(I),p.toBytes(m),p.toBytes(x)),cmov:({c0:I,c1:m,c2:x},{c0:y,c1:A,c2:L},F)=>({c0:p.cmov(I,y,F),c1:p.cmov(m,A,F),c2:p.cmov(x,L,F)}),fromBigSix:I=>{if(!Array.isArray(I)||I.length!==6)throw new Error("invalid Fp6 usage");return{c0:p.fromBigTuple(I.slice(0,2)),c1:p.fromBigTuple(I.slice(2,4)),c2:p.fromBigTuple(I.slice(4,6))}},frobeniusMap:({c0:I,c1:m,c2:x},y)=>({c0:p.frobeniusMap(I,y),c1:p.mul(p.frobeniusMap(m,y),J[y%6]),c2:p.mul(p.frobeniusMap(x,y),G[y%6])}),mulByFp2:({c0:I,c1:m,c2:x},y)=>({c0:p.mul(I,y),c1:p.mul(m,y),c2:p.mul(x,y)}),mulByNonresidue:({c0:I,c1:m,c2:x})=>({c0:p.mulByNonresidue(x),c1:I,c2:m}),mul1:({c0:I,c1:m,c2:x},y)=>({c0:p.mulByNonresidue(p.mul(x,y)),c1:p.mul(I,y),c2:p.mul(m,y)}),mul01({c0:I,c1:m,c2:x},y,A){let L=p.mul(I,y),F=p.mul(m,A);return{c0:p.add(p.mulByNonresidue(p.sub(p.mul(p.add(m,x),A),F)),L),c1:p.sub(p.sub(p.mul(p.add(y,A),p.add(I,m)),L),F),c2:p.add(p.sub(p.mul(p.add(I,x),y),L),F)}}},O=DM(p,f,t.ORDER,12,1,6)[0],v=({c0:I,c1:m},{c0:x,c1:y})=>({c0:U.add(I,x),c1:U.add(m,y)}),D=({c0:I,c1:m},{c0:x,c1:y})=>({c0:U.sub(I,x),c1:U.sub(m,y)}),z=({c0:I,c1:m},x)=>{if(typeof x=="bigint")return{c0:U.mul(I,x),c1:U.mul(m,x)};let{c0:y,c1:A}=x,L=U.mul(I,y),F=U.mul(m,A);return{c0:U.add(L,U.mulByNonresidue(F)),c1:U.sub(U.mul(U.add(I,m),U.add(y,A)),U.add(L,F))}},j=({c0:I,c1:m})=>{let x=U.mul(I,m);return{c0:U.sub(U.sub(U.mul(U.add(U.mulByNonresidue(m),I),U.add(I,m)),x),U.mulByNonresidue(x)),c1:U.add(x,x)}};function Y(I,m){let x=p.sqr(I),y=p.sqr(m);return{first:p.add(p.mulByNonresidue(y),x),second:p.sub(p.sub(p.sqr(p.add(I,m)),x),y)}}let H={ORDER:p.ORDER,isLE:U.isLE,BITS:2*U.BITS,BYTES:2*U.BYTES,MASK:O0(2*U.BITS),ZERO:{c0:U.ZERO,c1:U.ZERO},ONE:{c0:U.ONE,c1:U.ZERO},create:I=>I,isValid:({c0:I,c1:m})=>U.isValid(I)&&U.isValid(m),is0:({c0:I,c1:m})=>U.is0(I)&&U.is0(m),isValidNot0:I=>!H.is0(I)&&H.isValid(I),neg:({c0:I,c1:m})=>({c0:U.neg(I),c1:U.neg(m)}),eql:({c0:I,c1:m},{c0:x,c1:y})=>U.eql(I,x)&&U.eql(m,y),sqrt:li,inv:({c0:I,c1:m})=>{let x=U.inv(U.sub(U.sqr(I),U.mulByNonresidue(U.sqr(m))));return{c0:U.mul(I,x),c1:U.neg(U.mul(m,x))}},div:(I,m)=>H.mul(I,typeof m=="bigint"?t.inv(t.create(m)):H.inv(m)),pow:(I,m)=>CC(H,I,m),invertBatch:I=>ME(H,I),add:v,sub:D,mul:z,sqr:j,addN:v,subN:D,mulN:z,sqrN:j,fromBytes:I=>{if(I.length!==H.BYTES)throw new Error("fromBytes invalid length="+I.length);return{c0:U.fromBytes(I.subarray(0,U.BYTES)),c1:U.fromBytes(I.subarray(U.BYTES))}},toBytes:({c0:I,c1:m})=>so(U.toBytes(I),U.toBytes(m)),cmov:({c0:I,c1:m},{c0:x,c1:y},A)=>({c0:U.cmov(I,x,A),c1:U.cmov(m,y,A)}),fromBigTwelve:I=>({c0:U.fromBigSix(I.slice(0,6)),c1:U.fromBigSix(I.slice(6,12))}),frobeniusMap(I,m){let{c0:x,c1:y,c2:A}=U.frobeniusMap(I.c1,m),L=O[m%12];return{c0:U.frobeniusMap(I.c0,m),c1:U.create({c0:p.mul(x,L),c1:p.mul(y,L),c2:p.mul(A,L)})}},mulByFp2:({c0:I,c1:m},x)=>({c0:U.mulByFp2(I,x),c1:U.mulByFp2(m,x)}),conjugate:({c0:I,c1:m})=>({c0:I,c1:U.neg(m)}),mul014:({c0:I,c1:m},x,y,A)=>{let L=U.mul01(I,x,y),F=U.mul1(m,A);return{c0:U.add(U.mulByNonresidue(F),L),c1:U.sub(U.sub(U.mul01(U.add(m,I),x,p.add(y,A)),L),F)}},mul034:({c0:I,c1:m},x,y,A)=>{let L=U.create({c0:p.mul(I.c0,x),c1:p.mul(I.c1,x),c2:p.mul(I.c2,x)}),F=U.mul01(m,y,A),N=U.mul01(U.add(I,m),p.add(x,y),A);return{c0:U.add(U.mulByNonresidue(F),L),c1:U.sub(N,U.add(L,F))}},_cyclotomicSquare:n.Fp12cyclotomicSquare,_cyclotomicExp:n.Fp12cyclotomicExp,finalExponentiate:n.Fp12finalExponentiate};return{Fp:t,Fp2:p,Fp6:U,Fp12:H,Fp4Square:Y}}var ILe=BigInt(0),HM=BigInt(1),ah=BigInt(2),ALe=BigInt(3),H$=BigInt(6),UC=BigInt("4965661367192848881"),xLe=kE(UC),vLe=H$*UC**ah,GC={p:BigInt("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"),n:BigInt("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"),h:HM,a:ILe,b:ALe,Gx:HM,Gy:BigInt(2)},p$=JE(GC.n),J$={c0:BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),c1:BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")},{Fp:GE,Fp2:Fn,Fp6:JM,Fp4Square:TM,Fp12:Rn}=ELe({ORDER:GC.p,FP2_NONRESIDUE:[BigInt(9),HM],Fp2mulByB:n=>Fn.mul(n,J$),Fp12cyclotomicSquare:({c0:n,c1:e})=>{let{c0:t,c1:r,c2:i}=n,{c0:o,c1:s,c2:a}=e,{first:c,second:l}=TM(t,s),{first:u,second:d}=TM(o,i),{first:h,second:f}=TM(r,a),p=Fn.mulByNonresidue(f);return{c0:JM.create({c0:Fn.add(Fn.mul(Fn.sub(c,t),ah),c),c1:Fn.add(Fn.mul(Fn.sub(u,r),ah),u),c2:Fn.add(Fn.mul(Fn.sub(h,i),ah),h)}),c1:JM.create({c0:Fn.add(Fn.mul(Fn.add(p,o),ah),p),c1:Fn.add(Fn.mul(Fn.add(l,s),ah),l),c2:Fn.add(Fn.mul(Fn.add(d,a),ah),d)})}},Fp12cyclotomicExp(n,e){let t=Rn.ONE;for(let r=xLe-1;r>=0;r--)t=Rn._cyclotomicSquare(t),q8e(e,r)&&(t=Rn.mul(t,n));return t},Fp12finalExponentiate:n=>{let e=u=>Rn.conjugate(Rn._cyclotomicExp(u,UC)),t=Rn.mul(Rn.conjugate(n),Rn.inv(n)),r=Rn.mul(Rn.frobeniusMap(t,2),t),i=Rn._cyclotomicSquare(e(r)),o=Rn.mul(Rn._cyclotomicSquare(i),i),s=e(o),a=e(Rn._cyclotomicSquare(s)),c=Rn.mul(Rn.mul(Rn.conjugate(a),s),Rn.conjugate(o)),l=Rn.mul(c,i);return Rn.mul(Rn.frobeniusMap(Rn.mul(Rn.conjugate(r),l),3),Rn.mul(Rn.frobeniusMap(c,2),Rn.mul(Rn.frobeniusMap(l,1),Rn.mul(Rn.mul(c,s),r))))}}),{G2psi:SLe,psi:m$}=bLe(GE,Fn,Fn.NONRESIDUE),BM=Object.freeze({DST:"BN254G2_XMD:SHA-256_SVDW_RO_",encodeDST:"BN254G2_XMD:SHA-256_SVDW_RO_",p:GE.ORDER,m:2,k:128,expand:"xmd",hash:_M}),CLe=(n,e,t,r,i,o)=>{let s=m$(r,i);({Rx:n,Ry:e,Rz:t}=o(n,e,t,s[0],s[1]));let a=m$(s[0],s[1]);o(n,e,t,a[0],Fn.neg(a[1]))},LLe={p:Fn.ORDER,n:GC.n,h:BigInt("0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d"),a:Fn.ZERO,b:J$,Gx:Fn.fromBigTuple([BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")]),Gy:Fn.fromBigTuple([BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")])},F0=wLe({fields:{Fp:GE,Fp2:Fn,Fp6:JM,Fp12:Rn,Fr:p$},G1:{...GC,Fp:GE,htfDefaults:{...BM,m:1,DST:"BN254G2_XMD:SHA-256_SVDW_RO_"},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:li,fromBytes:li,toBytes:li,ShortSignature:{fromBytes:li,fromHex:li,toBytes:li,toRawBytes:li,toHex:li}},G2:{...LLe,Fp:Fn,hEff:BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),htfDefaults:{...BM},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(n,e)=>e.multiplyUnsafe(vLe).equals(SLe(n,e)),mapToCurve:li,fromBytes:li,toBytes:li,Signature:{fromBytes:li,fromHex:li,toBytes:li,toRawBytes:li,toHex:li}},params:{ateLoopSize:UC*H$+ah,r:p$.ORDER,xNegative:!1,twistType:"divisive"},htfDefaults:BM,hash:_M,postPrecompute:CLe});mLe({a:BigInt(0),b:BigInt(3),Fp:GE,n:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),Gx:BigInt(1),Gy:BigInt(2),h:BigInt(1),hash:_M});var KC="groth16",RLe="auth",DLe="authV2",TLe="authV3",BLe="authV3-8-32",PLe=new TextDecoder,g$=BigInt(0),y$=F0.fields.Fp2,w$=F0.fields.Fp12;async function rO(n,e,t){let r=await T8e(t),i=new TextDecoder().decode(n),o=JSON.parse(i),s=await r.calculateWTNSBin(o,0),{proof:a,publicSignals:c}=await EC.prove(e,s);return{proof:a,pub_signals:c}}var[qM,kLe]=[F0.G1.ProjectivePoint,F0.G2.ProjectivePoint],vC=([n,e])=>qM.fromAffine({x:BigInt(n),y:BigInt(e)}),SC=([[n,e],[t,r]])=>kLe.fromAffine({x:y$.fromBigTuple([BigInt(n),BigInt(e)]),y:y$.fromBigTuple([BigInt(t),BigInt(r)])});async function iO(n,e,t,r){if(r(e.pub_signals).challenge!==yI(n))throw new Error("challenge is not equal to message hash");let o=JSON.parse(PLe.decode(t));return oO(e,o)}function oO(n,e){if(!e.IC)throw new Error("verification file doesn't exist for circuit");let{proof:t,pub_signals:r}=n;if(r.length+1!==e.IC.length)throw new Error(`Invalid number of public signals, expected ${e.IC.length-1} but got ${r.length}`);let i=qM.ZERO;for(let s=0;s<r.length;s++){if(BigInt(r[s])<g$||BigInt(r[s])>=F0.G1.CURVE.n)throw new Error(`Input value is not in the field ${F0.G1.CURVE.n}`);if(BigInt(r[s])!==g$){let[a,c]=e.IC[s+1].map(BigInt);i=i.add(qM.fromAffine({x:a,y:c}).multiply(BigInt(r[s])))}}i=i.add(vC(e.IC[0]));let o=F0.pairingBatch([{g1:vC(t.pi_a).negate(),g2:SC(t.pi_b)},{g1:i,g2:SC(e.vk_gamma_2)},{g1:vC(t.pi_c),g2:SC(e.vk_delta_2)},{g1:vC(e.vk_alpha_1),g2:SC(e.vk_beta_2)}]);return w$.eql(o,w$.ONE)}var VM=class{methodAlg;constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}unmarshall(e){let t={};if(e.length!=3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return t.challenge=BigInt(e[0]),t.userState=BigInt(e[1]),t.userId=$e.fromBigInt(BigInt(e[2])),t}async verify(e,t,r){return iO(e,t,r,this.unmarshall)}prove(e,t,r){return rO(e,t,r)}},QM=new VM(new fd(KC,RLe)),zM=class n{methodAlg;static curveName="bn128";constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}async verify(e,t,r){return iO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await rO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await DE(n.curveName)).terminate()}unmarshall(e){if(e.length!==3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return{userID:$e.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},YM=new zM(new fd(KC,DLe)),MC=class n{methodAlg;static curveName="bn128";constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}async verify(e,t,r){return iO(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await rO(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await DE(n.curveName)).terminate()}unmarshall(e){if(e.length!==3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return{userID:$e.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:be.fromString(e[2])}}},jM=new MC(new fd(KC,TLe)),WM=new MC(new fd(KC,BLe));KE(QM.methodAlg,()=>QM);KE(YM.methodAlg,()=>YM);KE(jM.methodAlg,()=>jM);KE(WM.methodAlg,()=>WM);var N0={registerProvingMethod:KE,getProvingMethod:I$,provingMethodGroth16AuthInstance:QM,provingMethodGroth16AuthV2Instance:YM,provingMethodGroth16AuthV3Instance:jM,provingMethodGroth16AuthV3_8_32Instance:WM};var q$="unknown circuit ID. can't verify msg sender",HC="sender of message is not used for jwz token creation",V$="message was packed with unsupported circuit",Q$="message proof is invalid",z$="message state verification failed",Y$="unknown proving method algorithm";var{getProvingMethod:MLe}=N0,sO=class{constructor(e){this.dataPrepareFunc=e}prepare(e,t,r){return this.dataPrepareFunc(e,t,r)}},aO=class{constructor(e){this.stateVerificationFunc=e}verify(e,t,r){return this.stateVerificationFunc(e,t,r)}},cO=class{constructor(e,t,r={acceptedStateTransitionDelay:L5}){this.provingParamsMap=e;this.verificationParamsMap=t;this._opts=r;let i=Array.from(this.provingParamsMap.keys()).map(s=>s.split(":")[1]),o=Array.from(this.verificationParamsMap.keys()).map(s=>s.split(":")[1]);this.supportedCircuitIds=[...new Set([...i,...o])]}supportedProtocolVersions=["iden3comm/v1"];supportedAlgorithms=["groth16"];supportedCircuitIds;packMessage(e,t){return this.pack(Fe.encode(JSON.stringify(e)),t)}async pack(e,t){let r=await MLe(t.provingMethodAlg),i=this.provingParamsMap.get(t.provingMethodAlg.toString());if(!i)throw new Error(Y$);let o=new ch(r,dt.decode(e),(a,c)=>i?.dataPreparer?.prepare(a,t.senderDID,c));o.setHeader(Ha.Type,"application/iden3-zkp-json");let s=await o.prove(i.provingKey,i.wasm);return Fe.encode(s)}async unpack(e){let t=await ch.parse(dt.decode(e)),r=new fd(t.alg,t.circuitId),i=this.verificationParamsMap.get(r.toString());if(!i?.key)throw new Error(V$);if(!await t.verify(i?.key))throw new Error(Q$);if(!await i?.verificationFn?.verify(t.circuitId,t.zkProof.pub_signals,this._opts))throw new Error(z$);let a=JSON.parse(t.getPayload());return OLe(t,a),a}mediaType(){return"application/iden3-zkp-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(",")};circuitIds=${this.supportedCircuitIds.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=Ss(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;let s=this.supportedCircuitIds,a=!i?.length||i.some(u=>s.includes(u)),c=this.supportedAlgorithms;return(!o?.length||o.some(u=>c.includes(u)))&&a}},OLe=async(n,e)=>{switch(n.circuitId){case"authV2":case"authV3-8-32":case"authV3":{if(!e.from)throw new Error(HC);let t=(n.circuitId==="authV2"?new _s:new C0).pubSignalsUnmarshal(Fe.encode(JSON.stringify(n.zkProof.pub_signals))),r=Se.parseFromId(t.userID),i=await n.getMessageHash();if(vt.bytesToInt(i.reverse())!==t.challenge)throw new Error(HC);if(e.from!==r.string())throw new Error(HC)}break;default:throw new Error(q$)}};var j$=(r=>(r.Pending="pending",r.Completed="completed",r.Rejected="rejected",r))(j$||{});var lO=(t=>(t.AUTHV2="authV2",t.ETH_IDENTITY="ethIdentity",t))(lO||{});var W$=(e=>(e.FeatureType="feature-type",e))(W$||{}),Z$=(i=>(i.Accept="accept",i.Protocol="protocol",i.GoalCode="goal-code",i.Header="header",i))(Z$||{});var Nl=N0.provingMethodGroth16AuthV2Instance.methodAlg,Fi=class{nextMessageHandler;setNext(e){return this.nextMessageHandler=e,e}async handle(e,t){return t.allowExpiredMessages||vr(e),this.nextMessageHandler?this.nextMessageHandler.handle(e,t):Promise.reject("Message handler not provided or message not supported")}},uO=class{constructor(e){this._params=e;this.registerHandlers(e.messageHandlers)}messageHandler;registerHandlers(e){if(!e.length)return;let[t,...r]=e,i=t;for(let o of r){let s=i;for(;s.nextMessageHandler;)s=s.nextMessageHandler;s.setNext(o)}this.messageHandler?this.messageHandler.setNext(t):this.messageHandler=t}async handleMessage(e,t){let{unpackedMediaType:r,unpackedMessage:i}=await this._params.packageManager.unpack(e);if(!this.messageHandler)return Promise.reject(new Error("Message handler not provided"));r==="application/iden3-zkp-json"&&(t.messageProvingMethodAlg=await Oc(e));let o=await this.messageHandler.handle(i,t);if(!o)return null;let s={},a=t?.senderDid;return r==="application/iden3-zkp-json"&&a?(s={senderDID:a,provingMethodAlg:await Oc(e)},this._params.packageManager.packMessage(r,o,s)):this._params.packageManager.packMessage("application/iden3comm-plain-json",o,s)}};async function Oc(n){try{let e=dt.decode(n);return(await ch.parse(e)).method.methodAlg}catch{return Nl}}var FLe=n=>n.reduce((e,t)=>{let r=t.query.groupId;if(!r)return e;let i=e.get(r);if(!i){let s=Uc(12),c=new DataView(s.buffer).getUint32(0);return e.set(r,{query:t.query,linkNonce:c}),e}let o=H8(i.query.credentialSubject,t.query.credentialSubject);return e.set(r,{...i,query:{skipClaimRevocationCheck:i.query.skipClaimRevocationCheck||t.query.skipClaimRevocationCheck,...i.query,credentialSubject:o}}),e},new Map),Ny=async(n,e,t,r,i)=>{let o=e??[],s=FLe(o),a=new Map,c=[];for(let l of o){let u;try{if(!i.supportedCircuits.includes(l.circuitId)){if(l.optional)continue;throw new Error(`Circuit ${l.circuitId} is not allowed`)}let h=l.query,f=h.groupId,p=s.get(f);if(f){if(!p)throw new Error(`Invalid group id ${h.groupId}`);let b=p.query;if(!a.has(f)){let C=await r.findCredentialByProofQuery(n,p.query);if(!C.cred){if(l.optional)continue;throw new Error(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+`${JSON.stringify(b)}`)}a.set(f,C)}}let E=a.get(f);u=await r.generateProof(l,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h.skipClaimRevocationCheck,credential:E?.cred,credentialRevocationStatus:E?.revStatus,linkNonce:p?.linkNonce?BigInt(p.linkNonce):void 0})}catch(d){let h=[qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,qe.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,qe.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED];if(d instanceof Error&&(h.includes(d.message)||d.message.includes(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY))&&l.optional)continue;throw d}c.push(u)}return c},dO=async(n,e,t)=>{switch(t.acceptProfile||(t.acceptProfile=hE),t.acceptProfile.env){case"application/iden3-zkp-json":if(!t.acceptProfile.circuits)throw new Error("Circuit not specified in accept profile");for(let r of t.acceptProfile.circuits){if(!t.supportedCircuits.includes(r))throw new Error(`Circuit ${r} is not supported`);if(!t.senderAddress)throw new Error("Sender address is not provided");let i=X$(t.senderAddress,t.zkpResponses),o=await e.generateAuthProof(r,n,{challenge:i});return{authProof:{authMethod:"authV2",zkp:o}}}throw new Error("Auth method is not supported");case"application/iden3comm-signed-json":if(!t.acceptProfile.alg||t.acceptProfile.alg.length===0)throw new Error("Algorithm not specified");if(t.acceptProfile.alg[0]==="ES256K-R")return{authProof:{authMethod:"ethIdentity",userDid:n}};throw new Error(`Algorithm ${t.acceptProfile.alg[0]} not supported`);default:throw new Error("Accept env not supported")}},qE=n=>{let e=n.id,t=n.pub_signals,r="0x";if(t.length===0)return{requestId:e,zkProofEncoded:r,metadata:r};let i=L0(n.proof),o=QS(t,i.a,i.b,i.c);return{requestId:e,zkProofEncoded:o,metadata:r}},X$=(n,e)=>{let t=e.map(r=>{let i=qE(r);return{requestId:i.requestId,proof:i.zkProofEncoded,metadata:i.metadata}});return BigInt(An.keccak256(new An.AbiCoder().encode(["address","(uint256 requestId,bytes proof,bytes metadata)[]"],[n,t])))&BigInt("0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")},NLe=n=>new An.AbiCoder().encode(["tuple(string key,bytes value)[]"],[n]),vr=n=>{if(n?.expires_time&&n.expires_time<Ct(new Date))throw new Error("Message expired")},na=(n,e,t)=>{if(n==="application/iden3comm-signed-json"||n==="application/iden3comm-encrypted-json"){if(!e)throw new Error(`packer options are required for ${n}`);return e}if(n==="application/iden3comm-plain-json")return{};if(n==="application/iden3-zkp-json"){let r={provingMethodAlg:e?.provingMethodAlg||t?.provingMethodAlg||Nl,senderDID:e?.senderDID||t?.senderDID};if(!r.senderDID)throw new Error("senderDID is required for ZKPMessage");return r}throw new Error(`unsupported media type ${n}`)};function ULe(n,e,t,r){return _$(n,"",e,t,r)}function _$(n,e,t,r,i){let o=Ft();return{id:o,thid:o,from:t,typ:"application/iden3comm-plain-json",type:ut.AUTHORIZATION_REQUEST_MESSAGE_TYPE,body:{accept:i?.accept,reason:n,message:e,callbackUrl:r,scope:i?.scope??[]},created_time:Ct(new Date),expires_time:i?.expires_time?Ct(i.expires_time):void 0,attachments:i?.attachments}}var fO=class extends Fi{constructor(t,r){super();this._packerMgr=t;this._proofService=r}_supportedCircuits=["credentialAtomicQueryV3-beta.1","credentialAtomicQuerySigV2","credentialAtomicQueryMTPV2","linkedMultiQuery10-beta.1"];handle(t,r){switch(t.type){case ut.AUTHORIZATION_REQUEST_MESSAGE_TYPE:return this.handleAuthRequest(t,r);case ut.AUTHORIZATION_RESPONSE_MESSAGE_TYPE:return this.handleAuthResponse(t,r);default:return super.handle(t,r)}}async parseAuthorizationRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==ut.AUTHORIZATION_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i.body.scope=i.body.scope||[],i}async handleAuthRequest(t,r){if(t.type!==ut.AUTHORIZATION_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for authorization request");let i=t.to?Se.parse(t.to):r.senderDid,o=Ft();if(!t.from)throw new Error("auth request should contain from field");let s=ut.AUTHORIZATION_RESPONSE_MESSAGE_TYPE,a=this.getSupportedMediaTypeByProfile(r,t.body.accept),c=Se.parse(t.from),l=await Ny(i,t?.body.scope,c,this._proofService,{mediaType:a,supportedCircuits:this._supportedCircuits});return{id:o,typ:a,type:s,thid:t.thid??o,body:{message:t?.body?.message,scope:l},from:i.string(),to:t.from}}async handleAuthorizationRequest(t,r,i){let o=await this.parseAuthorizationRequest(r);i?.allowExpiredMessages||vr(o),i||(i={mediaType:"application/iden3-zkp-json"});let s=await this.handleAuthRequest(o,{senderDid:t,mediaType:i.mediaType}),a=Fe.encode(JSON.stringify(s)),c=na(i.mediaType,i.packerOptions,{provingMethodAlg:this.getDefaultProvingMethodAlg(i.preferredAuthProvingMethod,o.body.accept),senderDID:t}),l=dt.decode(await this._packerMgr.pack(i.mediaType,a,c));return{authRequest:o,authResponse:s,token:l}}async handleAuthResponse(t,r){let i=r.request;if(t.type!==ut.AUTHORIZATION_RESPONSE_MESSAGE_TYPE)throw new Error("Invalid message type for authorization response");if((i.body.message??"")!==(t.body.message??""))throw new Error("message for signing from request is not presented in response");if(i.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${i.from}, given ${t.to}`);this.verifyAuthRequest(i);let o=i.body.scope||[],s=t.body.scope||[];if(!t.from)throw new Error("proof response doesn't contain from field");let a=new Map;for(let c of o){let l=c.query.groupId,u=s.find(E=>E.id.toString()===c.id.toString());if(!u){if(c.optional)continue;throw new Error(`proof is not given for requestId ${c.id}`)}let d=u.circuitId;if(d!==c.circuitId)throw new Error(`proof is not given for requested circuit expected: ${c.circuitId}, given ${d}`);let h=c.params??{};h.verifierDid=Se.parse(i.from);let f=[r.acceptedProofGenerationDelay,r.acceptedStateTransitionDelay].some(E=>E!==void 0)?{acceptedProofGenerationDelay:r.acceptedProofGenerationDelay,acceptedStateTransitionDelay:r.acceptedStateTransitionDelay}:void 0,{linkID:p}=await this._proofService.verifyZKPResponse(u,{query:c.query,sender:t.from,params:h,opts:f});p&&l&&a.set(l,[...a.get(l)??[],{linkID:p,requestId:u.id}])}for(let[c,l]of a.entries())if(l.some(u=>u.linkID!==l[0].linkID))throw new Error(`Link id validation failed for group ${c}, request linkID to requestIds info: ${JSON.stringify(l)}`);return t}async handleAuthorizationResponse(t,r,i){i?.allowExpiredMessages||vr(t);let o=await this.handleAuthResponse(t,{request:r,acceptedStateTransitionDelay:i?.acceptedStateTransitionDelay,acceptedProofGenerationDelay:i?.acceptedProofGenerationDelay});return{request:r,response:o}}verifyAuthRequest(t){let r={},i=t.body.scope||[];for(let o of i){let s=o.query.groupId;if(s){let a=r[s]??[];for(let c of a){if(c.query.type!==o.query.type)throw new Error("all requests in the group should have the same type");if(c.query.context!==o.query.context)throw new Error("all requests in the group should have the same context");let l=o.query.allowedIssuers,u=c.query.allowedIssuers;if(!(l.includes("*")||l.every(d=>u.includes(d))))throw new Error("all requests in the group should have the same issuer")}r[s]=[...r[s]??[],o]}}}getSupportedMediaTypeByProfile(t,r){let i;if(!r?.length)return t.mediaType||"application/iden3-zkp-json";let o=[];for(let s of r){let{env:a}=Ss(s);this._packerMgr.isProfileSupported(a,s)&&o.push(a)}if(!o.length)throw new Error("no packer with profile which meets `accept` header requirements");return i=o.includes("application/iden3-zkp-json")?"application/iden3-zkp-json":o[0],t.mediaType&&o.includes(t.mediaType)&&(i=t.mediaType),i}getDefaultProvingMethodAlg(t,r){if(t&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",pE(t))&&(!r?.length||mE(r,t)))return t;if(r?.length){let i=N0.provingMethodGroth16AuthV3_8_32Instance.methodAlg;if(mE(r,i)&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",pE(i)))return i;let o=N0.provingMethodGroth16AuthV3Instance.methodAlg;if(mE(r,o)&&this._packerMgr.isProfileSupported("application/iden3-zkp-json",pE(o)))return o}return Nl}};var $$=[{inputs:[],name:"MAX_SMT_DEPTH",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"key",type:"uint256"}],name:"getNode",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatus",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatusByIdAndState",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256[][]",name:"nodes",type:"uint256[][]"}],name:"saveNodes",outputs:[],stateMutability:"nonpayable",type:"function"}];var VE=class n{constructor(e,t,r){this._config=e;this._signer=r;this._provider=new jt(e.url);let i=new Ln(t,$$,this._provider);this._signer&&(this._signer=this._signer.connect(this._provider),i=i.connect(this._signer)),this._contract=i,this._transactionService=new $s(this._provider)}_contract;_provider;_transactionService;async getRevocationStatusByIdAndState(e,t,r){let i=await this._contract.getRevocationStatusByIdAndState(e,t,r),o=n.convertIssuerInfo(i.issuer),s=n.convertSmtProofToProof(i.mtp);return{issuer:o,mtp:s}}async getRevocationStatus(e,t){let r=await this._contract.getRevocationStatus(e,t),i=n.convertIssuerInfo(r.issuer),o=n.convertSmtProofToProof(r.mtp);return{issuer:i,mtp:o}}async saveNodes(e){if(!this._signer)throw new Error("No signer provided");let t=await this._provider.getFeeData(),r=this._config.maxFeePerGas?BigInt(this._config.maxFeePerGas):t.maxFeePerGas,i=this._config.maxPriorityFeePerGas?BigInt(this._config.maxPriorityFeePerGas):t.maxPriorityFeePerGas,o=await this._contract.saveNodes.estimateGas(e),s=await this._contract.saveNodes.populateTransaction(e),a={to:s.to,data:s.data,gasLimit:o,maxFeePerGas:r,maxPriorityFeePerGas:i},{txnReceipt:c}=await this._transactionService.sendTransactionRequest(this._signer,a);return c}static convertIssuerInfo(e){let[t,r,i,o]=e.map(s=>be.fromBigInt(s).hex());return{state:t,claimsTreeRoot:r,revocationTreeRoot:i,rootOfRoots:o}}static convertSmtProofToProof(e){let t,r=e.siblings?.map(i=>i.toString());return e.auxExistence&&(t={key:e.auxIndex.toString(),value:e.auxValue.toString()}),Bt.fromJSON({existence:e.existence,node_aux:t,siblings:r})}};function KLe(n){return typeof n=="object"&&n!==null&&"errorArgs"in n&&Array.isArray(n.errorArgs)}function HLe(n){return(KLe(n)?n.errorArgs[0]:void 0)||(n instanceof Error?n.message:"")}function Uy(n,e){return HLe(n).includes(e)}function QE(n){return Uy(n,qe.ERRORS.IDENTITY_DOES_NOT_EXIST)||Uy(n,qe.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR)}function hO(n){return Uy(n,qe.ERRORS.STATE_DOES_NOT_EXIST)||Uy(n,qe.ERRORS.STATE_DOES_NOT_EXIST_CUSTOM_ERROR)}function pO(n){return Uy(n,qe.ERRORS.ROOT_DOES_NOT_EXIST)||Uy(n,qe.ERRORS.ROOT_DOES_NOT_EXIST_CUSTOM_ERROR)}var mO=class{constructor(e,t){this._configs=e;this._stateStorage=new zE(e,t?.stateStorageOptions)}_stateStorage;async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");return this.getRevocationOnChain(e,t.issuerDID)}async getRevocationOnChain(e,t){let{contractAddress:r,chainId:i,revocationNonce:o,stateHex:s}=this.extractCredentialStatusInfo(e);if(o!==e.revocationNonce)throw new Error("revocationNonce does not match");let a=Se.idFromDID(t),c;try{let h=await this._stateStorage.getLatestStateById(a.bigInt());if(!h.state)throw new Error("state contract returned empty state");c=h.state}catch(h){if(!QE(h))throw h;if(!s)throw new Error("latest state not found and state parameter is not present in credentialStatus.id");let f=be.fromHex(s).bigInt();if(!tl(t,f))throw new Error(`latest state not found and state parameter ${s} is not genesis state`);c=f}let l=Se.idFromDID(t);return await this._getOnChainRevocationStorageForIssuer(i,r).getRevocationStatusByIdAndState(l.bigInt(),c,o)}extractCredentialStatusInfo(e){if(!e.id)throw new Error("credentialStatus id is empty");if(e.id.split("/").length!==2)throw new Error("invalid credentialStatus id");let r=new URL(e.id),i=r.searchParams.get("state")||"",o=r.searchParams.get("contractAddress");if(!o)throw new Error("contractAddress not found in credentialStatus.id field");let s=o.split(":");if(s.length!=2)throw new Error("invalid contract address encoding. should be chainId:contractAddress");let a=parseInt(s[0],10),c=s[1],l=r.searchParams.get("revocationNonce")||e.revocationNonce;if(l==null)throw new Error("revocationNonce not found in credentialStatus id field");let u=typeof l=="number"?l:parseInt(l,10);return{contractAddress:c,chainId:a,revocationNonce:u,stateHex:i}}networkByChainId(e){let t=this._configs.find(r=>r.chainId===e);if(!t)throw new Error(`chainId "${e}" not supported`);return t}_getOnChainRevocationStorageForIssuer(e,t){let r=this.networkByChainId(e);return new VE(r,t)}};var U0=class{async resolve(e){let r=await(await fetch(e.id)).json();return JC(r)}},JC=({issuer:n,mtp:e})=>({mtp:Bt.fromJSON(e),issuer:n});var G0=class n{constructor(e=Ue,t=[]){this.hash=e;this.children=t}nodeType(){return this.children.length===2?1:this.children.length===3&&this.children[2].hex()===be.fromBigInt(BigInt(1)).hex()?2:this.children.length===3?3:0}toJSON(){return{hash:this.hash.hex(),children:this.children.map(e=>e.hex())}}static fromHex(e){return new n(be.fromHex(e.hash),e.children.map(t=>be.fromHex(t)))}};var gO=class{constructor(e){this._state=e}async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");try{return await this.getStatus(e,t.issuerDID,t.issuerData,t.issuerGenesisState)}catch(r){if(e?.statusIssuer?.type==="SparseMerkleTreeProof")try{return await new U0().resolve(e.statusIssuer)}catch(i){throw new Error(`can't fetch revocation status from backup endpoint: ${i?.message}`)}throw new Error(`can't fetch revocation status: ${r?.message}`)}}async getStatus(e,t,r,i){let o=Se.idFromDID(t),s;try{let u=await this._state.getLatestStateById(o.bigInt());if(!u.state)throw new Error("state contract returned empty state");s=u.state}catch(u){if(!QE(u))throw u;let d=this.extractState(e.id);if(!d)return this.getRevocationStatusFromIssuerData(t,r,i);let h=be.fromHex(d).bigInt(),f=rp(t);if(!f&&!tl(t,h))throw new Error(`latest state not found and state parameter ${d} is not genesis state`);if(f)throw new Error("State must be published for Ethereum based identity");s=h}let a=e.id.split("/node")[0],c=be.fromBigInt(BigInt(e.revocationNonce??0)),l=be.fromBigInt(s);return await this.getRevocationStatusFromRHS(c,l,a)}getRevocationStatusFromIssuerData(e,t,r){if(r&&tl(e,r.value.bigInt()))return{mtp:new Bt,issuer:{state:r.value.hex(),revocationTreeRoot:r.revocationTreeRoot.hex(),rootOfRoots:r.rootOfRoots.hex(),claimsTreeRoot:r.claimsTreeRoot.hex()}};if(t&&tl(e,t.state.value))return{mtp:new Bt,issuer:{state:t.state.value,revocationTreeRoot:t.state.revocationTreeRoot,rootOfRoots:t.state.rootOfRoots,claimsTreeRoot:t.state.claimsTreeRoot}};throw new Error("issuer data / genesis state param is empty")}async getRevocationStatusFromRHS(e,t,r){if(!r)throw new Error("HTTP reverse hash service URL is not specified");let o=(await(await fetch(`${r}/node/${t.hex()}`)).json())?.node;if(o.children.length!==3)throw new Error("state should has tree children");let s=t.hex(),[a,c,l]=o.children,u=be.fromHex(c);return{mtp:await this.rhsGenerateProof(u,e,`${r}/node`),issuer:{state:s,claimsTreeRoot:a,revocationTreeRoot:c,rootOfRoots:l}}}async rhsGenerateProof(e,t,r){let i=!1,o=[],s,a=()=>new Bt({siblings:o,existence:i,nodeAux:s}),c=e;for(let l=0;l<t.bytes.length*8;l++){if(c.bytes.every(f=>f===0))return a();let d=(await(await fetch(`${r}/${c.hex()}`)).json())?.node,h=G0.fromHex(d);switch(h.nodeType()){case 2:return t.bytes.every((f,p)=>f===h.children[0].bytes[p])?(i=!0,a()):(s={key:h.children[0],value:h.children[1]},a());case 1:tw(t.bytes,l)?(c=h.children[1],o.push(h.children[0])):(c=h.children[0],o.push(h.children[1]));break;default:throw new Error(`found unexpected node type in tree ${h.hash.hex()}`)}}throw new Error("tree depth is too high")}extractState(e){return new URL(e).searchParams.get("state")}};function JLe(n,e){let t=Se.parse(n),r=Se.idFromDID(t),{method:i,blockchain:o,networkId:s}=Se.decodePartsFromId(r),a=vt.hexToBytes(e),c=vt.bytesToInt(a),l=Hc(i,o,s);return eee(Se.idFromDID(t).bigInt(),c,l)}function eee(n,e,t){let r=$e.idGenesisFromIdenState(t,e);return n.toString()===r.bigInt().toString()}var YE=class{resolvers=new Map;register(e,t){this.resolvers.set(e,t)}get(e){return this.resolvers.get(e)}};var jE=class{async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");if(!t?.userDID)throw new Error("UserDID is not set in options");if(typeof e.revocationNonce!="number")throw new Error("Revocation nonce is not set in credential status");let r=t.userDID.string(),i=t.issuerDID.string(),o=qLe(r,i,e.revocationNonce),a=await(await fetch(e.id,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})).json();return JC(a.body)}};function qLe(n,e,t){return{id:Ft(),typ:"application/iden3comm-plain-json",type:ut.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE,body:{revocation_nonce:t},thid:Ft(),from:n,to:e}}var WE=class{_publishers=new Map;register(e,...t){let r=this._publishers.get(e)??[];r.push(...t),this._publishers.set(e,r)}get(e){return this._publishers.get(e)}},yO=class{constructor(e){this._storage=e}async publish(e){if(!["Iden3OnchainSparseMerkleTreeProof2023"].includes(e.credentialStatusType))throw new Error(`On-chain publishing is not supported for credential status type ${e.credentialStatusType}`);let t=e.nodes.map(o=>o.children.map(s=>s.bigInt())),r=this._storage.saveNodes(t),i=e.onChain?.publishMode??"sync";switch(e.onChain?.txCallback&&(i="callback"),i){case"sync":await r;break;case"callback":{if(!e.onChain?.txCallback)throw new Error('txCallback is required for publishMode "callback"');let o=e.onChain?.txCallback;r.then(s=>o(s));break}case"async":{let o=Yw.getInstance();r.then(s=>o.publish(ZR.TX_RECEIPT_ACCEPTED,s));break}default:throw new Error(`Invalid publishMode: ${i}`)}}},K0=class{async publish(e){if(!["Iden3ReverseSparseMerkleTreeProof"].includes(e.credentialStatusType))throw new Error(`On-chain publishing is not supported for credential status type ${e.credentialStatusType}`);let t=e.nodes.map(i=>i.toJSON()),r=await fetch(e.rhsUrl+"/node",{method:"post",body:JSON.stringify(t)});if(r.status!==200)throw new Error(`Failed to publish credential status. Status: ${r.status}`)}};var wO=class{constructor(e){this.didResolverUrl=e}async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");let r=`${this.didResolverUrl}/1.0/credential-status/${encodeURIComponent(t.issuerDID.string())}`;return await(await fetch(r,{method:"POST",body:JSON.stringify(e)})).json()}};var bO=class{constructor(e,t){this._storage=e;this._credentialStatusResolverRegistry=t;this._credentialStatusResolverRegistry||(this._credentialStatusResolverRegistry=new YE,this._credentialStatusResolverRegistry.register("SparseMerkleTreeProof",new U0),this._credentialStatusResolverRegistry.register("Iden3commRevocationStatusV1.0",new jE))}async getAuthBJJCredential(e){let t=await this._storage.credential.findCredentialsByQuery({context:qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:qe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]});if(!t.length)throw new Error(qe.ERRORS.NO_AUTH_CRED_FOUND);for(let r=0;r<t.length;r++){let i=t[r];if(!(await this.getRevocationStatusFromCredential(i)).mtp.existence)return i}throw new Error("all auth bjj credentials are revoked")}async getAllAuthBJJCredentials(e){return this._storage.credential.findCredentialsByQuery({context:qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:qe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]})}async getRevocationStatusFromCredential(e){let t=e.getIden3SparseMerkleTreeProof(),r=e.getBJJSignature2021Proof(),i=t?t.issuerData.state:r?.issuerData.state,o=Se.parse(e.issuer),s=Vu(o,e),a={issuerGenesisState:i,issuerDID:o,userDID:s};return this.getRevocationStatus(e.credentialStatus,a)}async getRevocationStatus(e,t){let r=this._credentialStatusResolverRegistry?.get(e.type);if(!r)throw new Error(`credential status resolver does not exist for ${e.type} type`);return r.resolve(e,t)}createCredential=(e,t,r)=>{if(!r.$metadata.uris.jsonLdContext)throw new Error("jsonLdContext is missing is the schema");let i={...t};return i.context=i.context??[],i.displayMethod?.type==="Iden3BasicDisplayMethodV1"&&!i.context.includes(qe.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)&&i.context.push(qe.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD),i.context.push(r.$metadata.uris.jsonLdContext),i.expiration=i.expiration?i.expiration*1e3:void 0,i.id=i.id?i.id:`urn:${Ft()}`,i.issuanceDate=i.issuanceDate?i.issuanceDate*1e3:Date.now(),Gr.fromCredentialRequest(e,i)};async findById(e){return this._storage.credential.findCredentialById(e)}async findByContextType(e,t){return this._storage.credential.findCredentialsByQuery({context:e,type:t})}async save(e){return this._storage.credential.saveCredential(e)}async saveAll(e){return this._storage.credential.saveAllCredentials(e)}async remove(e){return this._storage.credential.removeCredential(e)}async list(){return this._storage.credential.listCredentials()}async findByQuery(e){return this._storage.credential.findCredentialsByQuery(e)}async filterByCredentialSubject(e,t){return e.filter(r=>r.credentialSubject.id===t.string())}async findNonRevokedCredential(e){for(let t of e){let r=await this.getRevocationStatusFromCredential(t);if(!r.mtp.existence)return{cred:t,revStatus:r}}throw new Error(qe.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED)}};async function qC(n,e,t,r){let i=await VC(r,e,n);await new K0().publish({nodes:i,credentialStatusType:"Iden3ReverseSparseMerkleTreeProof",rhsUrl:t})}async function VC(n,e,t){let r=new EO;return n&&await QLe(r,e,n),await VLe(r,e),t.bytes.every(i=>i===0)||r.addProofNode(new G0(t,[await e.claimsTree.root(),await e.revocationTree.root(),await e.rootsTree.root()])),r.nodes}async function VLe(n,e){let t=e.rootsTree,r=e.claimsTree;return n.addKey(t,(await r.root()).bigInt())}async function QLe(n,e,t){let r=e.revocationTree;for(let i of t)await n.addKey(r,BigInt(i))}var EO=class{constructor(e=[],t=new Map){this.nodes=e;this.seen=t}async addKey(e,t){let{value:r,siblings:i}=await e.get(t),o=be.fromBigInt(t),s=be.fromBigInt(r),a=new qc(o,s),c=await zLe(i,a);for(let l of c)this.seen.get(l.hash.hex())||(this.nodes.push(l),this.seen.set(l.hash.hex(),!0))}addProofNode(e){let t=e.hash.hex();this.seen.get(t)||(this.nodes.push(e),this.seen.set(t,!0))}};async function zLe(n,e){if(e.type!==sa)throw new Error("node is not a leaf");let t=await e.getKey(),r=n.length,i=new Array(r+1);for(let a=0;a<i.length;a++)i[a]=new G0;i[r].hash=t;let o=be.fromBigInt(BigInt(1));i[r].children=[e.entry[0],e.entry[1],o];let s=e.entry[0];for(let a=r-1;a>=0;a--){let c=tw(s.bytes,a);i[a].children=new Array(2),c?(i[a].children[0]=n[a],i[a].children[1]=t):(i[a].children[0]=t,i[a].children[1]=n[a]),i[a].hash=hh([i[a].children[0].bigInt(),i[a].children[1].bigInt()]),t=i[a].hash}return i}var IO=class n extends Fi{constructor(t,r){super();this._packerMgr=t;this.opts=r}async handle(t,r){switch(t.type){case ut.CREDENTIAL_OFFER_MESSAGE_TYPE:{let i=await this.handleOfferMessage(t,r);if(Array.isArray(i)){let o=this.opts?.credentialWallet;if(!o)throw new Error("Credential wallet is not provided");return await o.saveAll(i),null}return i}case ut.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE:return this.handleFetchRequest(t);case ut.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:return this.handleIssuanceResponseMsg(t);case ut.CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE:{let i=await this.handleOnchainOfferMessage(t);if(Array.isArray(i)){let o=this.opts?.credentialWallet;if(!o)throw new Error("Credential wallet is not provided");return await o.saveAll(i),null}return i}default:return super.handle(t,r)}}async handleOnchainOfferMessage(t){if(!this.opts?.onchainIssuer)throw new Error("onchain issuer is not provided");let r=[];for(let i of t.body.credentials){let o=Se.parse(t.from),s=Se.parse(t.to),a=await this.opts.onchainIssuer.getCredential(o,s,BigInt(i.id));r.push(a)}return r}async handleOfferMessage(t,r){r.mediaType||(r.mediaType="application/iden3-zkp-json");let i=[];for(let o of t.body.credentials){let s=Ft(),a={id:s,typ:r.mediaType,type:ut.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE,thid:t.thid??s,body:{id:o.id},from:t.to,to:t.from},c=Fe.encode(JSON.stringify(a)),l=Se.parse(t.to),u=na(r.mediaType,r.packerOptions,{senderDID:l}),d=dt.decode(await this._packerMgr.pack(r.mediaType,c,u));try{if(!t?.body?.url)throw new Error("could not fetch W3C credential, body url is missing");let f=await(await fetch(t.body.url,{method:"post",headers:{"Content-Type":"application/x-www-form-urlencoded",...r.headers},body:d})).arrayBuffer();if(!f.byteLength)throw new Error(`could not fetch , ${o?.id}, response is empty`);let{unpackedMessage:p}=await this._packerMgr.unpack(new Uint8Array(f));if(p.type!==ut.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE)return p;i.push(Gr.fromJSON(p.body.credential))}catch(h){throw new Error(`could not fetch protocol message for credential offer id: , ${o?.id}, error: ${h.message??h}`)}}return i}async handleCredentialOffer(t,r){let i=await n.unpackMessage(this._packerMgr,t,ut.CREDENTIAL_OFFER_MESSAGE_TYPE);r?.allowExpiredMessages||vr(i);let o=r?.mediaType||"application/iden3-zkp-json",s=na(o,r?.packerOptions,{provingMethodAlg:r?.messageProvingMethodAlg||await Oc(t),senderDID:Se.parse(i.to)}),a=await this.handleOfferMessage(i,{mediaType:o,headers:r?.headers,packerOptions:s});if(Array.isArray(a))return a;throw new Error("invalid protocol message response")}async handleOnchainOffer(t){let r=await n.unpackMessage(this._packerMgr,t,ut.CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE);return this.handleOnchainOfferMessage(r)}async handleFetchRequest(t){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");let r=Se.parse(t.to),i=Se.parse(t.from),o=t.body?.id;if(!o)throw new Error("invalid credential id in fetch request body");if(!this.opts?.credentialWallet)throw new Error("please, provide credential wallet in options");let s=await this.opts.credentialWallet.findById(o);if(!s)throw new Error("credential not found");if(Vu(r,s).string()!==i.string())throw new Error("credential subject is not a sender DID");return{id:Ft(),type:ut.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE,typ:t.typ??"application/iden3comm-plain-json",thid:t.thid??Ft(),body:{credential:s},from:t.to,to:t.from}}async handleCredentialFetchRequest(t,r){let i=await n.unpackMessage(this._packerMgr,t,ut.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);r?.allowExpiredMessages||vr(i);let o=await this.handleFetchRequest(i);return this._packerMgr.pack("application/iden3comm-plain-json",Fe.encode(JSON.stringify(o)),{})}async handleIssuanceResponseMsg(t){if(!this.opts?.credentialWallet)throw new Error("please provide credential wallet in options");if(!t.body?.credential)throw new Error("credential is missing in issuance response message");if(!(t.body.credential instanceof Gr))throw new Error("credential object is not properly unmarshaled");return await this.opts.credentialWallet.save(t.body.credential),null}async handleIssuanceResponseMessage(t,r){let i=await n.unpackMessage(this._packerMgr,t,ut.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);return r?.allowExpiredMessages||vr(i),i.body.credential=Gr.fromJSON(i.body.credential),await this.handleIssuanceResponseMsg(i),Uint8Array.from([])}static async unpackMessage(t,r,i){let{unpackedMessage:o}=await t.unpack(r),s=o;if(o.type!==i)throw new Error("Invalid message type");return s}};var AO=class extends Fi{constructor(t,r,i){super();this._packerMgr=t;this._proofService=r;this._zkpVerifier=i}_supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1","authV2","credentialAtomicQueryV3-beta.1","linkedMultiQuery10-beta.1"];async handle(t,r){switch(t.type){case ut.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE:{let i=t,o=await this.handleContractInvoke(i,r);return this.createContractInvokeResponse(i,o)}default:return super.handle(t,r)}}async handleContractInvoke(t,r){if(t.type!==ut.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for contract invoke request");let{senderDid:i,ethSigner:o,challenge:s}=r;if(!r.ethSigner)throw new Error("Can't sign transaction. Provide Signer in options.");let{chain_id:a}=t.body.transaction_data;if(!Object.keys(ra).find(f=>ra[f]===a))throw new Error(`Invalid chain id ${a}`);let l=t.from?Se.parse(t.from):void 0,{scope:u=[]}=t.body,d=await Ny(i,u,l,this._proofService,{ethSigner:o,challenge:s??vt.bytesToInt(Ui(await o.getAddress())),supportedCircuits:this._supportedCircuits});switch(t.body.transaction_data.method_id.replace("0x","")){case"ade09fcd":{let f=await this._zkpVerifier.submitZKPResponseV2(o,t.body.transaction_data,d),p=new Map;for(let[E,b]of f)p.set(E,{responses:b});return t.body.transaction_data.txHash=f.keys().next().value,p}case"b68967e2":{let f=await this._zkpVerifier.submitZKPResponse(o,t.body.transaction_data,d),p=new Map;for(let[E,b]of f)p.set(E,{responses:[b]});return t.body.transaction_data.txHash=f.keys().next().value,p}case"06c86a91":{if(!t.to)throw new Error("failed message. empty 'to' field");let f=this.getFirstSupportedProfile(ut.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE,t.body.accept),p=Se.parse(t.to),{authProof:E}=await dO(p,this._proofService,{supportedCircuits:this._supportedCircuits,acceptProfile:f,senderAddress:await o.getAddress(),zkpResponses:d}),b=await this._zkpVerifier.submitResponse(o,t.body.transaction_data,d,E);return t.body.transaction_data.txHash=b.keys().next().value,b}default:throw new Error("Not supported method id. Only 'b68967e2, ade09fcd and 06c86a91 are supported.'")}}getFirstSupportedProfile(t,r){if(r?.length)for(let i of r){let o=Ss(i),s=Number(t.split("/").at(-2));if(!(o.protocolVersion!=="iden3comm/v1"||o.protocolVersion==="iden3comm/v1"&&(s<1||s>=2))&&this._packerMgr.isProfileSupported(o.env,i))return o}return hE}async parseContractInvokeRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==ut.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i.body.scope=i.body.scope||[],i}async createContractInvokeResponse(t,r){let i={id:t.id,thid:t.thid,type:ut.CONTRACT_INVOKE_RESPONSE_MESSAGE_TYPE,from:t.to,to:t.from,body:{transaction_data:t.body.transaction_data,scope:[]},created_time:Ct(new Date)};for(let[o,s]of r){for(let a of s.responses)i.body.scope.push({txHash:o,...a});i.body={...i.body,crossChainProof:s.crossChainProof,authProof:s.authProof}}return i}async handleContractInvokeRequest(t,r,i){let o=await this.parseContractInvokeRequest(r);if(i.allowExpiredMessages||vr(o),o.body.transaction_data.method_id!=="b68967e2")throw new Error("please use handle method to work with other method ids");if(o.type!==ut.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for contract invoke request");let{ethSigner:s,challenge:a}=i;if(!s)throw new Error("Can't sign transaction. Provide Signer in options.");let{chain_id:c}=o.body.transaction_data;if(!Object.keys(ra).find(h=>ra[h]===c))throw new Error(`Invalid chain id ${c}`);let u=o.from?Se.parse(o.from):void 0,d=await Ny(t,o?.body?.scope,u,this._proofService,{ethSigner:s,challenge:a,supportedCircuits:this._supportedCircuits});return this._zkpVerifier.submitZKPResponse(s,o.body.transaction_data,d)}};var xO=class{constructor(e){this._options=e}async refreshCredential(e,t){if(!e.refreshService)throw new Error("refreshService not specified for W3CCredential");if(e.refreshService.type!=="Iden3RefreshService2023")throw new Error(`refresh service type ${e.refreshService.type} is not supported`);let r=e.credentialSubject.id;if(!r)throw new Error("self credentials do not support refresh");let i=Se.parse(r),o=t?.mediaType||"application/iden3-zkp-json",s=t?.packerOptions??{senderDID:i,provingMethodAlg:Nl},a={id:Ft(),typ:"application/iden3-zkp-json",type:ut.CREDENTIAL_REFRESH_MESSAGE_TYPE,thid:Ft(),body:{id:e.id,reason:t?.reason??"credential is expired"},from:r,to:e.issuer},c=Fe.encode(JSON.stringify(a)),l=await this._options.packageManager.pack(o,c,s),u=await fetch(e.refreshService.id,{method:"post",headers:{"Content-Type":"application/json"},body:l.buffer});if(u.status!==200)throw new Error(`could not refresh W3C credential, return status ${u.status}`);let d=await u.json();if(!d.body?.credential)throw new Error("no credential in CredentialIssuanceMessage response");return Gr.fromJSON(d.body.credential)}};var vO=class extends Fi{constructor(t,r){super();this._packerMgr=t;this._identityWallet=r}handle(t,r){if(!r.senderDid)throw new Error("DID is required");if(!r.mediaType)throw new Error("mediaType is required");switch(t.type){case ut.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE:return this.handleRevocationStatusRequestMessage(t,r);default:return super.handle(t,r)}}async handleRevocationStatusRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body?.revocation_nonce)throw new Error("failed request. empty 'revocation_nonce' field");let i=Se.parse(t.to),o=await this._identityWallet.generateNonRevocationMtpWithNonce(i,BigInt(t.body.revocation_nonce),r.treeState),s=o.treeState,a={issuer:{state:s?.state.string(),claimsTreeRoot:s.claimsRoot.string(),revocationTreeRoot:s.revocationRoot.string(),rootOfRoots:s.rootOfRoots.string()},mtp:o.proof},c=Ft();return{id:c,typ:"application/iden3comm-plain-json",type:ut.REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE,thid:t.thid??c,body:a,from:r.senderDid.string(),to:t.from}}async parseRevocationStatusRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==ut.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handleRevocationStatusRequest(t,r,i){i||(i={mediaType:"application/iden3comm-plain-json"});let o=await this.parseRevocationStatusRequest(r);i.allowExpiredMessages||vr(o);let s=await this.handleRevocationStatusRequestMessage(o,{senderDid:t,mediaType:i.mediaType,packerOptions:i.packerOptions,treeState:i.treeState});if(!o.to)throw new Error("failed request. empty 'to' field");let a=Se.parse(o.to),c=na(i.mediaType,i.packerOptions,{senderDID:a,provingMethodAlg:i.packerOptions?.provingMethodAlg||await Oc(r)});return this._packerMgr.pack(i.mediaType,Fe.encode(JSON.stringify(s)),c)}};function YLe(n,e,t){let r=Ft();return{id:r,thid:r,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:ut.PROPOSAL_REQUEST_MESSAGE_TYPE,body:{credentials:t.credentials,did_doc:t.did_doc},created_time:Ct(new Date),expires_time:t?.expires_time?Ct(t.expires_time):void 0,attachments:t.attachments}}function jLe(n,e,t,r){let i=Ft();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:ut.PROPOSAL_MESSAGE_TYPE,body:{proposals:t||[]},created_time:Ct(new Date),expires_time:r?.expires_time?Ct(r.expires_time):void 0}}var SO=class extends Fi{constructor(t,r,i){super();this._packerMgr=t;this._identityWallet=r;this._params=i}async handle(t,r){switch(t.type){case ut.PROPOSAL_REQUEST_MESSAGE_TYPE:return await this.handleProposalRequestMessage(t,r);default:return super.handle(t,r)}}async parseProposalRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==ut.PROPOSAL_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handleProposalRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body?.credentials?.length)throw new Error("failed request. no 'credentials' in body");let i,o;for(let s=0;s<t.body.credentials.length;s++){let a=t.body.credentials[s],c=[];try{c=await this._identityWallet.credentialWallet.findByQuery({credentialSubject:{id:{$eq:t.from}},type:a.type,context:a.context,allowedIssuers:[t.to]})}catch(u){if(u.message!=="no credential satisfied query")throw u}if(c.length){let u=Ft();i||(i={id:u,typ:this._params.packerParams.mediaType,type:ut.CREDENTIAL_OFFER_MESSAGE_TYPE,thid:t.thid??u,body:{url:this._params.agentUrl,credentials:[]},from:t.to,to:t.from}),i.body.credentials.push(...c.map(d=>({id:d.id,description:""})));continue}let l=await this._params.proposalResolverFn(a.context,a.type,{msg:t});if(!l)throw new Error(`can't resolve Proposal for type: ${a.type}, context: ${a.context}`);if(!o){let u=Ft();o={id:u,typ:this._params.packerParams.mediaType,type:ut.PROPOSAL_MESSAGE_TYPE,thid:t.thid??u,body:{proposals:[]},from:t.to,to:t.from}}o.body?.proposals.push(l)}return o??i}async handleProposalRequest(t,r){let i=await this.parseProposalRequest(t);if(!i.from)throw new Error("failed request. empty 'from' field");r?.allowExpiredMessages||vr(i);let o=Se.parse(i.from),s=await this.handleProposalRequestMessage(i),a=Fe.encode(JSON.stringify(s)),c=na(this._params.packerParams.mediaType,this._params.packerParams.packerOptions,{provingMethodAlg:await Oc(t),senderDID:o});return this._packerMgr.pack(this._params.packerParams.mediaType,a,c)}async handleProposal(t,r){if(r?.allowExpiredMessages||vr(t),r?.proposalRequest&&r.proposalRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.proposalRequest.from}, given ${t.to}`);return{proposal:t}}};function tee(n,e,t,r,i){let o=Ft();return{id:o,thid:o,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:ut.PAYMENT_REQUEST_MESSAGE_TYPE,body:{agent:t,payments:r},created_time:Ct(new Date),expires_time:i?.expires_time?Ct(i.expires_time):void 0}}function nee(n,e,t,r){let i=Ft();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:ut.PAYMENT_MESSAGE_TYPE,body:{payments:t},created_time:Ct(new Date),expires_time:r?.expires_time?Ct(r.expires_time):void 0}}var CO=class extends Fi{constructor(t,r){super();this._packerMgr=t;this._params=r}async handle(t,r){switch(t.type){case ut.PAYMENT_REQUEST_MESSAGE_TYPE:return await this.handlePaymentRequestMessage(t,r);case ut.PAYMENT_MESSAGE_TYPE:return await this.handlePayment(t,r),null;default:return super.handle(t,r)}}async parsePaymentRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==ut.PAYMENT_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handlePaymentRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body.payments?.length)throw new Error("failed request. no 'payments' in body");if(!r.paymentHandler)throw new Error("please provide payment handler in context");let i=Se.parse(t.to),o=Se.parse(t.from),s=[];for(let p=0;p<t.body.payments.length;p++){let{data:E}=t.body.payments[p],b=Array.isArray(E)?E.find(C=>C.type==="Iden3PaymentRequestCryptoV1"?C.id===r.nonce:C.nonce===r.nonce):E;if(!b)throw new Error(`failed request. no payment in request for nonce ${r.nonce}`);switch(b.type){case"Iden3PaymentRequestCryptoV1":s.push(await this.handleIden3PaymentRequestCryptoV1(b,r.paymentHandler));break;case"Iden3PaymentRailsRequestV1":s.push(await this.handleIden3PaymentRailsRequestV1(b,r.paymentHandler));break;case"Iden3PaymentRailsERC20RequestV1":s.push(await this.handleIden3PaymentRailsERC20RequestV1(b,r.paymentHandler,r.erc20TokenApproveHandler));break;case"Iden3PaymentRailsSolanaRequestV1":s.push(await this.handleIden3PaymentRailsSolanaRequestV1(b,r.paymentHandler));break;case"Iden3PaymentRailsSolanaSPLRequestV1":s.push(await this.handleIden3PaymentRailsSolanaSPLRequestV1({...b,type:"Iden3PaymentRailsSolanaSPLRequestV1"},r.paymentHandler));break}}let a=nee(i,o,s),c=r?.mediaType||this._params.packerParams.mediaType||"application/iden3-zkp-json",l=na(c,r?.packerOptions||this._params.packerParams,{senderDID:i,provingMethodAlg:r.messageProvingMethodAlg}),u=await this.packMessage(a,i,c,l),h=await(await fetch(t.body.agent,{method:"POST",body:u.buffer,headers:{"Content-Type":this._params.packerParams.mediaType==="application/iden3comm-plain-json"?"application/json":"application/octet-stream"}})).arrayBuffer();if(!h.byteLength)return null;let{unpackedMessage:f}=await this._packerMgr.unpack(new Uint8Array(h));return f}async handlePaymentRequest(t,r){let i=await this.parsePaymentRequest(t);if(!i.from)throw new Error("failed request. empty 'from' field");if(!i.to)throw new Error("failed request. empty 'to' field");r?.allowExpiredMessages||vr(i);let o=r.mediaType||this._params.packerParams.mediaType||"application/iden3-zkp-json";r.packerOptions||(r.packerOptions=this._params.packerParams.packerOptions),r.mediaType=o;let s=Se.parse(i.to);r.packerOptions=na(o,r.packerOptions,{provingMethodAlg:await Oc(t),senderDID:s});let a=await this.handlePaymentRequestMessage(i,r);return a?this.packMessage(a,s,r.mediaType||"application/iden3-zkp-json",r.packerOptions):null}async handlePayment(t,r){if(r?.allowExpiredMessages||vr(t),r.paymentRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.paymentRequest.from}, given ${t.to}`);if(!t.body.payments.length)throw new Error("failed request. empty 'payments' field in body");if(!r.paymentValidationHandler)throw new Error("please provide payment validation handler in options");for(let i=0;i<t.body.payments.length;i++){let o=t.body.payments[i],s=o.type==="Iden3PaymentCryptoV1"?o.id:o.nonce,c=r.paymentRequest.body.payments.map(l=>Array.isArray(l.data)?l.data:[l.data]).flat().find(l=>l.type==="Iden3PaymentRequestCryptoV1"?l.id===s:l.nonce===s);if(!c)throw new Error(`can't find payment request for payment ${o.type==="Iden3PaymentCryptoV1"?"id":"nonce"} ${s}`);await r.paymentValidationHandler(o.paymentData.txId,c)}}async createPaymentRailsV1(t,r,i,o,s,a){let c=[];for(let l=0;l<s.length;l++){let{credentials:u,description:d}=s[l],h=[];for(let f=0;f<s[l].options.length;f++){let{nonce:p,amount:E,chainId:b,optionId:C,expirationDate:B}=s[l].options[f],J=this._params.multiChainPaymentConfig?.find(z=>z.chainId===b);if(!J)throw new Error(`failed request. no config for chain ${b}`);let{recipient:G,paymentRails:U,options:O}=J,v=O.find(z=>z.id===C);if(!v)throw new Error(`failed request. no option for id ${C}`);if((v.type==="Iden3PaymentRailsERC20RequestV1"||v.type==="Iden3PaymentRailsSolanaSPLRequestV1")&&!v.contractAddress)throw new Error(`failed request. no token address for option id ${C}`);let D=B??new Date(new Date().setHours(new Date().getHours()+1));if(v.type==="Iden3PaymentRailsSolanaRequestV1"||v.type==="Iden3PaymentRailsSolanaSPLRequestV1"){if(!a?.solSigner)throw new Error(`please provide solana signer in context for ${v.type} payment type`);let z=await UB(a.solSigner,v,b,U,G,BigInt(E),D,p);h.push(z)}else{let z=await GB(o,v,b,U,G,BigInt(E),D,p);h.push(z)}}c.push({data:h,credentials:u,description:d})}return tee(t,r,i,c)}async packMessage(t,r,i,o){let s=Fe.encode(JSON.stringify(t)),a=i==="application/iden3comm-signed-json"?o:{provingMethodAlg:o?.provingMethodAlg||Nl};return await this._packerMgr.pack(i,s,{senderDID:r,...a})}async handleIden3PaymentRequestCryptoV1(t,r){if(t.expiration&&new Date(t.expiration)<new Date)throw new Error("failed request. expired request");let i=await r(t);return{id:t.id,"@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentCryptoV1",type:"Iden3PaymentCryptoV1",paymentData:{txId:i}}}async handleIden3PaymentRailsRequestV1(t,r){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");let i=await D3(t,this._params.documentResolver);if(this._params.allowedSigners&&!this._params.allowedSigners.includes(i))throw new Error("failed request. signer is not in the allowed signers list");let o=await r(t),s=Array.isArray(t.proof)?t.proof[0]:t.proof;return{nonce:t.nonce,type:"Iden3PaymentRailsV1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsV1",paymentData:{txId:o,chainId:s.eip712.domain.chainId}}}async handleIden3PaymentRailsSolanaRequestV1(t,r){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");if(!await R3(t,this._params.documentResolver))throw new Error("failed request. invalid Solana payment request signature");let o=Array.isArray(t.proof)?t.proof[0]:t.proof,s=o.verificationMethod.split(":").slice(-1)[0];if(this._params.allowedSigners&&!this._params.allowedSigners.includes(s))throw new Error("failed request. signer is not in the allowed signers list");let a=await r(t);return{nonce:t.nonce,type:"Iden3PaymentRailsSolanaV1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsSolanaV1",paymentData:{txId:a,chainId:o.domain.chainId}}}async handleIden3PaymentRailsSolanaSPLRequestV1(t,r){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");if(!await R3(t,this._params.documentResolver))throw new Error("failed request. invalid Solana payment request signature");let o=Array.isArray(t.proof)?t.proof[0]:t.proof,s=o.verificationMethod.split(":").slice(-1)[0];if(this._params.allowedSigners&&!this._params.allowedSigners.includes(s))throw new Error("failed request. signer is not in the allowed signers list");let a=await r(t);return{nonce:t.nonce,type:"Iden3PaymentRailsSolanaSPLV1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsSolanaSPLV1",paymentData:{txId:a,chainId:o.domain.chainId,tokenAddress:t.tokenAddress}}}async handleIden3PaymentRailsERC20RequestV1(t,r,i){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");let o=await D3(t,this._params.documentResolver);if(this._params.allowedSigners&&!this._params.allowedSigners.includes(o))throw new Error("failed request. signer is not in the allowed signers list");if(!t.features?.includes("EIP-2612")&&!i)throw new Error("please provide erc20TokenApproveHandler in context for ERC-20 payment type");i&&await i(t);let s=await r(t),a=Array.isArray(t.proof)?t.proof[0]:t.proof;return{nonce:t.nonce,type:"Iden3PaymentRailsERC20V1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsERC20V1",paymentData:{txId:s,chainId:a.eip712.domain.chainId,tokenAddress:t.tokenAddress}}}};function WLe(n,e){let t=Ft();return{id:t,thid:t,typ:"application/iden3comm-plain-json",type:ut.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE,body:{queries:n},from:e?.from,to:e?.to,created_time:Ct(new Date),expires_time:e?.expires_time}}function ree(n,e){let t=Ft();return{id:t,typ:"application/iden3comm-plain-json",thid:t,type:ut.DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE,body:{disclosures:n},from:e?.from,to:e?.to,created_time:Ct(new Date),expires_time:e?.expires_time}}var LO=class extends Fi{constructor(t){super();this._options=t;let r=["id","typ","type","thid","body","from","to","created_time","expires_time"];t.headers||(t.headers=r)}async handle(t,r){switch(t.type){case ut.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE:return await this.handleDiscoveryQuery(t,r);default:return super.handle(t,r)}}async handleDiscoveryQuery(t,r){r?.allowExpiredMessages||vr(t);let i=[];for(let o of t.body.queries)i.push(...this.handleQuery(o));return Promise.resolve(ree(i,{to:t.from,from:t.to,expires_time:r?.disclosureExpiresDate?Ct(r.disclosureExpiresDate):void 0}))}handleQuery(t){let r=[];switch(t["feature-type"]){case"accept":r=this.handleAcceptQuery();break;case"protocol":r=this.handleProtocolQuery();break;case"goal-code":r=this.handleGoalCodeQuery();break;case"header":r=this.handleHeaderQuery();break}return this.handleMatch(r,t.match)}handleAcceptQuery(){return this._options.packageManager.getSupportedProfiles().map(r=>({"feature-type":"accept",id:r}))}handleProtocolQuery(){return this._options.protocols?.map(t=>({"feature-type":"protocol",id:t}))??[]}handleGoalCodeQuery(){return this._options.goalCodes?.map(t=>({"feature-type":"goal-code",id:t}))??[]}handleHeaderQuery(){return this._options.headers?.map(t=>({"feature-type":"header",id:t}))??[]}handleMatch(t,r){if(!r||r==="*")return t;let i=this.wildcardToRegExp(r);return t.filter(o=>i.test(o.id))}wildcardToRegExp(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`)}};function ZLe(n,e,t){return{id:Ft(),pthid:n,typ:"application/iden3comm-plain-json",type:ut.PROBLEM_REPORT_MESSAGE_TYPE,ack:t?.ack,body:{code:e,comment:t?.comment,args:t?.args,escalate_to:t?.escalate_to},from:t?.from,to:t?.to}}var hd={url:"http://localhost:8545",defaultGasLimit:6e5,minGasPrice:"0",maxGasPrice:"100000000000",confirmationBlockCount:5,confirmationTimeout:6e5,contractAddress:"",receiptTimeout:6e5,rpcResponseTimeout:5e3,waitReceiptCycleTime:3e4,waitBlockCycleTime:3e3},zE=class{constructor(e,t){this.ethConfig=e;let r=Array.isArray(e)?e[0]:e;this.provider=new jt(r.url),this.stateContract=new Ln(r.contractAddress,x5,this.provider),this._transactionService=new $s(this.getRpcProvider()),this._latestStateCacheOptions={ttl:t?.latestStateCacheOptions?.ttl??Zr.DEFAULT_PROOF_VERIFY_DELAY/2,maxSize:t?.latestStateCacheOptions?.maxSize??Xm},this._stateCacheOptions={notReplacedTtl:t?.stateCacheOptions?.notReplacedTtl??Zr.DEFAULT_PROOF_VERIFY_DELAY/2,replacedTtl:t?.stateCacheOptions?.replacedTtl??Zr.DEFAULT_PROOF_VERIFY_DELAY,maxSize:t?.stateCacheOptions?.maxSize??Xm},this._rootCacheOptions={replacedTtl:t?.rootCacheOptions?.replacedTtl??Zr.DEFAULT_AUTH_VERIFY_DELAY,notReplacedTtl:t?.rootCacheOptions?.notReplacedTtl??Zr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.rootCacheOptions?.maxSize??Xm},this._gistProofCacheOptions={ttl:Zr.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.gistProofCacheOptions?.maxSize??Xm},this._latestStateResolveCache=t?.latestStateCacheOptions?.cache??Iy({maxSize:this._latestStateCacheOptions.maxSize,ttl:this._latestStateCacheOptions.ttl}),this._stateResolveCache=t?.stateCacheOptions?.cache??Iy({maxSize:this._stateCacheOptions.maxSize,ttl:this._stateCacheOptions.replacedTtl}),this._rootResolveCache=t?.rootCacheOptions?.cache??Iy({maxSize:this._rootCacheOptions.maxSize,ttl:this._rootCacheOptions.replacedTtl}),this._gistProofResolveCache=t?.gistProofCacheOptions?.cache??Iy({maxSize:this._gistProofCacheOptions.maxSize,ttl:this._gistProofCacheOptions.ttl}),this._disableCache=t?.disableCache??!1}stateContract;provider;_transactionService;_latestStateResolveCache;_stateResolveCache;_rootResolveCache;_gistProofResolveCache;_latestStateCacheOptions;_stateCacheOptions;_rootCacheOptions;_gistProofCacheOptions;_disableCache=!1;async getLatestStateById(e){let t=this.getLatestStateCacheKey(e);if(!this._disableCache){let s=await this._latestStateResolveCache?.get(t);if(s)return s}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=await r.getStateInfoById(e),o={id:BigInt(i[0]),state:BigInt(i[1]),replacedByState:BigInt(i[2]),createdAtTimestamp:BigInt(i[3]),replacedAtTimestamp:BigInt(i[4]),createdAtBlock:BigInt(i[5]),replacedAtBlock:BigInt(i[6])};return!this._disableCache&&await this._latestStateResolveCache?.set(t,o,this._latestStateCacheOptions.ttl),o}async getStateInfoByIdAndState(e,t){let r=this.getStateCacheKey(e,t);if(!this._disableCache){let c=await this._stateResolveCache?.get(r);if(c)return c}let{stateContract:i}=this.getStateContractAndProviderForId(e),o=await i.getStateInfoByIdAndState(e,t),s={id:BigInt(o[0]),state:BigInt(o[1]),replacedByState:BigInt(o[2]),createdAtTimestamp:BigInt(o[3]),replacedAtTimestamp:BigInt(o[4]),createdAtBlock:BigInt(o[5]),replacedAtBlock:BigInt(o[6])},a=s.replacedAtTimestamp===0n?this._stateCacheOptions.notReplacedTtl:this._stateCacheOptions.replacedTtl;return!this._disableCache&&await this._stateResolveCache?.set(r,s,a),s}async publishState(e,t){let r=new cE;r.pubSignalsUnmarshal(Fe.encode(JSON.stringify(e.pub_signals)));let{userId:i,oldUserState:o,newUserState:s,isOldStateGenesis:a}=r,{stateContract:c,provider:l}=this.getStateContractAndProviderForId(i.bigInt()),u=c.connect(t),d=L0(e.proof),h=[i.bigInt().toString(),o.bigInt().toString(),s.bigInt().toString(),a,d.a,d.b,d.c],f=await l.getFeeData(),p=hd.maxFeePerGas?BigInt(hd.maxFeePerGas):f.maxFeePerGas,E=hd.maxPriorityFeePerGas?BigInt(hd.maxPriorityFeePerGas):f.maxPriorityFeePerGas,b=await u.transitState.estimateGas(...h),C=await u.transitState.populateTransaction(...h),B={to:C.to,data:C.data,gasLimit:b,maxFeePerGas:p,maxPriorityFeePerGas:E},{txnHash:J}=await this._transactionService.sendTransactionRequest(t,B);return J}async publishStateGeneric(e,t){let{userId:r,oldUserState:i,newUserState:o,isOldStateGenesis:s,methodId:a,methodParams:c}=t,{stateContract:l,provider:u}=this.getStateContractAndProviderForId(r.bigInt()),d=l.connect(e),h=await u.getFeeData(),f=hd.maxFeePerGas?BigInt(hd.maxFeePerGas):h.maxFeePerGas,p=hd.maxPriorityFeePerGas?BigInt(hd.maxPriorityFeePerGas):h.maxPriorityFeePerGas,E=[r.bigInt().toString(),i.bigInt().toString(),o.bigInt().toString(),s,a,c],b=await d.transitStateGeneric.estimateGas(...E),C=await d.transitStateGeneric.populateTransaction(...E),B={to:C.to,data:C.data,gasLimit:b,maxFeePerGas:f,maxPriorityFeePerGas:p},{txnHash:J}=await this._transactionService.sendTransactionRequest(e,B);return J}async getGISTProof(e){let t=this.getGistProofCacheKey(e);if(!this._disableCache){let s=await this._gistProofResolveCache?.get(t);if(s)return s}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=await r.getGISTProof(e),o={root:BigInt(i.root.toString()),existence:i.existence,siblings:i.siblings?.map(s=>BigInt(s.toString())),index:BigInt(i.index.toString()),value:BigInt(i.value.toString()),auxExistence:i.auxExistence,auxIndex:BigInt(i.auxIndex.toString()),auxValue:BigInt(i.auxValue.toString())};return!this._disableCache&&await this._gistProofResolveCache?.set(t,o,this._gistProofCacheOptions.ttl),o}async getGISTRootInfo(e,t){let r=this.getRootCacheKey(e);if(!this._disableCache){let c=await this._rootResolveCache?.get(r);if(c)return c}let{stateContract:i}=this.getStateContractAndProviderForId(t),o=await i.getGISTRootInfo(e),s={root:BigInt(o.root.toString()),replacedByRoot:BigInt(o.replacedByRoot.toString()),createdAtTimestamp:BigInt(o.createdAtTimestamp.toString()),replacedAtTimestamp:BigInt(o.replacedAtTimestamp.toString()),createdAtBlock:BigInt(o.createdAtBlock.toString()),replacedAtBlock:BigInt(o.replacedAtBlock.toString())},a=s.replacedAtTimestamp==0n?this._rootCacheOptions.notReplacedTtl:this._rootCacheOptions.replacedTtl;return!this._disableCache&&await this._rootResolveCache?.set(r,s,a),s}getRpcProvider(){return this.provider}enableCache(){this._disableCache=!1}disableCache(){this._disableCache=!0}getStateContractAndProviderForId(e){let t=$e.fromBigInt(e),r=Vy(Se.blockchainFromId(t),Se.networkIdFromId(t)),i=this.networkByChainId(r),o=new jt(i.url);return{stateContract:new Ln(i.contractAddress,x5,o),provider:o}}networkByChainId(e){let r=(Array.isArray(this.ethConfig)?this.ethConfig:[this.ethConfig]).find(i=>i.chainId===e);if(!r)throw new Error(`chainId "${e}" not supported`);return r}getGistProofCacheKey(e){return`gist-${e.toString()}`}getLatestStateCacheKey(e){return`latest-${e.toString()}`}getStateCacheKey(e,t){return`${e.toString()}-${t.toString()}`}getRootCacheKey(e){return e.toString()}};var RO=[{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[{internalType:"string",name:"message",type:"string"},{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256",name:"linkID",type:"uint256"},{internalType:"uint64",name:"requestIdToCompare",type:"uint64"},{internalType:"uint256",name:"linkIdToCompare",type:"uint256"}],name:"LinkedProofError",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint64",name:"requestId",type:"uint64"},{indexed:!0,internalType:"address",name:"requestOwner",type:"address"},{indexed:!1,internalType:"string",name:"metadata",type:"string"},{indexed:!1,internalType:"address",name:"validator",type:"address"},{indexed:!1,internalType:"bytes",name:"data",type:"bytes"}],name:"ZKPRequestSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint64",name:"requestId",type:"uint64"},{indexed:!0,internalType:"address",name:"caller",type:"address"}],name:"ZKPResponseSubmitted",type:"event"},{inputs:[],name:"REQUESTS_RETURN_LIMIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"acceptOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"addValidatorToWhitelist",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"disableZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"enableZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getProofStatus",outputs:[{components:[{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"uint256",name:"blockTimestamp",type:"uint256"}],internalType:"struct IZKPVerifier.ProofStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"string",name:"key",type:"string"}],name:"getProofStorageField",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getRequestOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getZKPRequest",outputs:[{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest",name:"zkpRequest",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"startIndex",type:"uint256"},{internalType:"uint256",name:"length",type:"uint256"}],name:"getZKPRequests",outputs:[{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getZKPRequestsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IStateCrossChain",name:"stateCrossChain",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"}],name:"isProofVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"isWhitelistedValidator",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"isZKPRequestEnabled",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pendingOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"removeValidatorFromWhitelist",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"requestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"address",name:"requestOwner",type:"address"}],name:"setRequestOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest",name:"request",type:"tuple"}],name:"setZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256[]",name:"inputs",type:"uint256[]"},{internalType:"uint256[2]",name:"a",type:"uint256[2]"},{internalType:"uint256[2][2]",name:"b",type:"uint256[2][2]"},{internalType:"uint256[2]",name:"c",type:"uint256[2]"}],name:"submitZKPResponse",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"bytes",name:"zkProof",type:"bytes"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct ZKPResponse[]",name:"responses",type:"tuple[]"},{internalType:"bytes",name:"crossChainProof",type:"bytes"}],name:"submitZKPResponseV2",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64[]",name:"requestIds",type:"uint64[]"}],name:"verifyLinkedProofs",outputs:[],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256[]",name:"inputs",type:"uint256[]"},{internalType:"uint256[2]",name:"a",type:"uint256[2]"},{internalType:"uint256[2][2]",name:"b",type:"uint256[2][2]"},{internalType:"uint256[2]",name:"c",type:"uint256[2]"},{internalType:"address",name:"sender",type:"address"}],name:"verifyZKPResponse",outputs:[{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"inputValue",type:"uint256"}],internalType:"struct ICircuitValidator.KeyToInputValue[]",name:"",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"}];var DO=[{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"address",name:"userAddress",type:"address"}],name:"areMultiRequestProofsVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"groupID",type:"uint256"}],name:"getGroupedRequests",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.RequestInfo[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getGroupsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"}],name:"getMultiRequest",outputs:[{components:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"uint256[]",name:"requestIds",type:"uint256[]"},{internalType:"uint256[]",name:"groupIds",type:"uint256[]"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.MultiRequest",name:"multiRequest",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"address",name:"userAddress",type:"address"}],name:"getMultiRequestProofsStatus",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct IVerifier.RequestProofStatus[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"}],name:"getRequest",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.RequestInfo",name:"request",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"requestId",type:"uint256"}],name:"getRequestProofStatus",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct IVerifier.RequestProofStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRequestsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"address",name:"sender",type:"address"},{internalType:"string",name:"responseFieldName",type:"string"}],name:"getResponseFieldValue",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"address",name:"sender",type:"address"}],name:"getResponseFields",outputs:[{components:[{internalType:"string",name:"name",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct IRequestValidator.ResponseField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"groupId",type:"uint256"}],name:"groupIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"requestId",type:"uint256"}],name:"isRequestProofVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"}],name:"multiRequestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"}],name:"requestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"string",name:"authMethod",type:"string"},{internalType:"contract IAuthValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"}],internalType:"struct IVerifier.AuthMethod",name:"authMethod",type:"tuple"}],name:"setAuthMethod",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"uint256[]",name:"requestIds",type:"uint256[]"},{internalType:"uint256[]",name:"groupIds",type:"uint256[]"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.MultiRequest",name:"multiRequest",type:"tuple"}],name:"setMultiRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.Request[]",name:"requests",type:"tuple[]"}],name:"setRequests",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"string",name:"authMethod",type:"string"},{internalType:"bytes",name:"proof",type:"bytes"}],internalType:"struct IVerifier.AuthResponse",name:"authResponse",type:"tuple"},{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bytes",name:"proof",type:"bytes"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.Response[]",name:"responses",type:"tuple[]"},{internalType:"bytes",name:"crossChainProofs",type:"bytes"}],name:"submitResponse",outputs:[],stateMutability:"nonpayable",type:"function"}];var TO=10000000n,iee=(r=>(r.SubmitZKPResponseV1="b68967e2",r.SubmitZKPResponseV2="ade09fcd",r.SubmitResponse="06c86a91",r))(iee||{}),oee=function(n){return[{authMethod:n.authProof.raw.authMethod,proof:n.authProof.encoded},n.proofs.map(e=>({requestId:e.requestId,proof:e.encoded,metadata:e.metadata})),n.crossChainProof.encoded]},BO=class n{constructor(e,t){this._configs=e;this._opts=t}static _supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1"];static _supportedCircuitsPubSignalsMap={credentialAtomicQueryMTPV2OnChain:_1,credentialAtomicQuerySigV2OnChain:sE,"credentialAtomicQueryV3OnChain-beta.1":iE,authV2:_s};static async prepareTxArgsSubmitV1(e,t){if(e.method_id.replace("0x","")!=="b68967e2")throw new Error("prepareTxArgsSubmitV1 function doesn't implement requested method id. Only '0xb68967e2' is supported.");let r=t.id,i=t.pub_signals,o=L0(t.proof);return[r,i,o.a,o.b,o.c]}async prepareTxArgsSubmitV1(e,t){return n.prepareTxArgsSubmitV1(e,t)}async submitZKPResponse(e,t,r){let i=this._configs.find(d=>d.chainId==t.chain_id);if(!i)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="b68967e2")throw new Error("submitZKPResponse function doesn't implement requested method id. Only '0xb68967e2' is supported.");let o=new jt(i.url,i.chainId);e=e.connect(o);let s=new Map,a=await o.getFeeData(),c=i.maxFeePerGas?BigInt(i.maxFeePerGas):a.maxFeePerGas,l=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,u=new Ln(t.contract_address,RO);for(let d of r){let h=await this.prepareTxArgsSubmitV1(t,d),f=await u.submitZKPResponse.populateTransaction(...h),p={to:t.contract_address,data:f.data,maxFeePerGas:c,maxPriorityFeePerGas:l},E;try{E=await e.estimateGas(p)}catch{E=TO}p.gasLimit=E;let b=new $s(o),{txnHash:C}=await b.sendTransactionRequest(e,p);s.set(C,d)}return s}async submitZKPResponseV2(e,t,r){let i=this._configs.find(b=>b.chainId==t.chain_id);if(!i)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="ade09fcd")throw new Error("submitZKPResponseV2 function doesn't implement requested method id. Only '0xade09fcd' is supported.");if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");let o=new jt(i.url,i.chainId);e=e.connect(o);let s=await this.prepareTxArgsSubmitV2(t,r),a=await o.getFeeData(),c=i.maxFeePerGas?BigInt(i.maxFeePerGas):a.maxFeePerGas,l=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,d=await new Ln(t.contract_address,RO).submitZKPResponseV2.populateTransaction(...s),h={to:t.contract_address,data:d.data,maxFeePerGas:c,maxPriorityFeePerGas:l},f;try{f=await e.estimateGas(h)}catch{f=TO}h.gasLimit=f;let p=new $s(o),{txnHash:E}=await p.sendTransactionRequest(e,h);return new Map().set(E,r)}async submitResponse(e,t,r,i){let o=this._configs.find(C=>C.chainId==t.chain_id);if(!o)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="06c86a91")throw new Error("submitResponse function doesn't implement requested method id. Only '0x06c86a91' is supported.");if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");let s=new jt(o.url,o.chainId);e=e.connect(s);let a=await this.prepareTxArgsSubmit(t,r,i),c=await s.getFeeData(),l=o.maxFeePerGas?BigInt(o.maxFeePerGas):c.maxFeePerGas,u=o.maxPriorityFeePerGas?BigInt(o.maxPriorityFeePerGas):c.maxPriorityFeePerGas,h=await new Ln(t.contract_address,DO).submitResponse.populateTransaction(...a.txDataArgs),f={to:t.contract_address,data:h.data,maxFeePerGas:l,maxPriorityFeePerGas:u},p;try{p=await e.estimateGas(f)}catch{p=TO}f.gasLimit=p;let E=new $s(s),{txnHash:b}=await E.sendTransactionRequest(e,f);return new Map().set(b,{authProof:a.result.authProof.raw,crossChainProof:a.result.crossChainProof.raw,responses:a.result.proofs.map(C=>C.proof)})}static async prepareTxArgsSubmit(e,t,r,i){if(t.method_id.replace("0x","")!=="06c86a91")throw new Error("submit cross chain doesn't implement requested method id. Only '0x06c86a91' is supported.");let o=[],s=[],a=[],c="0x",l="";switch(i.authMethod){case"authV2":{let f=L0(i.zkp.proof);l=QS(i.zkp.pub_signals,f.a,f.b,f.c);break}case"ethIdentity":{l=see(i.userDid);break}default:throw new Error("auth proof must use method AuthV2 or ethIdentity")}for(let f of r){this.checkSupportedCircuit(f.circuitId);let{requestId:p,zkProofEncoded:E,metadata:b}=qE(f);a.push({proof:f,requestId:p,encoded:E,metadata:b})}let u=r.map(f=>({circuitId:f.circuitId,pub_signals:f.pub_signals}));i.authMethod=="authV2"&&u.push({circuitId:i.zkp.circuitId,pub_signals:i.zkp.pub_signals});for(let f of u){let{gistUpdateResolutions:p,stateUpdateResolutions:E}=this.getUpdateResolutions(e,t.chain_id,f.circuitId,f.pub_signals);p.length>0&&o.push(...await Promise.all(p)),E.length>0&&s.push(...await Promise.all(E))}let d=o.length||s.length?this.packCrossChainProofs(o,s):c,h={authProof:{raw:i,encoded:l},proofs:a,crossChainProof:{raw:{globalStateProofs:o||[],identityStateProofs:s||[]},encoded:d}};return{result:h,txDataArgs:oee(h)}}async prepareTxArgsSubmit(e,t,r){if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");return n.prepareTxArgsSubmit(this._opts.didResolverUrl,e,t,r)}static checkSupportedCircuit(e){if(!this._supportedCircuits.includes(e))throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`)}static getCrossChainResolvers(e,t,r,i){return[...new Set(e.map(o=>JSON.stringify({id:o.id.string(),[r]:r==="gist"?o.root?.string():o.state?.string()})))].reduce((o,s)=>{let a=JSON.parse(s),c=$e.fromString(a.id),l=Qy(Se.parseFromId(c));if(t===l)return o;let u=this.resolveDidDocumentEip712MessageAndSignature(Se.parseFromId($e.fromString(a.id)),i,{[r]:be.fromString(a[r])});return[...o,u]},[])}static async prepareTxArgsSubmitV2(e,t,r){if(t.method_id.replace("0x","")!=="ade09fcd")throw new Error("submit cross chain doesn't implement requested method id. Only '0xade09fcd' is supported.");let i=[],o=[],s=[],a="0x";for(let l of r){this.checkSupportedCircuit(l.circuitId);let{requestId:u,zkProofEncoded:d,metadata:h}=qE(l);s.push({requestId:u,zkProof:d,data:h});let{gistUpdateResolutions:f,stateUpdateResolutions:p}=this.getUpdateResolutions(e,t.chain_id,l.circuitId,l.pub_signals);f.length>0&&i.push(...await Promise.all(f)),p.length>0&&o.push(...await Promise.all(p))}let c=i.length||o.length?this.packCrossChainProofs(i,o):a;return[s,c]}async prepareTxArgsSubmitV2(e,t){if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");return n.prepareTxArgsSubmitV2(this._opts.didResolverUrl,e,t)}static getUpdateResolutions(e,t,r,i){let o=this.getOnChainGistRootStatePubSignals(r,i),s=this.getCrossChainResolvers(o.gists,t,"gist",e),a=this.getCrossChainResolvers(o.states,t,"state",e);return{gistUpdateResolutions:s,stateUpdateResolutions:a}}static packCrossChainProofs(e,t){let r=[];for(let i of e)r.push({proofType:"globalStateProof",proof:this.packGlobalStateMsg(i)});for(let i of t)r.push({proofType:"stateProof",proof:this.packIdentityStateMsg(i)});return new An.AbiCoder().encode(["tuple(string proofType,bytes proof)[]"],[r])}static packGlobalStateMsg(e){return new An.AbiCoder().encode(["tuple(tuple(uint256 timestamp,bytes2 idType,uint256 root,uint256 replacedAtTimestamp) globalStateMsg,bytes signature,)"],[e])}static packIdentityStateMsg(e){return new An.AbiCoder().encode(["tuple(tuple(uint256 timestamp,uint256 id,uint256 state,uint256 replacedAtTimestamp) idStateMsg,bytes signature,)"],[e])}static getOnChainGistRootStatePubSignals(e,t){let r=this._supportedCircuitsPubSignalsMap[e];if(!r)throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`);let i=new r,o=Fe.encode(JSON.stringify(t));return i.pubSignalsUnmarshal(o),i.getStatesInfo()}static async resolveDidDocumentEip712MessageAndSignature(e,t,r){let i=await ip(e,t,{...r,signature:"EthereumEip712Signature2021"});if(!i.didResolutionMetadata.proof?.length)throw new Error("No proof found in resolved DID document");let o=i.didResolutionMetadata.proof[0].eip712.message,s=i.didResolutionMetadata.proof[0].proofValue;return r?.gist&&!r.state?{globalStateMsg:{timestamp:o.timestamp,idType:o.idType,root:o.root,replacedAtTimestamp:o.replacedAtTimestamp},signature:s}:{idStateMsg:{timestamp:o.timestamp,id:o.id,state:o.state,replacedAtTimestamp:o.replacedAtTimestamp},signature:s}}},see=n=>`0x${Lr(vt.intToBytes(Se.idFromDID(n).bigInt()))}`;var PO=[{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"},{internalType:"uint256",name:"_credentialId",type:"uint256"}],name:"getCredential",outputs:[{components:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"string[]",name:"context",type:"string[]"},{internalType:"string",name:"_type",type:"string"},{internalType:"uint64",name:"issuanceDate",type:"uint64"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.CredentialSchema",name:"credentialSchema",type:"tuple"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.DisplayMethod",name:"displayMethod",type:"tuple"}],internalType:"struct INonMerklizedIssuer.CredentialData",name:"",type:"tuple"},{internalType:"uint256[8]",name:"",type:"uint256[8]"},{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct INonMerklizedIssuer.SubjectField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCredentialAdapterVersion",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"}],name:"getUserCredentialIds",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"}];var kO=[{inputs:[],name:"CREDENTIAL_ADAPTER_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"}],name:"getClaimProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getClaimProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"}],name:"getClaimProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getClaimsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"},{internalType:"uint256",name:"_credentialId",type:"uint256"}],name:"getCredential",outputs:[{components:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"string[]",name:"context",type:"string[]"},{internalType:"string",name:"_type",type:"string"},{internalType:"uint64",name:"issuanceDate",type:"uint64"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.CredentialSchema",name:"credentialSchema",type:"tuple"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.DisplayMethod",name:"displayMethod",type:"tuple"}],internalType:"struct INonMerklizedIssuer.CredentialData",name:"",type:"tuple"},{internalType:"uint256[8]",name:"",type:"uint256[8]"},{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct INonMerklizedIssuer.SubjectField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCredentialAdapterVersion",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getIsOldStateGenesis",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedClaimsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedRevocationsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedRootsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedState",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"}],name:"getRevocationProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getRevocationProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"}],name:"getRevocationProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatus",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatusByIdAndState",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRevocationsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"rootsTreeRoot",type:"uint256"}],name:"getRootProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getRootProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"rootsTreeRoot",type:"uint256"}],name:"getRootProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"state",type:"uint256"}],name:"getRootsByState",outputs:[{components:[{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.Roots",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRootsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getSmtDepth",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"}],name:"getUserCredentialIds",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_stateContractAddr",type:"address"},{internalType:"bytes2",name:"idType",type:"bytes2"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],Gy=class{static abi=kO;static createInterface(){return new dc(kO)}static connect(e,t){return new Ln(e,kO,t)}};var ZE=class{_contract;_contractAddress;_chainId;_issuerDid;_merklizationOptions;constructor(e,t,r){if(!e.chainId)throw new Error("Chain ID is required");this._chainId=e.chainId,this._contractAddress=An.getAddress(An.hexlify($e.ethAddressFromId(Se.idFromDID(t)))),this._contract=Gy.connect(this._contractAddress,new An.JsonRpcProvider(e.url)),this._issuerDid=t,this._merklizationOptions=r?.merklizationOptions}async isInterfaceSupported(){let e=[{name:"Interface detection ERC-165",value:"0x01ffc9a7"},{name:"Interface non-merklized issuer",value:"0x58874949"},{name:"Interface get credential",value:"0x5d1ca631"}],r=(await Promise.all(e.map(async i=>await this._contract.supportsInterface(i.value)?null:i.name))).filter(i=>i!==null);if(r.length>0)throw new Error(`Unsupported interfaces: ${r.join(", ")}`)}async getCredential(e,t){let[r,i,o]=await this._contract.getCredential(e.bigInt(),t);return{credentialData:r,coreClaimBigInts:i,credentialSubjectFields:o}}async getUserCredentialsIds(e){return this._contract.getUserCredentialIds(e.bigInt())}async convertOnChainInfoToW3CCredential(e,t,r){let i=new Or().unMarshalJson(JSON.stringify(t.map(l=>l.toString()))),o=await this.convertCredentialSubject(i,e.context,e._type,r),s={id:this.credentialId(e.id),credentialSchema:e.credentialSchema.id,type:e._type,credentialSubject:o,expiration:i.getExpirationDate()?.getTime(),displayMethod:this.convertDisplayMethod(e.displayMethod),context:e.context,revocationOpts:{id:this._contractAddress,nonce:Number(i.getRevocationNonce()),type:"Iden3OnchainSparseMerkleTreeProof2023"},issuanceDate:ia(Number(e.issuanceDate)).getTime()},a=await this.existenceProof(i),c=Gr.fromCredentialRequest(this._issuerDid,s);return c.proof=[a],c}credentialId(e){return`urn:iden3:onchain:${this._chainId}:${this._contractAddress}:${e}`}async convertCredentialSubject(e,t,r,i){let o=JSON.stringify({"@context":t}),s={};for(let l of i){let u=await Ur.newTypeFromContext(o,`${r}.${l.key}`,this._merklizationOptions);switch(u){case"http://www.w3.org/2001/XMLSchema#boolean":{switch(l.rawValue.toString()){case"18586133768512220936620570745912940619677854269274689475585506675881198879027":s[l.key]=!0;break;case"19014214495641488759237505126948346942972912379615652741039992445865937985820":s[l.key]=!1;break}break}case("http://www.w3.org/2001/XMLSchema#nonNegativeInteger","http://www.w3.org/2001/XMLSchema#nonPositiveInteger","http://www.w3.org/2001/XMLSchema#negativeInteger","http://www.w3.org/2001/XMLSchema#positiveInteger"):{s[l.key]=l.value.toString();break}case"http://www.w3.org/2001/XMLSchema#integer":{s[l.key]=Number(l.value);break}case"http://www.w3.org/2001/XMLSchema#string":{this.validateSourceValue(u,l.value,l.rawValue),s[l.key]=l.rawValue;break}case"http://www.w3.org/2001/XMLSchema#dateTime":{let d=BigInt(l.rawValue),h=ia(Number(d)).toISOString();this.validateSourceValue(u,l.value,h),s[l.key]=h;break}case"http://www.w3.org/2001/XMLSchema#double":{let d=Number(l.rawValue);this.validateSourceValue(u,l.value,d),s[l.key]=d;break}default:throw new Error(`Unsupported data type ${u}`)}}s.type=r;let a=e.getId(),c=Se.parseFromId(a);return s.id=c.string(),s}async existenceProof(e){let[t,r]=await this._contract.getClaimProofWithStateInfo(e.hIndex());if(!t.existence)throw new Error("Claim does not exist");let i=be.fromBigInt(r.state),o=be.fromBigInt(r.claimsRoot),s=be.fromBigInt(r.revocationsRoot),a=be.fromBigInt(r.rootsRoot),c=new Bt({siblings:t.siblings.map(l=>be.fromBigInt(l)),existence:t.existence,nodeAux:t.auxExistence?{key:be.fromBigInt(t.auxIndex),value:be.fromBigInt(t.auxValue)}:void 0});return new mc({issuerData:{id:this._issuerDid,state:{value:i,claimsTreeRoot:o,revocationTreeRoot:s,rootOfRoots:a}},mtp:c,coreClaim:e})}async validateSourceValue(e,t,r){if(await Sl.hashValue(e,r)!==t)throw new Error(`Invalid source value for ${e} type`)}convertDisplayMethod(e){if(!(!e.id||!e._type))switch(e._type){case"Iden3BasicDisplayMethodV1":return{id:e.id,type:"Iden3BasicDisplayMethodV1"};default:throw new Error(`Unsupported display method type ${e._type}`)}}};var MO=class{_ethConnectionConfig;_onchainIssuerOptions;constructor(e,t){this._ethConnectionConfig=e,this._onchainIssuerOptions=t}async getCredential(e,t,r){let{contract:i,connection:o}=this.getContractConnection(e),s=await i.getCredentialAdapterVersion();switch(s){case"0.0.1":{let a=new ZE(o,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});await a.isInterfaceSupported();let{credentialData:c,coreClaimBigInts:l,credentialSubjectFields:u}=await a.getCredential(Se.idFromDID(t),r);return await a.convertOnChainInfoToW3CCredential(c,l,u)}default:throw new Error(`Unsupported adapter version ${s}`)}}async getUserCredentialIds(e,t){let{contract:r,connection:i}=this.getContractConnection(e),o=await r.getCredentialAdapterVersion();switch(o){case"0.0.1":{let s=new ZE(i,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});return await s.isInterfaceSupported(),await s.getUserCredentialsIds(Se.idFromDID(t))}default:throw new Error(`Unsupported adapter version ${o}`)}}getContractConnection(e){let t=Se.idFromDID(e),r=Qy(e),i=An.getAddress(An.hexlify($e.ethAddressFromId(t))),o=this._ethConnectionConfig.find(a=>a.chainId===r);if(!o)throw new Error(`No connection found for chain ID ${r}`);if(!o.url)throw new Error(`No URL found for chain ID ${r}`);return{contract:new Ln(i,PO,new An.JsonRpcProvider(o.url)),connection:o}}};var OO=class{constructor(e){this.resolverUrl=e}async getLatestStateById(e){return this.getStateInfo(e)}async getStateInfoByIdAndState(e,t){return this.getStateInfo(e,t)}async getGISTProof(e){let{didDocument:t}=await ip(Se.parseFromId($e.fromBigInt(e)),this.resolverUrl),{global:r}=this.getIden3StateInfo2023(t);if(!r)throw new Error("GIST root not found");let{proof:i}=r;if(!i)throw new Error("GIST proof not found");return{root:r.root,existence:i.existence,siblings:i.siblings?.map(o=>BigInt(o)),index:BigInt(0),value:BigInt(0),auxExistence:!!i.node_aux,auxIndex:i.node_aux?BigInt(i.node_aux.key):BigInt(0),auxValue:i.node_aux?BigInt(i.node_aux.value):BigInt(0)}}async getGISTRootInfo(e,t){let{didDocument:r}=await ip(Se.parseFromId($e.fromBigInt(t)),this.resolverUrl,{gist:be.fromBigInt(e)}),{global:i}=this.getIden3StateInfo2023(r);if(!i)throw new Error("GIST root not found");return i}getRpcProvider(){return new jt}publishState(){throw new Error("publishState method not implemented.")}publishStateGeneric(){throw new Error("publishStateGeneric method not implemented.")}async getStateInfo(e,t){let r=t?{state:be.fromBigInt(t)}:void 0,{didDocument:i}=await ip(Se.parseFromId($e.fromBigInt(e)),this.resolverUrl,r),{info:o,published:s}=this.getIden3StateInfo2023(i);if(!o&&!s)throw new Error(qe.ERRORS.STATE_DOES_NOT_EXIST);if(!o)throw new Error("State info not found");return o.id=e,o.state=r?.state?.bigInt(),{...o}}getIden3StateInfo2023(e){let t=e.verificationMethod?.find(r=>r.type==="Iden3StateInfo2023");if(!t)throw new Error("Iden3StateInfo2023 verification method not found");return t}};var aee=[{inputs:[],name:"ECDSAInvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"length",type:"uint256"}],name:"ECDSAInvalidSignatureLength",type:"error"},{inputs:[{internalType:"bytes32",name:"s",type:"bytes32"}],name:"ECDSAInvalidSignatureS",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"allowance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientAllowance",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC20InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC20InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC20InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"}],name:"ERC20InvalidSpender",type:"error"},{inputs:[{internalType:"uint256",name:"deadline",type:"uint256"}],name:"ERC2612ExpiredSignature",type:"error"},{inputs:[{internalType:"address",name:"signer",type:"address"},{internalType:"address",name:"owner",type:"address"}],name:"ERC2612InvalidSigner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"currentNonce",type:"uint256"}],name:"InvalidAccountNonce",type:"error"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[],name:"DOMAIN_SEPARATOR",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"nonces",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],name:"permit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];var cee=[{inputs:[{internalType:"uint256",name:"initialSupply",type:"uint256"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"allowance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientAllowance",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC20InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC20InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC20InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"}],name:"ERC20InvalidSpender",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];async function oRe(n,e,t,r,i){let o=new Ln(e,aee,n),s=await o.nonces(await n.getAddress()),a=await o.eip712Domain(),c={name:a[1],version:a[2],chainId:a[3],verifyingContract:e},l={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:await n.getAddress(),spender:t,value:r,nonce:s,deadline:i};return n.signTypedData(c,l,u)}async function sRe(n,e){return new Ln(n,cee,e).decimals()}var pee=(t=>(t.NotDefinedQueryKey="not defined query key",t.NotDefinedComparator="not defined comparator",t))(pee||{}),mee=(o=>(o[o.BigInt=0]="BigInt",o[o.Boolean=1]="Boolean",o[o.Double=2]="Double",o[o.DateTime=3]="DateTime",o[o.String=4]="String",o))(mee||{}),FO=[!0,1,"true"],NO=[!1,0,"false"],lee=(n,e)=>Array.isArray(n)&&Array.isArray(e)?n.length===e.length&&n.every((t,r)=>t===e[r]):!Array.isArray(n)&&Array.isArray(e)?e.includes(n):Array.isArray(n)&&!Array.isArray(e)?n.includes(e):(n=n,e=e,FO.includes(n)&&FO.includes(e)||NO.includes(n)&&NO.includes(e)?!0:n===e),uee=(n,e)=>yee(n,e,(r,i)=>{switch(wee(r.toString())){case 0:case 1:return BigInt(r)>BigInt(i);case 3:return Date.parse(r.toString())>Date.parse(i.toString());case 2:case 4:default:return r>i}}),dee=(n,e)=>yee(n,e,(r,i)=>{switch(wee(r.toString())){case 0:case 1:return BigInt(r)>=BigInt(i);case 3:return Date.parse(r.toString())>=Date.parse(i.toString());case 2:case 4:default:return r>=i}}),aRe=(n,e)=>!!(FO.includes(e)&&typeof n<"u"||NO.includes(e)&&(n===void 0||Array.isArray(n)&&!n.length)),fee=(n,e)=>Array.isArray(n)&&Array.isArray(e)?n.every(t=>e.includes(t)):!Array.isArray(n)&&Array.isArray(e)?e.includes(n):Array.isArray(n)&&!Array.isArray(e)?n.includes(e):!1,hee=(n,e)=>{if(!Array.isArray(e)||e.length!==2)throw new Error("$between/$nonbetween operator value should be 2 elements array");let[t,r]=e.map(BigInt),i=o=>o>=t&&o<=r;return Array.isArray(n)?n.map(BigInt).every(i):i(BigInt(n))},Ul={$noop:()=>!0,$sd:()=>!0,$exists:(n,e)=>aRe(n,e),$eq:(n,e)=>lee(n,e),$in:(n,e)=>fee(n,e),$nin:(n,e)=>!fee(n,e),$gt:(n,e)=>uee(n,e),$lt:(n,e)=>!dee(n,e),$ne:(n,e)=>!lee(n,e),$gte:(n,e)=>dee(n,e),$lte:(n,e)=>!uee(n,e),$between:(n,e)=>hee(n,e),$nonbetween:(n,e)=>!hee(n,e)},gee=(n,e,t=null)=>{let r=e.split("."),i=n;for(let o of r){if(i==null)return t;i=i[o]}return i},Fc=class{constructor(e,t,r,i=!1){this.path=e;this.operatorFunc=t;this.value=r;this.isReverseParams=i}execute(e){if(!this.operatorFunc)throw new Error("not defined comparator");let t=gee(e,this.path);return t==null&&this.operatorFunc!==Ul.$exists?!1:this.isReverseParams?this.operatorFunc(this.value,t):this.operatorFunc(t,this.value)}},UO=n=>Object.keys(n).reduce((e,t)=>{let r=n[t];switch(t){case"claimId":return e.concat(new Fc("id",Ul.$eq,r));case"allowedIssuers":return(r||["*"]).includes("*")?e:e.concat(new Fc("issuer",Ul.$in,r));case"type":return e.concat(new Fc("type",Ul.$in,r,!0));case"context":return e.concat(new Fc("@context",Ul.$in,r,!0));case"credentialSubjectId":return e.concat(new Fc("credentialSubject.id",Ul.$eq,r));case"schema":return e.concat(new Fc("credentialSchema.id",Ul.$eq,r));case"credentialSubject":{let i=Object.keys(r).reduce((o,s)=>{let a=r[s];if(typeof a=="object"&&Object.keys(a).length===0)return o.concat([new Fc(`credentialSubject.${s}`,Ul.$noop,null)]);let c=Object.keys(a).map(l=>{let u=a[l],d=`credentialSubject.${s}`;return new Fc(d,Ul[l],u)});return o.concat(c)},[]);return e.concat(i)}case"proofType":case"groupId":case"skipClaimRevocationCheck":return e;default:throw new Error(`${t} : not defined query key`)}},[]),yee=(n,e,t)=>Array.isArray(n)&&Array.isArray(e)?n.every((r,i)=>t(r,e[i])):!Array.isArray(n)&&Array.isArray(e)?e.every(r=>t(n,r)):Array.isArray(n)&&!Array.isArray(e)?n.every(r=>t(r,e)):t(n,e),cRe=/^[+-]?\d+$/,lRe=/^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$/,uRe=/^([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))$/,dRe=/^(true)|(false)$/,fRe=/^\d{4}-\d{2}-\d{2}$/,wee=n=>cRe.test(n)?0:lRe.test(n)?2:uRe.test(n)||fRe.test(n)?3:dRe.test(n)?1:4;var GO=class{constructor(e){this._localStorageKey=e;localStorage.getItem(this._localStorageKey)||localStorage.setItem(e,JSON.stringify([]))}async save(e,t,r="id"){if(localStorage){let i=localStorage.getItem(this._localStorageKey),o=[];i&&(o=JSON.parse(i));let s=o.findIndex(a=>a[r]===e);s===-1?o.push(t):o[s]=t,localStorage.setItem(this._localStorageKey,JSON.stringify(o))}}async get(e,t="id"){let r=localStorage.getItem(this._localStorageKey),i=[];return r&&(i=JSON.parse(r)),i.find(o=>o[t]===e)}async load(){let e=localStorage.getItem(this._localStorageKey);return e&&JSON.parse(e)}async delete(e,t="id"){let r=localStorage.getItem(this._localStorageKey),i=[];r&&(i=JSON.parse(r));let o=i.filter(s=>s[t]!==e);if(i.length===o.length)throw new Error(`item not found to delete: ${e}`);localStorage.setItem(this._localStorageKey,JSON.stringify(o))}};var KO=class n{constructor(e){this._mtDepth=e}static storageKeyMeta="merkle-tree-meta";async createIdentityMerkleTrees(e){e||(e=`${Ft()}`);let t=localStorage.getItem(n.storageKeyMeta);if(t){let i=JSON.parse(t);if(i.find(c=>c.treeId===`${e}+${c.type}`))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let s=i.filter(c=>c.identifier===e);if(s.length>0)return s;let a=dE(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify([...i,...a])),[...i,...a]}let r=dE(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify(r)),r}async getIdentityMerkleTreesInfo(e){let t=localStorage.getItem(n.storageKeyMeta);if(t)return JSON.parse(t).filter(i=>i.identifier===e);throw new Error(`Merkle tree meta not found for identifier ${e}`)}async getMerkleTreeByIdentifierAndType(e,t){let r=this.getMeta(e,t);return new aa(new $y(Vc(r.treeId)),!0,this._mtDepth)}getMeta(e,t){let r=localStorage.getItem(n.storageKeyMeta),i=new Error(`Merkle tree not found for identifier ${e} and type ${t}`);if(!r)throw i;let s=JSON.parse(r).filter(a=>a.identifier===e&&a.type===t)[0];if(!s)throw i;return s}async addToMerkleTree(e,t,r,i){let o=this.getMeta(e,t);await new aa(new $y(Vc(o.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=localStorage.getItem(n.storageKeyMeta);if(!r)throw new Error(`Merkle tree meta not found for identifier ${e}`);let i=JSON.parse(r),o=i.filter(a=>a.identifier===e).map(a=>({...a,identifier:t}));if(o.length===0)throw new Error(`Merkle tree meta not found for identifier ${e}`);let s=[...i.filter(a=>a.identifier!==e),...o];localStorage.setItem(n.storageKeyMeta,JSON.stringify(s))}};var HO=class{constructor(e){this._storageKey=e;this._store=Ad(`${e}-db`,e)}_store;async save(e,t,r="id"){return xd(e,t,this._store)}async get(e,t="id"){return Jc(e,this._store)}async load(){return JF(this._store)}async delete(e,t="id"){return bI(e,this._store)}};var JO=class n{constructor(e){this._mtDepth=e;this._merkleTreeMetaStore=Ad(`${n.storageKeyMeta}-db`,n.storageKeyMeta),this._bindingStore=Ad(`${n.storageBindingKeyMeta}-db`,n.storageBindingKeyMeta)}static storageKeyMeta="merkle-tree-meta";static storageBindingKeyMeta="binding-did";_merkleTreeMetaStore;_bindingStore;async createIdentityMerkleTrees(e){if(e||(e=`${Ft()}`),await Jc(e,this._bindingStore))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let r=dE(e);return await xd(e,r,this._merkleTreeMetaStore),r}async getIdentityMerkleTreesInfo(e){let t=await Jc(e,this._merkleTreeMetaStore);if(t)return t;throw new Error(`Merkle tree meta not found for identifier ${e}`)}async getMerkleTreeByIdentifierAndType(e,t){let r=await Jc(e,this._merkleTreeMetaStore),i=new Error(`Merkle tree not found for identifier ${e} and type ${t}`);if(!r)throw i;let o=r.find(s=>s.identifier===e&&s.type===t);if(!o)throw i;return new aa(new ew(Vc(o.treeId)),!0,this._mtDepth)}async addToMerkleTree(e,t,r,i){let o=await Jc(e,this._merkleTreeMetaStore);if(!o)throw new Error(`Merkle tree meta not found for identifier ${e}`);let s=o.find(c=>c.identifier===e&&c.type===t);if(!s)throw new Error(`Merkle tree not found for identifier ${e} and type ${t}`);await new aa(new ew(Vc(s.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=await Jc(e,this._merkleTreeMetaStore);if(!r||!r?.length)throw new Error(`Merkle tree meta not found for identifier ${e}`);let i=r.map(o=>({...o,identifier:t}));await bI(e,this._merkleTreeMetaStore),await xd(t,i,this._merkleTreeMetaStore),await xd(e,t,this._bindingStore)}};var qO=class{constructor(e){this._dataSource=e}static storageKey="circuits";async loadCircuitData(e){let t=await this._dataSource.get(e.toString(),"circuitId");if(!t)throw new Error(`item not found: ${e}`);return t}async saveCircuitData(e,t){await this._dataSource.save(e.toString(),t,"circuitId")}};var VO=class{constructor(e){this._dataSource=e}static storageKey="credentials";async listCredentials(){return(await this._dataSource.load()).filter(t=>t!==void 0).map(t=>t&&Gr.fromJSON(t))}async saveCredential(e){return this._dataSource.save(e.id,e.toJSON())}async saveAllCredentials(e){for(let t of e)await this.saveCredential(t)}async removeCredential(e){return this._dataSource.delete(e)}async findCredentialById(e){let t=await this._dataSource.get(e);return t&&Gr.fromJSON(t)}async findCredentialsByQuery(e){let t=UO(e);return(await this._dataSource.load()).filter(o=>t.every(s=>s.execute(o))).filter(o=>o!==void 0).map(o=>Gr.fromJSON(o))}};var QO=class{constructor(e,t){this._identityDataSource=e;this._profileDataSource=t}static identitiesStorageKey="identities";static profilesStorageKey="profiles";async saveProfile(e){let r=(await this._profileDataSource.load()).filter(o=>o.genesisIdentifier===e.genesisIdentifier),i=r.length?[...r,e]:[e];for(let o=0;o<i.length;o++){let s=i[o];await this._profileDataSource.save(s.id,s)}}async getProfileByVerifier(e){return this._profileDataSource.get(e,"verifier")}async getProfilesByVerifier(e,t){return(await this._profileDataSource.load()).filter(r=>r.verifier===e&&(!t||t.every(i=>r.tags?.includes(i))))}async getProfileById(e){return this._profileDataSource.get(e)}async getProfilesByGenesisIdentifier(e){return(await this._profileDataSource.load()).filter(t=>t.genesisIdentifier===e)}async getAllIdentities(){return this._identityDataSource.load()}async saveIdentity(e){return this._identityDataSource.save(e.did,e,"did")}async getIdentity(e){return this._identityDataSource.get(e,"did")}};var zO=class{constructor(e){this.opts=e;this._verificationKeyPath=this.opts.verificationFileName??this._verificationKeyPath,this._provingKeyPath=this.opts.provingFileName??this._provingKeyPath,this._wasmFilePath=this.opts.wasmFileName??this._wasmFilePath}_verificationKeyPath="verification_key.json";_provingKeyPath="circuit_final.zkey";_wasmFilePath="circuit.wasm";_fs=null;_browserNotSupportedError=new Error("File system operations are not supported in browser environment");async getFs(){return this._fs?this._fs:(this._fs={existsSync:()=>{throw this._browserNotSupportedError},readFileSync:()=>{throw this._browserNotSupportedError},writeFileSync:()=>{throw this._browserNotSupportedError},mkdirSync:()=>{throw this._browserNotSupportedError}},this._fs)}async loadCircuitData(e){let t=await this.loadCircuitFile(e,this._verificationKeyPath),r=await this.loadCircuitFile(e,this._provingKeyPath),i=await this.loadCircuitFile(e,this._wasmFilePath);return{circuitId:e,wasm:i,provingKey:r,verificationKey:t}}async loadCircuitFile(e,t){let r=`${this.opts.dirname}/${e}/${t}`,i=await this.getFs();if(i.existsSync(r)){let o=i.readFileSync(r);return new Uint8Array(o)}return null}async writeCircuitFile(e,t,r,i){let o=`${this.opts.dirname}/${e}`,s=`${o}/${t}`,a=await this.getFs();a.mkdirSync(o,{recursive:!0}),a.writeFileSync(s,r,i)}async saveCircuitData(e,t){t.verificationKey&&await this.writeCircuitFile(e,this._verificationKeyPath,t.verificationKey,"utf-8"),t.provingKey&&await this.writeCircuitFile(e,this._provingKeyPath,t.provingKey),t.wasm&&await this.writeCircuitFile(e,this._wasmFilePath,t.wasm)}};var Gl=n=>{if(!n){let e=Nn.hash(new Array(3).fill(0n));return{proof:new Bt,treeState:{state:be.fromBigInt(e),claimsRoot:Ue,revocationRoot:Ue,rootOfRoots:Ue}}}return{proof:n.mtp,treeState:b5(n.issuer.state,n.issuer.claimsTreeRoot,n.issuer.revocationTreeRoot,n.issuer.rootOfRoots)}},lh=n=>{let e=!1,t;n.existence?e=!0:n.auxExistence&&(t={key:be.fromBigInt(n.auxIndex),value:be.fromBigInt(n.auxValue)});let r=n.siblings.map(s=>be.fromBigInt(s)),i=new Bt({siblings:r,nodeAux:t,existence:e});return{root:be.fromBigInt(n.root),proof:i}},QC=n=>{if(!n)return[{operator:dn.$noop,fieldName:""}];let e=[],t=Object.entries(n);if(!t.length)throw new Error("query must have at least 1 predicate");for(let[r,i]of t){let o=Object.entries(i);if(o.length===0){e.push({operator:dn.$sd,fieldName:r});continue}for(let[a,c]of o){if(!dn[a])throw new Error("operator is not supported by lib");let l=dn[a];e.push({operator:l,fieldName:r,operatorValue:c})}}return e},zC=async(n,e,t,r)=>{let i={...n,slotIndex:0,merklizedSchema:!1,datatype:"",claimPathKey:BigInt(0),values:[],path:new Ur};if(!n.fieldName&&n.operator!==0)throw new Error("query must have a field name if operator is not $noop");if(n.fieldName&&(i.datatype=await Ur.newTypeFromContext(e,`${t}.${n.fieldName}`,r)),await x2(JSON.parse(e),r,t)||(i.merklizedSchema=!0),!i.merklizedSchema)i.slotIndex=await A2(n.fieldName,t,Fe.encode(e));else try{let s=await UT(e,t,n.fieldName,r);i.claimPathKey=await s.mtEntry(),i.path=s}catch(s){throw new Error(`field does not exist in the schema ${s.message}`)}if(n.operatorValue!==void 0){if(!I5(i.datatype,n.operator))throw new Error(`operator ${n.operator} is not supported for datatype ${i.datatype}`);if((n.operator===0||n.operator===16)&&n.operatorValue)throw new Error(`operator value should be undefined for ${n.operator} operator`);let s;switch(n.operator){case 0:case 16:s=[];break;case 11:s=hRe(n.operatorValue);break;default:s=await YC(n.operatorValue,i.datatype)}i.values=s}return i},XE=async(n,e,t,r)=>{let i=QC(t);return Promise.all(i.map(o=>zC(o,e,n,r)))},YC=async(n,e)=>{let t=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)t[r]=await Sl.hashValue(e,n[r]);else t[0]=await Sl.hashValue(e,n);return t},hRe=n=>{if(typeof n=="boolean")return[BigInt(n)];throw new Error("exists operator value must be true or false")};async function WO(n,e){e=e||{};let t;try{t=await WebAssembly.compile(n)}catch(u){throw new Error(u)}let r="",i="",o=await WebAssembly.instantiate(t,{runtime:{exceptionHandler:function(u){let d;throw u==1?d=`Signal not found.
|
|
424
424
|
`:u==2?d=`Too many signals set.
|
|
425
425
|
`:u==3?d=`Signal already set.
|
|
426
426
|
`:u==4?d=`Assert Failed.
|